lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
b037b1aa2dc40086df00aa61ca1ba3a03370680d
0
vital-ai/beaker-notebook,vital-ai/beaker-notebook,vital-ai/beaker-notebook,ScottPJones/beaker-notebook,ScottPJones/beaker-notebook,vital-ai/beaker-notebook,ScottPJones/beaker-notebook,ScottPJones/beaker-notebook,vital-ai/beaker-notebook,vital-ai/beaker-notebook,ScottPJones/beaker-notebook,vital-ai/beaker-notebook
/* * Copyright 2014 TWO SIGMA OPEN SOURCE, LLC * * 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.twosigma.beaker.jvm.object; import java.util.List; public class OutputContainerCell extends OutputContainer { public OutputContainerCell() { } public OutputContainerCell(List<Object> items) { super(items); } public OutputContainerCell(List<Object> items, List<String> labels) { super(items, labels); } public OutputContainer leftShift(Object item) { addItem(item); return this; } }
plugin/jvm/src/main/java/com/twosigma/beaker/jvm/object/OutputContainerCell.java
/* * Copyright 2014 TWO SIGMA OPEN SOURCE, LLC * * 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.twosigma.beaker.jvm.object; import java.util.List; public class OutputContainerCell extends OutputContainer { public OutputContainerCell() { } public OutputContainerCell(List<Object> items) { super(items); } public OutputContainerCell(List<Object> items, List<String> labels) { super(items, labels); } }
#3267 - Implements Groovys left shifting into containers
plugin/jvm/src/main/java/com/twosigma/beaker/jvm/object/OutputContainerCell.java
#3267 - Implements Groovys left shifting into containers
<ide><path>lugin/jvm/src/main/java/com/twosigma/beaker/jvm/object/OutputContainerCell.java <ide> public OutputContainerCell(List<Object> items, List<String> labels) { <ide> super(items, labels); <ide> } <add> <add> public OutputContainer leftShift(Object item) { <add> addItem(item); <add> return this; <add> } <ide> }
Java
apache-2.0
964ab18ebe833a5c2902faac77e1c8ad97873fa7
0
wecoderBao/starjobs,wecoderBao/starjobs,wecoderBao/starjobs,wecoderBao/starjobs
/** * */ package io.rong.service.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.starjobs.common.StarConstants; import com.starjobs.mapper.TCompanyInfoMapper; import com.starjobs.mapper.TFriendMapper; import com.starjobs.mapper.TGroupMapper; import com.starjobs.mapper.TGroupMemberMapper; import com.starjobs.mapper.TUserInfoMapper; import com.starjobs.pojo.TCompanyInfo; import com.starjobs.pojo.TFriend; import com.starjobs.pojo.TGroup; import com.starjobs.pojo.TGroupMember; import com.starjobs.pojo.TGroupMemberExample; import com.starjobs.pojo.TUserInfo; import io.rong.RongCloud; import io.rong.messages.ContactNtfMessage; import io.rong.messages.GroupNtfMessage; import io.rong.models.CodeSuccessResult; import io.rong.models.TokenResult; import io.rong.service.RongCloudService; import io.rong.util.RongConstants; /** * <p> * Title:RongCloudServiceImpl * </p> * <p> * Description: * </p> * * @author:bao * @date:2017年6月7日下午11:04:47 */ @Service public class RongCloudServiceImpl implements RongCloudService { @Autowired TFriendMapper tFriendMapper; @Autowired TUserInfoMapper tUserInfoMapper; @Autowired TCompanyInfoMapper tCompanyInfoMapper; @Autowired TGroupMapper tGroupMapper; @Autowired TGroupMemberMapper tGroupMemberMapper; /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#getToken() */ public Map<String, Object> getToken(String phoneNum, String name, String portraitUri) { if (StringUtils.isEmpty(name)) { name = "Tom"; } if (StringUtils.isEmpty(portraitUri)) { portraitUri = "http://www.rongcloud.cn/images/logo.png"; } try { TokenResult userGetTokenResult = RongCloud.getInstance(RongConstants.RONG_APP_KEY, RongConstants.RONG_APP_SECRET).user.getToken(phoneNum, name, portraitUri); Map<String, Object> result = new HashMap<String, Object>(); result.put("code", userGetTokenResult.getCode().toString()); result.put("rongToken", userGetTokenResult.getToken()); result.put("userId", userGetTokenResult.getUserId()); return result; } catch (Exception e) { e.printStackTrace(); return null; } } /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#addFriend(java.lang.String, * java.lang.String, java.lang.String, java.lang.String) */ public Map<String, Object> addFriend(String fromUserId, String toUserId, String content, String pushContent) { // 将标识排序,做小右大 Long fid = Long.parseLong(fromUserId); Long tid = Long.parseLong(toUserId); String cuid = fromUserId; String cfid = toUserId; if (fid.equals(tid)) return null;// 自己和自己不能成为好友 if (fid > tid) { cuid = toUserId; cfid = fromUserId; } // 检查是否已经是好友 TFriend friend = tFriendMapper.selectByUserId(cuid, cfid); // 检查好友状态 if (null != friend && !friend.getcState().equals("0")) { return null;// 已经添加过或者是好友 } if (null == friend) { friend = new TFriend(); friend.setcUid(cuid); friend.setcFid(cfid); friend.setcState(fromUserId); tFriendMapper.insert(friend);// 添加好友 } else { friend.setcState(fromUserId);// 修改状态为请求待确认 tFriendMapper.updateByPrimaryKey(friend); } String[] toUserIds = { toUserId }; ContactNtfMessage ntfMessage = new ContactNtfMessage("add friend", "extra", fromUserId, toUserId, pushContent); try { CodeSuccessResult result = RongCloud.getInstance(RongConstants.RONG_APP_KEY, RongConstants.RONG_APP_SECRET).message.PublishSystem(fromUserId, toUserIds, ntfMessage, pushContent, null, 1, 1); if (null != result) { Map<String, Object> data = new HashMap<String, Object>(); data.put("code", result.getCode().toString()); return data; } return null; } catch (Exception e) { e.printStackTrace(); return null; } } /* * (non-Javadoc) * * @see * io.rong.service.RongCloudService#confirmFriendAdded(java.lang.String, * java.lang.String) */ public Map<String, Object> confirmFriendAdded(String fromUserId, String toUserId) { // 将标识排序,做小右大 Long fid = Long.parseLong(fromUserId); Long tid = Long.parseLong(toUserId); String cuid = fromUserId; String cfid = toUserId; if (fid.equals(tid)) return null;// 自己和自己不能成为好友 if (fid > tid) { cuid = toUserId; cfid = fromUserId; } // 检查是否已经是好友 TFriend friend = tFriendMapper.selectByUserId(cuid, cfid); if (friend == null) {// 记录必须存在 return null; } if (friend.equals("0")) { return null;// 陌生人 } if (null != friend && friend.equals("2")) { return null;// 已经是好友 } friend.setcState("2");// 成为好友 tFriendMapper.updateByPrimaryKey(friend);// 添加好友 // 向融云发送通知信息 String[] toUserIds = { toUserId }; String content = "" + fromUserId + "与" + toUserId + "成为好友"; ContactNtfMessage ntfMessage = new ContactNtfMessage("confirm friend_added", "extra", fromUserId, toUserId, content); try { CodeSuccessResult result = RongCloud.getInstance(RongConstants.RONG_APP_KEY, RongConstants.RONG_APP_SECRET).message.PublishSystem(fromUserId, toUserIds, ntfMessage, null, null, 1, 1); if (null != result) { Map<String, Object> data = new HashMap<String, Object>(); data.put("code", result.getCode().toString()); return data; } return null; } catch (Exception e) { e.printStackTrace(); return null; } } /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#lookFriend(java.lang.String) */ public Map<String, Object> lookFriend(String userPhone, String phoneNum) { // 将标识排序,做小右大 Long fid = Long.parseLong(userPhone); Long tid = Long.parseLong(phoneNum); String cuid = userPhone; String cfid = phoneNum; if (fid.equals(tid)) return null;// 自己和自己不能成为好友 if (fid > tid) { cuid = phoneNum; cfid = userPhone; } // 检查是否已经是好友 TFriend friend = tFriendMapper.selectByUserId(cuid, cfid); String state = "0";// 陌生人 if (null != friend) { state = friend.getcState(); } // 根据手机号查找用户 TUserInfo userInfo = tUserInfoMapper.selectByPhone(phoneNum.trim()); Map<String, Object> resultMap = new HashMap<String, Object>(); if (null != userInfo) { resultMap.put("friendName", userInfo.getcUserNickname()); resultMap.put("friendPicUrl", StarConstants.USER_IMG_URL+userInfo.getcUserImg()); resultMap.put("friendPhoneNum", userInfo.getcUserPhone()); resultMap.put("state", state); return resultMap; } // 普通用户不存在,查找公司用户 TCompanyInfo comInfo = tCompanyInfoMapper.selectByPhone(phoneNum.trim()); if (null != comInfo) { resultMap.put("friendName", comInfo.getcComName()); resultMap.put("friendPicUrl", StarConstants.COM_IMG_URL+comInfo.getcComHeadImg()); resultMap.put("friendPhoneNum", comInfo.getcComPhone()); resultMap.put("state", state); return resultMap; } // 都没找到 return null; } public Map<String, Object> readFriends(String phoneNum) { // 根据手机号查找好友,本人在左侧 List<TFriend> leftList = tFriendMapper.selectByUid(phoneNum); Map<String, Object> result = new HashMap<String, Object>(); List<Map<String, Object>> friendList = new ArrayList<Map<String, Object>>(); if (null != leftList && leftList.size() > 0) { for (TFriend tf : leftList) { TUserInfo info = tUserInfoMapper.selectByPhone(tf.getcFid()); if (info != null && tf.getcState().equals("2")) {// 好友 Map<String, Object> fr = new HashMap<String, Object>(3); fr.put("friendName", info.getcUserNickname()); fr.put("friendPicUrl", info.getcUserImg()); fr.put("friendPhoneNum", info.getcUserPhone()); friendList.add(fr); } } } // 查找好友,本人在右侧 List<TFriend> rightList = tFriendMapper.selectByFid(phoneNum); if (null != rightList && rightList.size() > 0) { for (TFriend tf : rightList) { TUserInfo info = tUserInfoMapper.selectByPhone(tf.getcUid()); if (info != null && tf.getcState().equals("2")) {// 好友 Map<String, Object> fr = new HashMap<String, Object>(3); fr.put("friendName", info.getcUserNickname()); fr.put("friendPicUrl", info.getcUserImg()); fr.put("friendPhoneNum", info.getcUserPhone()); friendList.add(fr); } } } result.put("friendList", friendList); return result; } /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#createGroup(java.lang.String, * java.lang.String) */ public Map<String, Object> createGroup(String userId, String groupName, String jobId) { RongCloud rongCloud = RongCloud.getInstance(RongConstants.RONG_APP_KEY, RongConstants.RONG_APP_SECRET); String[] groupCreateUserId = { userId }; Map<String, Object> result = new HashMap<String, Object>(); try { TCompanyInfo comInfo = tCompanyInfoMapper.selectByPhone(userId); String comHeadImg = comInfo.getcComHeadImg(); comHeadImg = (comHeadImg==null?"default.png":comHeadImg); // 保存群组 TGroup group = new TGroup(); group.setcGroupCreaterId(userId); group.setcGroupHeadImg(comHeadImg); group.setcGroupName(groupName); group.setcGroupStatu("1"); group.setcJobId(jobId); tGroupMapper.insertSelective(group); // 保存群组成员 TGroupMember member = new TGroupMember(); member.setcGroupId(group.getcGroupId());// 所在群组id member.setcGroupMemberId(userId);// 成员手机号 member.setcGroupMemberIdentity("0");// 群主标识 tGroupMemberMapper.insertSelective(member); CodeSuccessResult groupCreateResult = rongCloud.group.create(groupCreateUserId, String.valueOf(group.getcGroupId()), groupName); System.out.println("--" + groupCreateResult.toString()); if (groupCreateResult != null && groupCreateResult.getCode() == 200) { String[] messagePublishGroupToGroupId = { String.valueOf(group.getcGroupId()) }; Map<String, Object> data = new HashMap<String, Object>(); data.put("operatorNickname", userId); data.put("targetGroupName", groupName); GroupNtfMessage groupMessage = new GroupNtfMessage(userId, "Create", data, "创建群组:" + groupName, "创建群组:" + groupName); CodeSuccessResult messagePublishGroupResult = rongCloud.message.publishGroup(userId, messagePublishGroupToGroupId, groupMessage, "创建群组:" + groupName, "{\"pushData\":\"" + "创建群组:" + groupName + "\"}", 1, 1, 1); System.out.println("--2--" + messagePublishGroupResult.toString()); if (messagePublishGroupResult.getCode() == 200) { group.setcGroupStatu("0");// 创建成功群组激活 tGroupMapper.updateByPrimaryKey(group); result.put("code", "200"); return result; } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#joinGroup(java.lang.String, * java.lang.String, java.lang.String) */ public Map<String, Object> joinGroup(String userId, String groupId, String groupName) { RongCloud rongCloud = RongCloud.getInstance(RongConstants.RONG_APP_KEY, RongConstants.RONG_APP_SECRET); // 将用户加入指定群组,用户将可以收到该群的消息,同一用户最多可加入 500 个群,每个群最大至 3000 人。 String[] groupJoinUserId = userId.split(";"); Map<String, Object> result = new HashMap<String, Object>(); // 获取融云端群组id TGroup group = tGroupMapper.selectByPrimaryKey(Integer.parseInt(groupId)); if (group == null) { return null; } try { CodeSuccessResult groupJoinResult = rongCloud.group.join(groupJoinUserId, String.valueOf(group.getcGroupId()), groupName); if (groupJoinResult != null && groupJoinResult.getCode() == 200) { // 添加群成员记录 // todo TGroupMember member = new TGroupMember(); member.setcGroupId(Integer.parseInt(groupId));// 所在群组id member.setcGroupMemberId(userId);// 成员手机号 member.setcGroupMemberIdentity("1");// 群主标识 tGroupMemberMapper.insertSelective(member); result.put("code", "200"); String[] messagePublishGroupToGroupId = { String.valueOf(group.getcGroupId()) }; Map<String, Object> data = new HashMap<String, Object>(); data.put("operatorNickname", userId); String[] targetUserIds = { userId }; data.put("targetUserIds", targetUserIds); data.put("operatorNickname", userId); TUserInfo userInfo = tUserInfoMapper.selectByPhone(userId); GroupNtfMessage groupMessage = new GroupNtfMessage(userId, "Add", data, userInfo.getcUserNickname()+" 加入群组", userInfo.getcUserNickname()+" 加入群组"); CodeSuccessResult messagePublishGroupResult = rongCloud.message.publishGroup(userId, messagePublishGroupToGroupId, groupMessage, "加入群组:" + groupName, "{\"pushData\":\"" + "加入群组:" + groupName + "\"}", 1, 1, 1); return result; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#dismissGroup(java.lang.String, * java.lang.String) */ public Map<String, Object> dismissGroup(String userId, String groupId) { // 解散群组方法。(将该群解散,所有用户都无法再接收该群的消息。) RongCloud rongCloud = RongCloud.getInstance(RongConstants.RONG_APP_KEY, RongConstants.RONG_APP_SECRET); Map<String, Object> result = new HashMap<String, Object>(); // 获取融云端群组id TGroup group = tGroupMapper.selectByPrimaryKey(Integer.parseInt(groupId)); if (group == null) { return null; } try { CodeSuccessResult groupDismissResult = rongCloud.group.dismiss(userId, groupId); if (groupDismissResult != null && groupDismissResult.getCode() == 200) { // 对群记录进行修改 // todo group.setcGroupStatu("1");// 群组失效 tGroupMapper.updateByPrimaryKey(group);// 更新群组信息 result.put("code", "200"); String[] messagePublishGroupToGroupId = { String.valueOf(group.getcGroupId()) }; Map<String, Object> data = new HashMap<String, Object>(); data.put("operatorNickname", userId); String pushTip = "群组:" + group.getcGroupName() + "解散了"; GroupNtfMessage groupMessage = new GroupNtfMessage(userId, "Dismiss", data, pushTip, pushTip); CodeSuccessResult messagePublishGroupResult = rongCloud.message.publishGroup(userId, messagePublishGroupToGroupId, groupMessage, pushTip, "{\"pushData\":\"" + pushTip + "\"}", 1, 1, 1); return result; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#groupList(java.lang.String) */ public Map<String, Object> groupList(String phoneNum) { // 根据手机号查询所在的群id List<TGroupMember> memberList = tGroupMemberMapper.selectByPhone(phoneNum); Map<String, Object> result = new HashMap<String, Object>(); List<Map<String, Object>> groupList = new ArrayList<Map<String, Object>>(); if (memberList != null && memberList.size() > 0) { // 根据所在群id获取群组信息 for (TGroupMember member : memberList) { TGroup group = tGroupMapper.selectByPrimaryKey(member.getcGroupId()); Map<String, Object> aGroup = new HashMap<String, Object>(); if (null != group && group.getcGroupStatu().equals("0")) { aGroup.put("groupName", group.getcGroupName()); aGroup.put("groupId", String.valueOf(group.getcGroupId())); aGroup.put("groupImg",StarConstants.COM_IMG_URL+ group.getcGroupHeadImg()); TGroupMemberExample memberExample = new TGroupMemberExample(); TGroupMemberExample.Criteria criteria = memberExample.createCriteria(); criteria.andCGroupIdEqualTo(group.getcGroupId()); int groupSize = tGroupMemberMapper.countByExample(memberExample); aGroup.put("groupSize", groupSize); groupList.add(aGroup); } } } result.put("groupList", groupList); return result; } /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#groupMembers(java.lang.String) */ public Map<String, Object> groupMembers(String groupId) { Integer id = Integer.parseInt(groupId); List<TGroupMember> members = tGroupMemberMapper.selectByGroupId(id); Map<String, Object> result = new HashMap<String, Object>(); List<Map<String, Object>> memberList = new ArrayList<Map<String, Object>>(); for (TGroupMember member : members) { Map<String, Object> aMember = new HashMap<String, Object>(); if (member.getcGroupMemberIdentity().equals("0")) {// 群主是公司用户 TCompanyInfo info = tCompanyInfoMapper.selectByPhone(member.getcGroupMemberId()); if (info != null) { aMember.put("memberName", info.getcComName()); aMember.put("memberImg",StarConstants.COM_IMG_URL+ info.getcComHeadImg()); aMember.put("memberId", info.getcComPhone()); aMember.put("memberIdentity", member.getcGroupMemberIdentity()); memberList.add(aMember); } } else { TUserInfo info = tUserInfoMapper.selectByPhone(member.getcGroupMemberId()); if (info != null) { aMember.put("memberName", info.getcUserNickname()); aMember.put("memberImg", StarConstants.USER_IMG_URL+info.getcUserImg()); aMember.put("memberId", info.getcUserPhone()); aMember.put("memberIdentity", member.getcGroupMemberIdentity()); memberList.add(aMember); } } } result.put("memberList", memberList); return result; } /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#deleteFriend(java.lang.String, * java.lang.String) */ public Map<String, Object> deleteFriend(String fromUserId, String toUserId) { long currId = Long.parseLong(fromUserId); long delId = Long.parseLong(toUserId); String leftId = fromUserId; String rightId = toUserId; if (currId > delId) { leftId = toUserId; rightId = fromUserId; } int result = tFriendMapper.deleteByChoice(leftId, rightId); if (result > 0) { Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap.put("code", "200"); return resultMap; } return null; } /* * (non-Javadoc) * * @see * io.rong.service.RongCloudService#groupGroupIdByJobId(java.lang.String) */ public Map<String, Object> getGroupIdByJobId(String jobId) { TGroup group = tGroupMapper.selectByJobId(jobId); Map<String, Object> resultMap = new HashMap<String, Object>(); if (null != group) { resultMap.put("groupId", String.valueOf(group.getcGroupId())); } else { resultMap.put("groupId", "-1"); } return resultMap; } /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#getGroupInfo(java.lang.String) */ public Map<String, Object> getGroupInfo(String groupId) { int group_id = Integer.parseInt(groupId); TGroup group = tGroupMapper.selectByPrimaryKey(group_id); Map<String, Object> groupInfoMap = new HashMap<String, Object>(); // 根据群组id获取群成员列表 List<TGroupMember> members = tGroupMemberMapper.selectByGroupId(group_id); String groupSize = "0"; if (members != null) { groupSize = String.valueOf(members.size()); } if (null != group) { groupInfoMap.put("groupId", groupId); groupInfoMap.put("groupName", group.getcGroupName()); groupInfoMap.put("groupOwnerId", group.getcGroupCreaterId()); groupInfoMap.put("groupImgUrl", group.getcGroupHeadImg()); groupInfoMap.put("groupSize", groupSize); } return groupInfoMap; } /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#quitGroup(java.lang.String, * java.lang.String) */ public Map<String, Object> quitGroup(String userId, String groupId) { // 退出群组方法(将用户从群中移除,不再接收该群组的消息.) RongCloud rongCloud = RongCloud.getInstance(RongConstants.RONG_APP_KEY, RongConstants.RONG_APP_SECRET); String[] groupQuitUserId = { userId }; Map<String, Object> resultMap = new HashMap<String, Object>(); TGroup group = tGroupMapper.selectByPrimaryKey(Integer.parseInt(groupId)); if (group == null) { return null; } if (group.getcGroupCreaterId().equals(userId)) { return null;// 群主无法退群 } try { CodeSuccessResult groupQuitResult = rongCloud.group.quit(groupQuitUserId, groupId); if (groupQuitResult.getCode() == 200) { resultMap.put("code", "200"); // 删除数据库中的群成员记录 tGroupMemberMapper.deleteByGroupIdAndUserId(Integer.parseInt(groupId), userId); String[] messagePublishGroupToGroupId = { String.valueOf(group.getcGroupId()) }; Map<String, Object> data = new HashMap<String, Object>(); data.put("operatorNickname", userId); String[] targetUserIds = { userId, group.getcGroupCreaterId() }; data.put("targetUserIds", targetUserIds); data.put("targetUserDisplayNames", groupQuitUserId); GroupNtfMessage groupMessage = new GroupNtfMessage(userId, "Quit", data, "退出群组", "退出群组"); CodeSuccessResult messagePublishGroupResult = rongCloud.message.publishGroup(userId, messagePublishGroupToGroupId, groupMessage, "退出群组", "{\"pushData\":\"" + "退出群组\"}", 1, 1, 1); return resultMap; } } catch (Exception e) { } return null; } public Map<String, Object> getRelations(String phoneNum) { // 根据手机号查找好友,本人在左侧 List<TFriend> leftList = tFriendMapper.selectByUid(phoneNum); Map<String, Object> result = new HashMap<String, Object>(); List<Map<String, Object>> friendList = new ArrayList<Map<String, Object>>(); if (null != leftList && leftList.size() > 0) { for (TFriend tf : leftList) { TUserInfo info = tUserInfoMapper.selectByPhone(tf.getcFid()); if (info != null) {// 好友 Map<String, Object> fr = new HashMap<String, Object>(3); fr.put("friendName", info.getcUserNickname()); fr.put("friendPicUrl",StarConstants.USER_IMG_URL+ info.getcUserImg()); fr.put("friendPhoneNum", info.getcUserPhone()); fr.put("state", tf.getcState()); friendList.add(fr); } } } // 查找好友,本人在右侧 List<TFriend> rightList = tFriendMapper.selectByFid(phoneNum); if (null != rightList && rightList.size() > 0) { for (TFriend tf : rightList) { TUserInfo info = tUserInfoMapper.selectByPhone(tf.getcUid()); if (info != null) {// 好友 Map<String, Object> fr = new HashMap<String, Object>(3); fr.put("friendName", info.getcUserNickname()); fr.put("friendPicUrl",StarConstants.USER_IMG_URL+ info.getcUserImg()); fr.put("friendPhoneNum", info.getcUserPhone()); fr.put("state", tf.getcState()); friendList.add(fr); } } } result.put("relationList", friendList); return result; } }
starjobs/src/main/java/io/rong/service/impl/RongCloudServiceImpl.java
/** * */ package io.rong.service.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.starjobs.common.StarConstants; import com.starjobs.mapper.TCompanyInfoMapper; import com.starjobs.mapper.TFriendMapper; import com.starjobs.mapper.TGroupMapper; import com.starjobs.mapper.TGroupMemberMapper; import com.starjobs.mapper.TUserInfoMapper; import com.starjobs.pojo.TCompanyInfo; import com.starjobs.pojo.TFriend; import com.starjobs.pojo.TGroup; import com.starjobs.pojo.TGroupMember; import com.starjobs.pojo.TUserInfo; import io.rong.RongCloud; import io.rong.messages.ContactNtfMessage; import io.rong.messages.GroupNtfMessage; import io.rong.models.CodeSuccessResult; import io.rong.models.TokenResult; import io.rong.service.RongCloudService; import io.rong.util.RongConstants; /** * <p> * Title:RongCloudServiceImpl * </p> * <p> * Description: * </p> * * @author:bao * @date:2017年6月7日下午11:04:47 */ @Service public class RongCloudServiceImpl implements RongCloudService { @Autowired TFriendMapper tFriendMapper; @Autowired TUserInfoMapper tUserInfoMapper; @Autowired TCompanyInfoMapper tCompanyInfoMapper; @Autowired TGroupMapper tGroupMapper; @Autowired TGroupMemberMapper tGroupMemberMapper; /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#getToken() */ public Map<String, Object> getToken(String phoneNum, String name, String portraitUri) { if (StringUtils.isEmpty(name)) { name = "Tom"; } if (StringUtils.isEmpty(portraitUri)) { portraitUri = "http://www.rongcloud.cn/images/logo.png"; } try { TokenResult userGetTokenResult = RongCloud.getInstance(RongConstants.RONG_APP_KEY, RongConstants.RONG_APP_SECRET).user.getToken(phoneNum, name, portraitUri); Map<String, Object> result = new HashMap<String, Object>(); result.put("code", userGetTokenResult.getCode().toString()); result.put("rongToken", userGetTokenResult.getToken()); result.put("userId", userGetTokenResult.getUserId()); return result; } catch (Exception e) { e.printStackTrace(); return null; } } /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#addFriend(java.lang.String, * java.lang.String, java.lang.String, java.lang.String) */ public Map<String, Object> addFriend(String fromUserId, String toUserId, String content, String pushContent) { // 将标识排序,做小右大 Long fid = Long.parseLong(fromUserId); Long tid = Long.parseLong(toUserId); String cuid = fromUserId; String cfid = toUserId; if (fid.equals(tid)) return null;// 自己和自己不能成为好友 if (fid > tid) { cuid = toUserId; cfid = fromUserId; } // 检查是否已经是好友 TFriend friend = tFriendMapper.selectByUserId(cuid, cfid); // 检查好友状态 if (null != friend && !friend.getcState().equals("0")) { return null;// 已经添加过或者是好友 } if (null == friend) { friend = new TFriend(); friend.setcUid(cuid); friend.setcFid(cfid); friend.setcState(fromUserId); tFriendMapper.insert(friend);// 添加好友 } else { friend.setcState(fromUserId);// 修改状态为请求待确认 tFriendMapper.updateByPrimaryKey(friend); } String[] toUserIds = { toUserId }; ContactNtfMessage ntfMessage = new ContactNtfMessage("add friend", "extra", fromUserId, toUserId, pushContent); try { CodeSuccessResult result = RongCloud.getInstance(RongConstants.RONG_APP_KEY, RongConstants.RONG_APP_SECRET).message.PublishSystem(fromUserId, toUserIds, ntfMessage, pushContent, null, 1, 1); if (null != result) { Map<String, Object> data = new HashMap<String, Object>(); data.put("code", result.getCode().toString()); return data; } return null; } catch (Exception e) { e.printStackTrace(); return null; } } /* * (non-Javadoc) * * @see * io.rong.service.RongCloudService#confirmFriendAdded(java.lang.String, * java.lang.String) */ public Map<String, Object> confirmFriendAdded(String fromUserId, String toUserId) { // 将标识排序,做小右大 Long fid = Long.parseLong(fromUserId); Long tid = Long.parseLong(toUserId); String cuid = fromUserId; String cfid = toUserId; if (fid.equals(tid)) return null;// 自己和自己不能成为好友 if (fid > tid) { cuid = toUserId; cfid = fromUserId; } // 检查是否已经是好友 TFriend friend = tFriendMapper.selectByUserId(cuid, cfid); if (friend == null) {// 记录必须存在 return null; } if (friend.equals("0")) { return null;// 陌生人 } if (null != friend && friend.equals("2")) { return null;// 已经是好友 } friend.setcState("2");// 成为好友 tFriendMapper.updateByPrimaryKey(friend);// 添加好友 // 向融云发送通知信息 String[] toUserIds = { toUserId }; String content = "" + fromUserId + "与" + toUserId + "成为好友"; ContactNtfMessage ntfMessage = new ContactNtfMessage("confirm friend_added", "extra", fromUserId, toUserId, content); try { CodeSuccessResult result = RongCloud.getInstance(RongConstants.RONG_APP_KEY, RongConstants.RONG_APP_SECRET).message.PublishSystem(fromUserId, toUserIds, ntfMessage, null, null, 1, 1); if (null != result) { Map<String, Object> data = new HashMap<String, Object>(); data.put("code", result.getCode().toString()); return data; } return null; } catch (Exception e) { e.printStackTrace(); return null; } } /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#lookFriend(java.lang.String) */ public Map<String, Object> lookFriend(String userPhone, String phoneNum) { // 将标识排序,做小右大 Long fid = Long.parseLong(userPhone); Long tid = Long.parseLong(phoneNum); String cuid = userPhone; String cfid = phoneNum; if (fid.equals(tid)) return null;// 自己和自己不能成为好友 if (fid > tid) { cuid = phoneNum; cfid = userPhone; } // 检查是否已经是好友 TFriend friend = tFriendMapper.selectByUserId(cuid, cfid); String state = "0";// 陌生人 if (null != friend) { state = friend.getcState(); } // 根据手机号查找用户 TUserInfo userInfo = tUserInfoMapper.selectByPhone(phoneNum.trim()); Map<String, Object> resultMap = new HashMap<String, Object>(); if (null != userInfo) { resultMap.put("friendName", userInfo.getcUserNickname()); resultMap.put("friendPicUrl", StarConstants.USER_IMG_URL+userInfo.getcUserImg()); resultMap.put("friendPhoneNum", userInfo.getcUserPhone()); resultMap.put("state", state); return resultMap; } // 普通用户不存在,查找公司用户 TCompanyInfo comInfo = tCompanyInfoMapper.selectByPhone(phoneNum.trim()); if (null != comInfo) { resultMap.put("friendName", comInfo.getcComName()); resultMap.put("friendPicUrl", StarConstants.COM_IMG_URL+comInfo.getcComHeadImg()); resultMap.put("friendPhoneNum", comInfo.getcComPhone()); resultMap.put("state", state); return resultMap; } // 都没找到 return null; } public Map<String, Object> readFriends(String phoneNum) { // 根据手机号查找好友,本人在左侧 List<TFriend> leftList = tFriendMapper.selectByUid(phoneNum); Map<String, Object> result = new HashMap<String, Object>(); List<Map<String, Object>> friendList = new ArrayList<Map<String, Object>>(); if (null != leftList && leftList.size() > 0) { for (TFriend tf : leftList) { TUserInfo info = tUserInfoMapper.selectByPhone(tf.getcFid()); if (info != null && tf.getcState().equals("2")) {// 好友 Map<String, Object> fr = new HashMap<String, Object>(3); fr.put("friendName", info.getcUserNickname()); fr.put("friendPicUrl", info.getcUserImg()); fr.put("friendPhoneNum", info.getcUserPhone()); friendList.add(fr); } } } // 查找好友,本人在右侧 List<TFriend> rightList = tFriendMapper.selectByFid(phoneNum); if (null != rightList && rightList.size() > 0) { for (TFriend tf : rightList) { TUserInfo info = tUserInfoMapper.selectByPhone(tf.getcUid()); if (info != null && tf.getcState().equals("2")) {// 好友 Map<String, Object> fr = new HashMap<String, Object>(3); fr.put("friendName", info.getcUserNickname()); fr.put("friendPicUrl", info.getcUserImg()); fr.put("friendPhoneNum", info.getcUserPhone()); friendList.add(fr); } } } result.put("friendList", friendList); return result; } /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#createGroup(java.lang.String, * java.lang.String) */ public Map<String, Object> createGroup(String userId, String groupName, String jobId) { RongCloud rongCloud = RongCloud.getInstance(RongConstants.RONG_APP_KEY, RongConstants.RONG_APP_SECRET); String[] groupCreateUserId = { userId }; Map<String, Object> result = new HashMap<String, Object>(); try { TCompanyInfo comInfo = tCompanyInfoMapper.selectByPhone(userId); String comHeadImg = comInfo.getcComHeadImg(); comHeadImg = (comHeadImg==null?"default.png":comHeadImg); // 保存群组 TGroup group = new TGroup(); group.setcGroupCreaterId(userId); group.setcGroupHeadImg(comHeadImg); group.setcGroupName(groupName); group.setcGroupStatu("1"); group.setcJobId(jobId); tGroupMapper.insertSelective(group); // 保存群组成员 TGroupMember member = new TGroupMember(); member.setcGroupId(group.getcGroupId());// 所在群组id member.setcGroupMemberId(userId);// 成员手机号 member.setcGroupMemberIdentity("0");// 群主标识 tGroupMemberMapper.insertSelective(member); CodeSuccessResult groupCreateResult = rongCloud.group.create(groupCreateUserId, String.valueOf(group.getcGroupId()), groupName); System.out.println("--" + groupCreateResult.toString()); if (groupCreateResult != null && groupCreateResult.getCode() == 200) { String[] messagePublishGroupToGroupId = { String.valueOf(group.getcGroupId()) }; Map<String, Object> data = new HashMap<String, Object>(); data.put("operatorNickname", userId); data.put("targetGroupName", groupName); GroupNtfMessage groupMessage = new GroupNtfMessage(userId, "Create", data, "创建群组:" + groupName, "创建群组:" + groupName); CodeSuccessResult messagePublishGroupResult = rongCloud.message.publishGroup(userId, messagePublishGroupToGroupId, groupMessage, "创建群组:" + groupName, "{\"pushData\":\"" + "创建群组:" + groupName + "\"}", 1, 1, 1); System.out.println("--2--" + messagePublishGroupResult.toString()); if (messagePublishGroupResult.getCode() == 200) { group.setcGroupStatu("0");// 创建成功群组激活 tGroupMapper.updateByPrimaryKey(group); result.put("code", "200"); return result; } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#joinGroup(java.lang.String, * java.lang.String, java.lang.String) */ public Map<String, Object> joinGroup(String userId, String groupId, String groupName) { RongCloud rongCloud = RongCloud.getInstance(RongConstants.RONG_APP_KEY, RongConstants.RONG_APP_SECRET); // 将用户加入指定群组,用户将可以收到该群的消息,同一用户最多可加入 500 个群,每个群最大至 3000 人。 String[] groupJoinUserId = userId.split(";"); Map<String, Object> result = new HashMap<String, Object>(); // 获取融云端群组id TGroup group = tGroupMapper.selectByPrimaryKey(Integer.parseInt(groupId)); if (group == null) { return null; } try { CodeSuccessResult groupJoinResult = rongCloud.group.join(groupJoinUserId, String.valueOf(group.getcGroupId()), groupName); if (groupJoinResult != null && groupJoinResult.getCode() == 200) { // 添加群成员记录 // todo TGroupMember member = new TGroupMember(); member.setcGroupId(Integer.parseInt(groupId));// 所在群组id member.setcGroupMemberId(userId);// 成员手机号 member.setcGroupMemberIdentity("1");// 群主标识 tGroupMemberMapper.insertSelective(member); result.put("code", "200"); String[] messagePublishGroupToGroupId = { String.valueOf(group.getcGroupId()) }; Map<String, Object> data = new HashMap<String, Object>(); data.put("operatorNickname", userId); String[] targetUserIds = { userId }; data.put("targetUserIds", targetUserIds); data.put("operatorNickname", userId); TUserInfo userInfo = tUserInfoMapper.selectByPhone(userId); GroupNtfMessage groupMessage = new GroupNtfMessage(userId, "Add", data, userInfo.getcUserNickname()+" 加入群组", userInfo.getcUserNickname()+" 加入群组"); CodeSuccessResult messagePublishGroupResult = rongCloud.message.publishGroup(userId, messagePublishGroupToGroupId, groupMessage, "加入群组:" + groupName, "{\"pushData\":\"" + "加入群组:" + groupName + "\"}", 1, 1, 1); return result; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#dismissGroup(java.lang.String, * java.lang.String) */ public Map<String, Object> dismissGroup(String userId, String groupId) { // 解散群组方法。(将该群解散,所有用户都无法再接收该群的消息。) RongCloud rongCloud = RongCloud.getInstance(RongConstants.RONG_APP_KEY, RongConstants.RONG_APP_SECRET); Map<String, Object> result = new HashMap<String, Object>(); // 获取融云端群组id TGroup group = tGroupMapper.selectByPrimaryKey(Integer.parseInt(groupId)); if (group == null) { return null; } try { CodeSuccessResult groupDismissResult = rongCloud.group.dismiss(userId, groupId); if (groupDismissResult != null && groupDismissResult.getCode() == 200) { // 对群记录进行修改 // todo group.setcGroupStatu("1");// 群组失效 tGroupMapper.updateByPrimaryKey(group);// 更新群组信息 result.put("code", "200"); String[] messagePublishGroupToGroupId = { String.valueOf(group.getcGroupId()) }; Map<String, Object> data = new HashMap<String, Object>(); data.put("operatorNickname", userId); String pushTip = "群组:" + group.getcGroupName() + "解散了"; GroupNtfMessage groupMessage = new GroupNtfMessage(userId, "Dismiss", data, pushTip, pushTip); CodeSuccessResult messagePublishGroupResult = rongCloud.message.publishGroup(userId, messagePublishGroupToGroupId, groupMessage, pushTip, "{\"pushData\":\"" + pushTip + "\"}", 1, 1, 1); return result; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#groupList(java.lang.String) */ public Map<String, Object> groupList(String phoneNum) { // 根据手机号查询所在的群id List<TGroupMember> memberList = tGroupMemberMapper.selectByPhone(phoneNum); Map<String, Object> result = new HashMap<String, Object>(); List<Map<String, Object>> groupList = new ArrayList<Map<String, Object>>(); if (memberList != null && memberList.size() > 0) { // 根据所在群id获取群组信息 for (TGroupMember member : memberList) { TGroup group = tGroupMapper.selectByPrimaryKey(member.getcGroupId()); Map<String, Object> aGroup = new HashMap<String, Object>(); if (null != group && group.getcGroupStatu().equals("0")) { aGroup.put("groupName", group.getcGroupName()); aGroup.put("groupId", String.valueOf(group.getcGroupId())); aGroup.put("groupImg",StarConstants.COM_IMG_URL+ group.getcGroupHeadImg()); groupList.add(aGroup); } } } result.put("groupList", groupList); result.put("groupSize", groupList.size()); return result; } /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#groupMembers(java.lang.String) */ public Map<String, Object> groupMembers(String groupId) { Integer id = Integer.parseInt(groupId); List<TGroupMember> members = tGroupMemberMapper.selectByGroupId(id); Map<String, Object> result = new HashMap<String, Object>(); List<Map<String, Object>> memberList = new ArrayList<Map<String, Object>>(); for (TGroupMember member : members) { Map<String, Object> aMember = new HashMap<String, Object>(); if (member.getcGroupMemberIdentity().equals("0")) {// 群主是公司用户 TCompanyInfo info = tCompanyInfoMapper.selectByPhone(member.getcGroupMemberId()); if (info != null) { aMember.put("memberName", info.getcComName()); aMember.put("memberImg",StarConstants.COM_IMG_URL+ info.getcComHeadImg()); aMember.put("memberId", info.getcComPhone()); aMember.put("memberIdentity", member.getcGroupMemberIdentity()); memberList.add(aMember); } } else { TUserInfo info = tUserInfoMapper.selectByPhone(member.getcGroupMemberId()); if (info != null) { aMember.put("memberName", info.getcUserNickname()); aMember.put("memberImg", StarConstants.USER_IMG_URL+info.getcUserImg()); aMember.put("memberId", info.getcUserPhone()); aMember.put("memberIdentity", member.getcGroupMemberIdentity()); memberList.add(aMember); } } } result.put("memberList", memberList); return result; } /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#deleteFriend(java.lang.String, * java.lang.String) */ public Map<String, Object> deleteFriend(String fromUserId, String toUserId) { long currId = Long.parseLong(fromUserId); long delId = Long.parseLong(toUserId); String leftId = fromUserId; String rightId = toUserId; if (currId > delId) { leftId = toUserId; rightId = fromUserId; } int result = tFriendMapper.deleteByChoice(leftId, rightId); if (result > 0) { Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap.put("code", "200"); return resultMap; } return null; } /* * (non-Javadoc) * * @see * io.rong.service.RongCloudService#groupGroupIdByJobId(java.lang.String) */ public Map<String, Object> getGroupIdByJobId(String jobId) { TGroup group = tGroupMapper.selectByJobId(jobId); Map<String, Object> resultMap = new HashMap<String, Object>(); if (null != group) { resultMap.put("groupId", String.valueOf(group.getcGroupId())); } else { resultMap.put("groupId", "-1"); } return resultMap; } /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#getGroupInfo(java.lang.String) */ public Map<String, Object> getGroupInfo(String groupId) { int group_id = Integer.parseInt(groupId); TGroup group = tGroupMapper.selectByPrimaryKey(group_id); Map<String, Object> groupInfoMap = new HashMap<String, Object>(); // 根据群组id获取群成员列表 List<TGroupMember> members = tGroupMemberMapper.selectByGroupId(group_id); String groupSize = "0"; if (members != null) { groupSize = String.valueOf(members.size()); } if (null != group) { groupInfoMap.put("groupId", groupId); groupInfoMap.put("groupName", group.getcGroupName()); groupInfoMap.put("groupOwnerId", group.getcGroupCreaterId()); groupInfoMap.put("groupImgUrl", group.getcGroupHeadImg()); groupInfoMap.put("groupSize", groupSize); } return groupInfoMap; } /* * (non-Javadoc) * * @see io.rong.service.RongCloudService#quitGroup(java.lang.String, * java.lang.String) */ public Map<String, Object> quitGroup(String userId, String groupId) { // 退出群组方法(将用户从群中移除,不再接收该群组的消息.) RongCloud rongCloud = RongCloud.getInstance(RongConstants.RONG_APP_KEY, RongConstants.RONG_APP_SECRET); String[] groupQuitUserId = { userId }; Map<String, Object> resultMap = new HashMap<String, Object>(); TGroup group = tGroupMapper.selectByPrimaryKey(Integer.parseInt(groupId)); if (group == null) { return null; } if (group.getcGroupCreaterId().equals(userId)) { return null;// 群主无法退群 } try { CodeSuccessResult groupQuitResult = rongCloud.group.quit(groupQuitUserId, groupId); if (groupQuitResult.getCode() == 200) { resultMap.put("code", "200"); // 删除数据库中的群成员记录 tGroupMemberMapper.deleteByGroupIdAndUserId(Integer.parseInt(groupId), userId); String[] messagePublishGroupToGroupId = { String.valueOf(group.getcGroupId()) }; Map<String, Object> data = new HashMap<String, Object>(); data.put("operatorNickname", userId); String[] targetUserIds = { userId, group.getcGroupCreaterId() }; data.put("targetUserIds", targetUserIds); data.put("targetUserDisplayNames", groupQuitUserId); GroupNtfMessage groupMessage = new GroupNtfMessage(userId, "Quit", data, "退出群组", "退出群组"); CodeSuccessResult messagePublishGroupResult = rongCloud.message.publishGroup(userId, messagePublishGroupToGroupId, groupMessage, "退出群组", "{\"pushData\":\"" + "退出群组\"}", 1, 1, 1); return resultMap; } } catch (Exception e) { } return null; } public Map<String, Object> getRelations(String phoneNum) { // 根据手机号查找好友,本人在左侧 List<TFriend> leftList = tFriendMapper.selectByUid(phoneNum); Map<String, Object> result = new HashMap<String, Object>(); List<Map<String, Object>> friendList = new ArrayList<Map<String, Object>>(); if (null != leftList && leftList.size() > 0) { for (TFriend tf : leftList) { TUserInfo info = tUserInfoMapper.selectByPhone(tf.getcFid()); if (info != null) {// 好友 Map<String, Object> fr = new HashMap<String, Object>(3); fr.put("friendName", info.getcUserNickname()); fr.put("friendPicUrl",StarConstants.USER_IMG_URL+ info.getcUserImg()); fr.put("friendPhoneNum", info.getcUserPhone()); fr.put("state", tf.getcState()); friendList.add(fr); } } } // 查找好友,本人在右侧 List<TFriend> rightList = tFriendMapper.selectByFid(phoneNum); if (null != rightList && rightList.size() > 0) { for (TFriend tf : rightList) { TUserInfo info = tUserInfoMapper.selectByPhone(tf.getcUid()); if (info != null) {// 好友 Map<String, Object> fr = new HashMap<String, Object>(3); fr.put("friendName", info.getcUserNickname()); fr.put("friendPicUrl",StarConstants.USER_IMG_URL+ info.getcUserImg()); fr.put("friendPhoneNum", info.getcUserPhone()); fr.put("state", tf.getcState()); friendList.add(fr); } } } result.put("relationList", friendList); return result; } }
update
starjobs/src/main/java/io/rong/service/impl/RongCloudServiceImpl.java
update
<ide><path>tarjobs/src/main/java/io/rong/service/impl/RongCloudServiceImpl.java <ide> import com.starjobs.pojo.TFriend; <ide> import com.starjobs.pojo.TGroup; <ide> import com.starjobs.pojo.TGroupMember; <add>import com.starjobs.pojo.TGroupMemberExample; <ide> import com.starjobs.pojo.TUserInfo; <ide> <ide> import io.rong.RongCloud; <ide> aGroup.put("groupName", group.getcGroupName()); <ide> aGroup.put("groupId", String.valueOf(group.getcGroupId())); <ide> aGroup.put("groupImg",StarConstants.COM_IMG_URL+ group.getcGroupHeadImg()); <add> TGroupMemberExample memberExample = new TGroupMemberExample(); <add> TGroupMemberExample.Criteria criteria = memberExample.createCriteria(); <add> criteria.andCGroupIdEqualTo(group.getcGroupId()); <add> int groupSize = tGroupMemberMapper.countByExample(memberExample); <add> aGroup.put("groupSize", groupSize); <ide> groupList.add(aGroup); <ide> } <ide> } <ide> } <ide> result.put("groupList", groupList); <del> result.put("groupSize", groupList.size()); <ide> return result; <ide> } <ide>
Java
bsd-3-clause
3b9062442520994c3aba8933e39db94a09a5abd4
0
codecop/ugly-trivia-kata
package com.adaptionsoft.games.uglytrivia; import org.junit.Before; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.mockito.Mockito.mock; public class CurrentPlayerTest { private static final String PLAYER_ONE = "Thomas"; private static final String PLAYER_TWO = "Peter"; private CurrentPlayer currentPlayer; @Before public void addPlayers() { PlayerUi ui = mock(PlayerUi.class); Players players = new Players(ui); players.add(PLAYER_ONE); players.add(PLAYER_TWO); currentPlayer = new CurrentPlayer(players); } @Test public void shouldGiveFirstPlayer() { assertThat(currentPlayer.getName(), is(PLAYER_ONE)); } @Test public void shouldIteratePlayers() { currentPlayer.nextPlayer(); assertThat(currentPlayer.getName(), is(PLAYER_TWO)); } @Test public void shouldStartWithFirstPlayerAgain() { currentPlayer.nextPlayer(); currentPlayer.nextPlayer(); assertThat(currentPlayer.getName(), is(PLAYER_ONE)); } }
src/test/java/com/adaptionsoft/games/uglytrivia/CurrentPlayerTest.java
package com.adaptionsoft.games.uglytrivia; import org.junit.Before; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.mockito.Mockito.mock; public class CurrentPlayerTest { public static final String PLAYER_ONE = "Thomas"; public static final String PLAYER_TWO = "Peter"; private CurrentPlayer currentPlayer; @Before public void addPlayers() { PlayerUi ui = mock(PlayerUi.class); Players players = new Players(ui); players.add(PLAYER_ONE); players.add(PLAYER_TWO); currentPlayer = new CurrentPlayer(players); } @Test public void shouldGiveFirstPlayer() { assertThat(currentPlayer.getName(), is(PLAYER_ONE)); } @Test public void shouldIteratePlayers() { currentPlayer.nextPlayer(); assertThat(currentPlayer.getName(), is(PLAYER_TWO)); } @Test public void shouldStartWithFirstPlayerAgain() { currentPlayer.nextPlayer(); currentPlayer.nextPlayer(); assertThat(currentPlayer.getName(), is(PLAYER_ONE)); } }
Reduce visibility (as proposed by inspection).
src/test/java/com/adaptionsoft/games/uglytrivia/CurrentPlayerTest.java
Reduce visibility (as proposed by inspection).
<ide><path>rc/test/java/com/adaptionsoft/games/uglytrivia/CurrentPlayerTest.java <ide> <ide> public class CurrentPlayerTest { <ide> <del> public static final String PLAYER_ONE = "Thomas"; <del> public static final String PLAYER_TWO = "Peter"; <add> private static final String PLAYER_ONE = "Thomas"; <add> private static final String PLAYER_TWO = "Peter"; <ide> <ide> private CurrentPlayer currentPlayer; <ide>
Java
apache-2.0
3e45cdbb5ba21bb52e8af92c6fba6ed06388d107
0
TimurTarasenko/omim,TimurTarasenko/omim,mgsergio/omim,programming086/omim,rokuz/omim,albertshift/omim,mpimenov/omim,bykoianko/omim,rokuz/omim,Transtech/omim,alexzatsepin/omim,kw217/omim,milchakov/omim,UdjinM6/omim,andrewshadura/omim,yunikkk/omim,igrechuhin/omim,guard163/omim,therearesomewhocallmetim/omim,victorbriz/omim,yunikkk/omim,TimurTarasenko/omim,trashkalmar/omim,dobriy-eeh/omim,AlexanderMatveenko/omim,Volcanoscar/omim,Komzpa/omim,vng/omim,goblinr/omim,Zverik/omim,igrechuhin/omim,darina/omim,matsprea/omim,vng/omim,Komzpa/omim,trashkalmar/omim,ygorshenin/omim,Volcanoscar/omim,ygorshenin/omim,65apps/omim,mgsergio/omim,andrewshadura/omim,vladon/omim,andrewshadura/omim,gardster/omim,albertshift/omim,mpimenov/omim,Transtech/omim,65apps/omim,bykoianko/omim,andrewshadura/omim,alexzatsepin/omim,AlexanderMatveenko/omim,alexzatsepin/omim,Zverik/omim,andrewshadura/omim,Komzpa/omim,Saicheg/omim,mapsme/omim,albertshift/omim,andrewshadura/omim,matsprea/omim,syershov/omim,Endika/omim,alexzatsepin/omim,mpimenov/omim,dkorolev/omim,dkorolev/omim,AlexanderMatveenko/omim,Volcanoscar/omim,kw217/omim,Transtech/omim,dkorolev/omim,Saicheg/omim,Endika/omim,vasilenkomike/omim,kw217/omim,mpimenov/omim,yunikkk/omim,vng/omim,bykoianko/omim,vladon/omim,milchakov/omim,ygorshenin/omim,victorbriz/omim,edl00k/omim,alexzatsepin/omim,lydonchandra/omim,UdjinM6/omim,Zverik/omim,victorbriz/omim,edl00k/omim,programming086/omim,goblinr/omim,mgsergio/omim,Zverik/omim,dobriy-eeh/omim,UdjinM6/omim,dobriy-eeh/omim,UdjinM6/omim,kw217/omim,AlexanderMatveenko/omim,sidorov-panda/omim,vng/omim,wersoo/omim,therearesomewhocallmetim/omim,augmify/omim,yunikkk/omim,vng/omim,Zverik/omim,stangls/omim,syershov/omim,trashkalmar/omim,Komzpa/omim,trashkalmar/omim,lydonchandra/omim,VladiMihaylenko/omim,milchakov/omim,mpimenov/omim,felipebetancur/omim,mapsme/omim,alexzatsepin/omim,Zverik/omim,simon247/omim,wersoo/omim,vng/omim,trashkalmar/omim,vng/omim,augmify/omim,Transtech/omim,vladon/omim,Transtech/omim,dkorolev/omim,alexzatsepin/omim,goblinr/omim,AlexanderMatveenko/omim,gardster/omim,kw217/omim,mapsme/omim,sidorov-panda/omim,mapsme/omim,felipebetancur/omim,Saicheg/omim,mpimenov/omim,syershov/omim,sidorov-panda/omim,jam891/omim,vng/omim,therearesomewhocallmetim/omim,Volcanoscar/omim,trashkalmar/omim,albertshift/omim,dkorolev/omim,syershov/omim,victorbriz/omim,albertshift/omim,guard163/omim,goblinr/omim,stangls/omim,Endika/omim,gardster/omim,darina/omim,Transtech/omim,felipebetancur/omim,albertshift/omim,TimurTarasenko/omim,mgsergio/omim,65apps/omim,felipebetancur/omim,trashkalmar/omim,Transtech/omim,Saicheg/omim,Endika/omim,VladiMihaylenko/omim,Zverik/omim,stangls/omim,goblinr/omim,yunikkk/omim,rokuz/omim,darina/omim,darina/omim,vasilenkomike/omim,dobriy-eeh/omim,stangls/omim,darina/omim,rokuz/omim,vladon/omim,darina/omim,vladon/omim,goblinr/omim,programming086/omim,jam891/omim,dkorolev/omim,jam891/omim,albertshift/omim,bykoianko/omim,TimurTarasenko/omim,AlexanderMatveenko/omim,krasin/omim,alexzatsepin/omim,mgsergio/omim,Saicheg/omim,victorbriz/omim,65apps/omim,augmify/omim,Zverik/omim,vng/omim,ygorshenin/omim,simon247/omim,bykoianko/omim,Volcanoscar/omim,mpimenov/omim,guard163/omim,dobriy-eeh/omim,jam891/omim,guard163/omim,mgsergio/omim,VladiMihaylenko/omim,stangls/omim,Komzpa/omim,milchakov/omim,mpimenov/omim,simon247/omim,vasilenkomike/omim,jam891/omim,rokuz/omim,vasilenkomike/omim,Endika/omim,kw217/omim,wersoo/omim,lydonchandra/omim,vasilenkomike/omim,yunikkk/omim,victorbriz/omim,bykoianko/omim,kw217/omim,dkorolev/omim,AlexanderMatveenko/omim,dobriy-eeh/omim,wersoo/omim,andrewshadura/omim,rokuz/omim,Zverik/omim,felipebetancur/omim,lydonchandra/omim,Komzpa/omim,AlexanderMatveenko/omim,ygorshenin/omim,simon247/omim,Komzpa/omim,felipebetancur/omim,simon247/omim,VladiMihaylenko/omim,therearesomewhocallmetim/omim,Endika/omim,augmify/omim,VladiMihaylenko/omim,alexzatsepin/omim,mapsme/omim,jam891/omim,programming086/omim,sidorov-panda/omim,65apps/omim,darina/omim,Saicheg/omim,goblinr/omim,edl00k/omim,sidorov-panda/omim,stangls/omim,Zverik/omim,victorbriz/omim,matsprea/omim,igrechuhin/omim,Endika/omim,goblinr/omim,vasilenkomike/omim,igrechuhin/omim,rokuz/omim,programming086/omim,darina/omim,edl00k/omim,mgsergio/omim,wersoo/omim,VladiMihaylenko/omim,alexzatsepin/omim,matsprea/omim,Zverik/omim,guard163/omim,sidorov-panda/omim,matsprea/omim,bykoianko/omim,vasilenkomike/omim,vladon/omim,edl00k/omim,vng/omim,vladon/omim,Volcanoscar/omim,dobriy-eeh/omim,rokuz/omim,ygorshenin/omim,sidorov-panda/omim,TimurTarasenko/omim,Endika/omim,yunikkk/omim,milchakov/omim,kw217/omim,jam891/omim,syershov/omim,gardster/omim,Saicheg/omim,VladiMihaylenko/omim,TimurTarasenko/omim,therearesomewhocallmetim/omim,albertshift/omim,sidorov-panda/omim,victorbriz/omim,lydonchandra/omim,goblinr/omim,andrewshadura/omim,augmify/omim,matsprea/omim,gardster/omim,bykoianko/omim,bykoianko/omim,therearesomewhocallmetim/omim,milchakov/omim,vasilenkomike/omim,TimurTarasenko/omim,ygorshenin/omim,igrechuhin/omim,alexzatsepin/omim,ygorshenin/omim,therearesomewhocallmetim/omim,syershov/omim,lydonchandra/omim,milchakov/omim,igrechuhin/omim,65apps/omim,dobriy-eeh/omim,augmify/omim,jam891/omim,mpimenov/omim,AlexanderMatveenko/omim,edl00k/omim,rokuz/omim,VladiMihaylenko/omim,dkorolev/omim,syershov/omim,krasin/omim,65apps/omim,darina/omim,guard163/omim,goblinr/omim,wersoo/omim,rokuz/omim,krasin/omim,simon247/omim,mgsergio/omim,syershov/omim,Zverik/omim,Volcanoscar/omim,VladiMihaylenko/omim,syershov/omim,edl00k/omim,kw217/omim,stangls/omim,milchakov/omim,dobriy-eeh/omim,trashkalmar/omim,edl00k/omim,mapsme/omim,mapsme/omim,edl00k/omim,stangls/omim,alexzatsepin/omim,milchakov/omim,Komzpa/omim,krasin/omim,dkorolev/omim,mapsme/omim,lydonchandra/omim,ygorshenin/omim,65apps/omim,dobriy-eeh/omim,darina/omim,stangls/omim,matsprea/omim,programming086/omim,stangls/omim,Transtech/omim,guard163/omim,therearesomewhocallmetim/omim,igrechuhin/omim,vladon/omim,UdjinM6/omim,syershov/omim,andrewshadura/omim,felipebetancur/omim,mapsme/omim,milchakov/omim,trashkalmar/omim,stangls/omim,edl00k/omim,yunikkk/omim,rokuz/omim,krasin/omim,simon247/omim,VladiMihaylenko/omim,AlexanderMatveenko/omim,rokuz/omim,Endika/omim,gardster/omim,augmify/omim,programming086/omim,bykoianko/omim,krasin/omim,jam891/omim,Transtech/omim,Komzpa/omim,therearesomewhocallmetim/omim,mgsergio/omim,wersoo/omim,dkorolev/omim,felipebetancur/omim,goblinr/omim,krasin/omim,vladon/omim,gardster/omim,trashkalmar/omim,wersoo/omim,victorbriz/omim,andrewshadura/omim,yunikkk/omim,TimurTarasenko/omim,bykoianko/omim,VladiMihaylenko/omim,igrechuhin/omim,felipebetancur/omim,victorbriz/omim,gardster/omim,mapsme/omim,syershov/omim,albertshift/omim,felipebetancur/omim,ygorshenin/omim,Transtech/omim,alexzatsepin/omim,guard163/omim,darina/omim,krasin/omim,Komzpa/omim,jam891/omim,rokuz/omim,bykoianko/omim,milchakov/omim,UdjinM6/omim,Transtech/omim,65apps/omim,mapsme/omim,simon247/omim,Zverik/omim,augmify/omim,VladiMihaylenko/omim,TimurTarasenko/omim,milchakov/omim,darina/omim,UdjinM6/omim,Transtech/omim,albertshift/omim,ygorshenin/omim,simon247/omim,yunikkk/omim,simon247/omim,igrechuhin/omim,goblinr/omim,Saicheg/omim,mpimenov/omim,programming086/omim,matsprea/omim,vasilenkomike/omim,lydonchandra/omim,65apps/omim,lydonchandra/omim,UdjinM6/omim,kw217/omim,mgsergio/omim,mpimenov/omim,Saicheg/omim,milchakov/omim,UdjinM6/omim,vladon/omim,lydonchandra/omim,sidorov-panda/omim,mgsergio/omim,Endika/omim,syershov/omim,dobriy-eeh/omim,wersoo/omim,Volcanoscar/omim,UdjinM6/omim,guard163/omim,mpimenov/omim,augmify/omim,VladiMihaylenko/omim,65apps/omim,yunikkk/omim,trashkalmar/omim,gardster/omim,bykoianko/omim,mapsme/omim,krasin/omim,matsprea/omim,guard163/omim,mpimenov/omim,wersoo/omim,programming086/omim,mapsme/omim,igrechuhin/omim,therearesomewhocallmetim/omim,goblinr/omim,syershov/omim,programming086/omim,mgsergio/omim,dobriy-eeh/omim,matsprea/omim,darina/omim,gardster/omim,augmify/omim,sidorov-panda/omim,krasin/omim,Volcanoscar/omim,Volcanoscar/omim,ygorshenin/omim,vasilenkomike/omim,dobriy-eeh/omim,trashkalmar/omim,Saicheg/omim
package com.mapswithme.yopme; import java.io.File; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.NumberFormat; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Bitmap; import android.location.Location; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.mapswithme.location.LocationRequester; import com.mapswithme.maps.api.MWMPoint; import com.mapswithme.yopme.map.MapData; import com.mapswithme.yopme.map.MapDataProvider; import com.mapswithme.yopme.map.MapRenderer; import com.yotadevices.sdk.BSActivity; import com.yotadevices.sdk.BSDrawer.Waveform; import com.yotadevices.sdk.BSMotionEvent; import com.yotadevices.sdk.Constants.Gestures; public class BackscreenActivity extends BSActivity { private final static String AUTHORITY = "com.mapswithme.yopme"; private final static String TAG = "YOPME"; public final static String EXTRA_MODE = AUTHORITY + ".mode"; public final static String EXTRA_POINT = AUTHORITY + ".point"; public final static String EXTRA_ZOOM = AUTHORITY + ".zoom"; public final static String EXTRA_LOCATION = AUTHORITY + ".location"; public enum Mode { LOCATION, POI, } /// @name Save to state. //@{ private MWMPoint mPoint = null; private Mode mMode = Mode.LOCATION; private double mZoomLevel = MapDataProvider.ZOOM_DEFAULT; private Location mLocation = null; //@} protected View mView; protected ImageView mMapView; protected TextView mPoiText; protected TextView mPoiDist; protected TextView mWaitMessage; protected View mWaitScreen; protected View mPoiInfo; protected MapDataProvider mMapDataProvider; private LocationRequester mLocationManager; private final Runnable mInvalidateDrawable = new Runnable() { @Override public void run() { draw(); } }; private final Handler mHandler = new Handler(); private final static long REDRAW_MIN_INTERVAL = 333; @Override protected void onBSCreate() { super.onBSCreate(); final String extStoragePath = getDataStoragePath(); final String extTmpPath = getTempPath(); // Create folders if they don't exist new File(extStoragePath).mkdirs(); new File(extTmpPath).mkdirs(); nativeInitPlatform(getApkPath(), extStoragePath, extTmpPath, "", true, Build.DEVICE.equals("yotaphone")); /// !!! Create MapRenderer ONLY AFTER platform init !!! //final Resources res = getResources(); //mMapDataProvider = new MapRenderer((int) res.getDimension(R.dimen.yota_width), // (int)res.getDimension(R.dimen.yota_height)); mMapDataProvider = MapRenderer.GetRenderer(); setUpView(); mLocationManager = new LocationRequester(this); } @Override protected void onBSPause() { super.onBSPause(); mLocationManager.removeUpdates(getLocationPendingIntent(this)); mHandler.removeCallbacks(mInvalidateDrawable); } @Override protected void onBSResume() { super.onBSResume(); updateData(); invalidate(); } @Override protected void onBSRestoreInstanceState(Bundle savedInstanceState) { super.onBSRestoreInstanceState(savedInstanceState); if (savedInstanceState == null) return; // Do not save and restore m_location! It's compared by getElapsedRealtimeNanos(). mPoint = (MWMPoint) savedInstanceState.getSerializable(EXTRA_POINT); mMode = (Mode) savedInstanceState.getSerializable(EXTRA_MODE); mZoomLevel = savedInstanceState.getDouble(EXTRA_ZOOM); } @Override protected void onBSSaveInstanceState(Bundle outState) { super.onBSSaveInstanceState(outState); outState.putSerializable(EXTRA_POINT, mPoint); outState.putSerializable(EXTRA_MODE, mMode); outState.putDouble(EXTRA_ZOOM, mZoomLevel); } @Override protected void onBSTouchEvent(BSMotionEvent motionEvent) { super.onBSTouchEvent(motionEvent); final Gestures action = motionEvent.getBSAction(); if (action == Gestures.GESTURES_BS_SINGLE_TAP) requestLocationUpdate(); else if (action == Gestures.GESTURES_BS_LR) { if (!zoomOut()) return; } else if (action == Gestures.GESTURES_BS_RL) { if (!zoomIn()) return; } else return; // do not react on other events updateData(); invalidate(); } @Override protected void onHandleIntent(Intent intent) { super.onHandleIntent(intent); if (intent.hasExtra(LocationManager.KEY_LOCATION_CHANGED)) { if (updateWithLocation((Location) intent.getParcelableExtra(LocationManager.KEY_LOCATION_CHANGED))) return; } else if (intent.hasExtra(EXTRA_MODE)) { mMode = (Mode) intent.getSerializableExtra(EXTRA_MODE); mPoint = (MWMPoint) intent.getSerializableExtra(EXTRA_POINT); mZoomLevel = intent.getDoubleExtra(EXTRA_ZOOM, MapDataProvider.COMFORT_ZOOM); } // Do always update data. // This function is called from back screen menu without any extras. requestLocationUpdate(); updateData(); invalidate(); } public void setUpView() { mView = View.inflate(this, R.layout.yota_backscreen, null); mMapView = (ImageView) mView.findViewById(R.id.map); mPoiText = (TextView) mView.findViewById(R.id.poiText); mPoiDist = (TextView) mView.findViewById(R.id.poiDist); mWaitMessage = (TextView) mView.findViewById(R.id.waitMsg); mWaitScreen = mView.findViewById(R.id.waitScreen); mPoiInfo = mView.findViewById(R.id.poiInfo); } public void invalidate() { mHandler.removeCallbacks(mInvalidateDrawable); mHandler.postDelayed(mInvalidateDrawable, REDRAW_MIN_INTERVAL); } private boolean zoomIn() { if (mZoomLevel < MapDataProvider.MAX_ZOOM) { ++mZoomLevel; return true; } return false; } private boolean zoomOut() { if (mZoomLevel > MapDataProvider.MIN_ZOOM) { --mZoomLevel; return true; } return false; } protected void draw() { if (mView != null) getBSDrawer().drawBitmap(mView, Waveform.WAVEFORM_GC_FULL); } private void requestLocationUpdate() { final String updateIntervalStr = PreferenceManager.getDefaultSharedPreferences(this) .getString(getString(R.string.pref_loc_update), YopmePreference.LOCATION_UPDATE_DEFAULT); final long updateInterval = Long.parseLong(updateIntervalStr); // before requesting updates try to get last known in the first try if (mLocation == null) mLocation = mLocationManager.getLastLocation(); // then listen to updates final PendingIntent pi = getLocationPendingIntent(this); if (updateInterval == -1) mLocationManager.requestSingleUpdate(pi, 60*1000); else mLocationManager.requestLocationUpdates(updateInterval*1000, 5.0f, pi); } private boolean updateWithLocation(Location location) { if (LocationRequester.isFirstOneBetterLocation(location, mLocation)) { mLocation = location; updateData(); invalidate(); return true; } return false; } private void onLocationUpdate(Location location) { updateWithLocation(location); } private void showWaitMessage(CharSequence msg) { mWaitMessage.setText(msg); mWaitScreen.setVisibility(View.VISIBLE); } private void hideWaitMessage() { mWaitScreen.setVisibility(View.GONE); } private final static NumberFormat df = DecimalFormat.getInstance(); static { df.setRoundingMode(RoundingMode.DOWN); } private void setDistance(double distance) { if (distance < 0) mPoiDist.setVisibility(View.GONE); else { String suffix = "m"; double div = 1; df.setMaximumFractionDigits(0); if (distance >= 1000) { suffix = "km"; div = 1000; // set fraction digits only in [1..10) kilometers range if (distance < 10000) df.setMaximumFractionDigits(2); } mPoiDist.setText(df.format(distance/div) + suffix); mPoiDist.setVisibility(View.VISIBLE); } } public void updateData() { if (mZoomLevel < MapDataProvider.MIN_ZOOM) mZoomLevel = MapDataProvider.MIN_ZOOM; MapData data = null; if (mMode == null) { Log.d(TAG, "Unknown mode"); return; } if (mMode == Mode.LOCATION) { mPoiInfo.setVisibility(View.GONE); if (mLocation == null) { showWaitMessage(getString(R.string.wait_msg)); return; } data = mMapDataProvider.getMyPositionData(mLocation.getLatitude(), mLocation.getLongitude(), mZoomLevel); } else if (mMode == Mode.POI) { mPoiInfo.setVisibility(View.VISIBLE); if (mLocation != null) data = mMapDataProvider.getPOIData(mPoint, mZoomLevel, true, mLocation.getLatitude(), mLocation.getLongitude()); else data = mMapDataProvider.getPOIData(mPoint, mZoomLevel, false, 0, 0); if (mLocation != null && mPoint != null) { final Location poiLoc = new Location(""); poiLoc.setLatitude(mPoint.getLat()); poiLoc.setLongitude(mPoint.getLon()); setDistance(poiLoc.distanceTo(mLocation)); } } final Bitmap bitmap = data.getBitmap(); mMapView.setImageBitmap(bitmap); if (bitmap == null) { // this means we don't have this map showWaitMessage(getString(R.string.error_map_is_absent)); return; } else hideWaitMessage(); if (mMode == Mode.POI) mPoiText.setText(mPoint.getName()); } public static void startInMode(Context context, Mode mode, MWMPoint point, double zoom) { final Intent i = new Intent(context, BackscreenActivity.class) .putExtra(EXTRA_MODE, mode) .putExtra(EXTRA_POINT, point) .putExtra(EXTRA_ZOOM, zoom >= MapDataProvider.MIN_ZOOM ? zoom : MapDataProvider.ZOOM_DEFAULT); context.startService(i); } public static PendingIntent getLocationPendingIntent(Context context) { final Intent i = new Intent(context, BackscreenActivity.class); final PendingIntent pi = PendingIntent.getService(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT); return pi; } public String getApkPath() { try { return getPackageManager().getApplicationInfo(getPackageName(), 0).sourceDir; } catch (final NameNotFoundException e) { return ""; } } public String getDataStoragePath() { return Environment.getExternalStorageDirectory().getAbsolutePath() + "/MapsWithMe/"; } public String getTempPath() { // Can't use getExternalCacheDir() here because of API level = 7. return getExtAppDirectoryPath("cache"); } public String getExtAppDirectoryPath(String folder) { final String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath(); return storagePath.concat(String.format("/Android/data/%s/%s/", getPackageName(), folder)); } private String getOBBGooglePath() { final String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath(); return storagePath.concat(String.format("/Android/obb/%s/", getPackageName())); } static { System.loadLibrary("yopme"); } private native void nativeInitPlatform(String apkPath, String storagePath, String tmpPath, String obbGooglePath, boolean isPro, boolean isYota); }
android/YoPme/src/com/mapswithme/yopme/BackscreenActivity.java
package com.mapswithme.yopme; import java.io.File; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.NumberFormat; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Bitmap; import android.location.Location; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.mapswithme.location.LocationRequester; import com.mapswithme.maps.api.MWMPoint; import com.mapswithme.yopme.map.MapData; import com.mapswithme.yopme.map.MapDataProvider; import com.mapswithme.yopme.map.MapRenderer; import com.yotadevices.sdk.BSActivity; import com.yotadevices.sdk.BSDrawer.Waveform; import com.yotadevices.sdk.BSMotionEvent; import com.yotadevices.sdk.Constants.Gestures; public class BackscreenActivity extends BSActivity { private final static String AUTHORITY = "com.mapswithme.yopme"; private final static String TAG = "YOPME"; public final static String EXTRA_MODE = AUTHORITY + ".mode"; public final static String EXTRA_POINT = AUTHORITY + ".point"; public final static String EXTRA_ZOOM = AUTHORITY + ".zoom"; public final static String EXTRA_LOCATION = AUTHORITY + ".location"; public enum Mode { LOCATION, POI, } /// @name Save to state. //@{ private MWMPoint mPoint = null; private Mode mMode = Mode.LOCATION; private double mZoomLevel = MapDataProvider.ZOOM_DEFAULT; private Location mLocation = null; //@} protected View mView; protected ImageView mMapView; protected TextView mPoiText; protected TextView mPoiDist; protected TextView mWaitMessage; protected View mWaitScreen; protected View mPoiInfo; protected MapDataProvider mMapDataProvider; private LocationRequester mLocationManager; private final Runnable mInvalidateDrawable = new Runnable() { @Override public void run() { draw(); } }; private final Handler mHandler = new Handler(); private final static long REDRAW_MIN_INTERVAL = 333; @Override protected void onBSCreate() { super.onBSCreate(); final String extStoragePath = getDataStoragePath(); final String extTmpPath = getTempPath(); // Create folders if they don't exist new File(extStoragePath).mkdirs(); new File(extTmpPath).mkdirs(); nativeInitPlatform(getApkPath(), extStoragePath, extTmpPath, "", true, Build.DEVICE.equals("yotaphone")); /// !!! Create MapRenderer ONLY AFTER platform init !!! //final Resources res = getResources(); //mMapDataProvider = new MapRenderer((int) res.getDimension(R.dimen.yota_width), // (int)res.getDimension(R.dimen.yota_height)); mMapDataProvider = MapRenderer.GetRenderer(); setUpView(); mLocationManager = new LocationRequester(this); } @Override protected void onBSPause() { super.onBSPause(); mLocationManager.removeUpdates(getLocationPendingIntent(this)); mHandler.removeCallbacks(mInvalidateDrawable); } @Override protected void onBSResume() { super.onBSResume(); updateData(); invalidate(); } @Override protected void onBSRestoreInstanceState(Bundle savedInstanceState) { super.onBSRestoreInstanceState(savedInstanceState); if (savedInstanceState == null) return; // Do not save and restore m_location! It's compared by getElapsedRealtimeNanos(). mPoint = (MWMPoint) savedInstanceState.getSerializable(EXTRA_POINT); mMode = (Mode) savedInstanceState.getSerializable(EXTRA_MODE); mZoomLevel = savedInstanceState.getDouble(EXTRA_ZOOM); } @Override protected void onBSSaveInstanceState(Bundle outState) { super.onBSSaveInstanceState(outState); outState.putSerializable(EXTRA_POINT, mPoint); outState.putSerializable(EXTRA_MODE, mMode); outState.putDouble(EXTRA_ZOOM, mZoomLevel); } @Override protected void onBSTouchEvent(BSMotionEvent motionEvent) { super.onBSTouchEvent(motionEvent); final Gestures action = motionEvent.getBSAction(); if (action == Gestures.GESTURES_BS_SINGLE_TAP) requestLocationUpdate(); else if (action == Gestures.GESTURES_BS_LR) { if (!zoomIn()) return; } else if (action == Gestures.GESTURES_BS_RL) { if (!zoomOut()) return; } else return; // do not react on other events updateData(); invalidate(); } @Override protected void onHandleIntent(Intent intent) { super.onHandleIntent(intent); if (intent.hasExtra(LocationManager.KEY_LOCATION_CHANGED)) { if (updateWithLocation((Location) intent.getParcelableExtra(LocationManager.KEY_LOCATION_CHANGED))) return; } else if (intent.hasExtra(EXTRA_MODE)) { mMode = (Mode) intent.getSerializableExtra(EXTRA_MODE); mPoint = (MWMPoint) intent.getSerializableExtra(EXTRA_POINT); mZoomLevel = intent.getDoubleExtra(EXTRA_ZOOM, MapDataProvider.COMFORT_ZOOM); } // Do always update data. // This function is called from back screen menu without any extras. requestLocationUpdate(); updateData(); invalidate(); } public void setUpView() { mView = View.inflate(this, R.layout.yota_backscreen, null); mMapView = (ImageView) mView.findViewById(R.id.map); mPoiText = (TextView) mView.findViewById(R.id.poiText); mPoiDist = (TextView) mView.findViewById(R.id.poiDist); mWaitMessage = (TextView) mView.findViewById(R.id.waitMsg); mWaitScreen = mView.findViewById(R.id.waitScreen); mPoiInfo = mView.findViewById(R.id.poiInfo); } public void invalidate() { mHandler.removeCallbacks(mInvalidateDrawable); mHandler.postDelayed(mInvalidateDrawable, REDRAW_MIN_INTERVAL); } private boolean zoomIn() { if (mZoomLevel < MapDataProvider.MAX_ZOOM) { ++mZoomLevel; return true; } return false; } private boolean zoomOut() { if (mZoomLevel > MapDataProvider.MIN_ZOOM) { --mZoomLevel; return true; } return false; } protected void draw() { if (mView != null) getBSDrawer().drawBitmap(mView, Waveform.WAVEFORM_GC_FULL); } private void requestLocationUpdate() { final String updateIntervalStr = PreferenceManager.getDefaultSharedPreferences(this) .getString(getString(R.string.pref_loc_update), YopmePreference.LOCATION_UPDATE_DEFAULT); final long updateInterval = Long.parseLong(updateIntervalStr); // before requesting updates try to get last known in the first try if (mLocation == null) mLocation = mLocationManager.getLastLocation(); // then listen to updates final PendingIntent pi = getLocationPendingIntent(this); if (updateInterval == -1) mLocationManager.requestSingleUpdate(pi, 60*1000); else mLocationManager.requestLocationUpdates(updateInterval*1000, 5.0f, pi); } private boolean updateWithLocation(Location location) { if (LocationRequester.isFirstOneBetterLocation(location, mLocation)) { mLocation = location; updateData(); invalidate(); return true; } return false; } private void onLocationUpdate(Location location) { updateWithLocation(location); } private void showWaitMessage(CharSequence msg) { mWaitMessage.setText(msg); mWaitScreen.setVisibility(View.VISIBLE); } private void hideWaitMessage() { mWaitScreen.setVisibility(View.GONE); } private final static NumberFormat df = DecimalFormat.getInstance(); static { df.setRoundingMode(RoundingMode.DOWN); } private void setDistance(double distance) { if (distance < 0) mPoiDist.setVisibility(View.GONE); else { String suffix = "m"; double div = 1; df.setMaximumFractionDigits(0); if (distance >= 1000) { suffix = "km"; div = 1000; // set fraction digits only in [1..10) kilometers range if (distance < 10000) df.setMaximumFractionDigits(2); } mPoiDist.setText(df.format(distance/div) + suffix); mPoiDist.setVisibility(View.VISIBLE); } } public void updateData() { if (mZoomLevel < MapDataProvider.MIN_ZOOM) mZoomLevel = MapDataProvider.MIN_ZOOM; MapData data = null; if (mMode == null) { Log.d(TAG, "Unknown mode"); return; } if (mMode == Mode.LOCATION) { mPoiInfo.setVisibility(View.GONE); if (mLocation == null) { showWaitMessage(getString(R.string.wait_msg)); return; } data = mMapDataProvider.getMyPositionData(mLocation.getLatitude(), mLocation.getLongitude(), mZoomLevel); } else if (mMode == Mode.POI) { mPoiInfo.setVisibility(View.VISIBLE); if (mLocation != null) data = mMapDataProvider.getPOIData(mPoint, mZoomLevel, true, mLocation.getLatitude(), mLocation.getLongitude()); else data = mMapDataProvider.getPOIData(mPoint, mZoomLevel, false, 0, 0); if (mLocation != null && mPoint != null) { final Location poiLoc = new Location(""); poiLoc.setLatitude(mPoint.getLat()); poiLoc.setLongitude(mPoint.getLon()); setDistance(poiLoc.distanceTo(mLocation)); } } final Bitmap bitmap = data.getBitmap(); mMapView.setImageBitmap(bitmap); if (bitmap == null) { // this means we don't have this map showWaitMessage(getString(R.string.error_map_is_absent)); return; } else hideWaitMessage(); if (mMode == Mode.POI) mPoiText.setText(mPoint.getName()); } public static void startInMode(Context context, Mode mode, MWMPoint point, double zoom) { final Intent i = new Intent(context, BackscreenActivity.class) .putExtra(EXTRA_MODE, mode) .putExtra(EXTRA_POINT, point) .putExtra(EXTRA_ZOOM, zoom >= MapDataProvider.MIN_ZOOM ? zoom : MapDataProvider.ZOOM_DEFAULT); context.startService(i); } public static PendingIntent getLocationPendingIntent(Context context) { final Intent i = new Intent(context, BackscreenActivity.class); final PendingIntent pi = PendingIntent.getService(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT); return pi; } public String getApkPath() { try { return getPackageManager().getApplicationInfo(getPackageName(), 0).sourceDir; } catch (final NameNotFoundException e) { return ""; } } public String getDataStoragePath() { return Environment.getExternalStorageDirectory().getAbsolutePath() + "/MapsWithMe/"; } public String getTempPath() { // Can't use getExternalCacheDir() here because of API level = 7. return getExtAppDirectoryPath("cache"); } public String getExtAppDirectoryPath(String folder) { final String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath(); return storagePath.concat(String.format("/Android/data/%s/%s/", getPackageName(), folder)); } private String getOBBGooglePath() { final String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath(); return storagePath.concat(String.format("/Android/obb/%s/", getPackageName())); } static { System.loadLibrary("yopme"); } private native void nativeInitPlatform(String apkPath, String storagePath, String tmpPath, String obbGooglePath, boolean isPro, boolean isYota); }
[yopme] RightLeft - zoom in; LeftRight - zoom out.
android/YoPme/src/com/mapswithme/yopme/BackscreenActivity.java
[yopme] RightLeft - zoom in; LeftRight - zoom out.
<ide><path>ndroid/YoPme/src/com/mapswithme/yopme/BackscreenActivity.java <ide> requestLocationUpdate(); <ide> else if (action == Gestures.GESTURES_BS_LR) <ide> { <add> if (!zoomOut()) <add> return; <add> } <add> else if (action == Gestures.GESTURES_BS_RL) <add> { <ide> if (!zoomIn()) <del> return; <del> } <del> else if (action == Gestures.GESTURES_BS_RL) <del> { <del> if (!zoomOut()) <ide> return; <ide> } <ide> else
Java
apache-2.0
e5f224b2faa38de4d973f70a5394a3de953bd32e
0
PDXFinder/pdxfinder,PDXFinder/pdxfinder,PDXFinder/pdxfinder,PDXFinder/pdxfinder
package org.pdxfinder.repositories; import org.pdxfinder.dao.Patient; import org.pdxfinder.dao.PatientSnapshot; import org.springframework.data.neo4j.annotation.Query; import org.springframework.data.neo4j.repository.Neo4jRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.Set; @Repository public interface PatientSnapshotRepository extends Neo4jRepository<PatientSnapshot, Long> { Set<Patient> findByAge(String sex); Set<Patient> findByPatientSex(String sex); Patient findByPatientExternalId(String externalId); @Query("MATCH (ps:PatientSnapshot)--(p:Patient) WHERE p.externalId = {patientId} RETURN ps") Set<PatientSnapshot> findByPatient(@Param("patientId") String patientId); @Query("MATCH (mod:ModelCreation)-[ii:IMPLANTED_IN]-(s:Sample)-[sf:SAMPLED_FROM]-(ps:PatientSnapshot)" + "WHERE mod.sourcePdxId = {modelId} " + "RETURN mod,ii,s,sf,ps") PatientSnapshot findByModelId(@Param("modelId") String modelId); }
data-model/src/main/java/org/pdxfinder/repositories/PatientSnapshotRepository.java
package org.pdxfinder.repositories; import org.pdxfinder.dao.Patient; import org.pdxfinder.dao.PatientSnapshot; import org.springframework.data.neo4j.annotation.Query; import org.springframework.data.neo4j.repository.Neo4jRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.Set; @Repository public interface PatientSnapshotRepository extends Neo4jRepository<PatientSnapshot, Long> { Set<Patient> findByAge(String sex); Set<Patient> findByPatientSex(String sex); Patient findByPatientExternalId(String externalId); Set<PatientSnapshot> findByPatient(Patient patient); @Query("MATCH (mod:ModelCreation)-[ii:IMPLANTED_IN]-(s:Sample)-[sf:SAMPLED_FROM]-(ps:PatientSnapshot)" + "WHERE mod.sourcePdxId = {modelId} " + "RETURN mod,ii,s,sf,ps") PatientSnapshot findByModelId(@Param("modelId") String modelId); }
Do not create snapshot node if age is the same
data-model/src/main/java/org/pdxfinder/repositories/PatientSnapshotRepository.java
Do not create snapshot node if age is the same
<ide><path>ata-model/src/main/java/org/pdxfinder/repositories/PatientSnapshotRepository.java <ide> Set<Patient> findByPatientSex(String sex); <ide> <ide> Patient findByPatientExternalId(String externalId); <del> <del> Set<PatientSnapshot> findByPatient(Patient patient); <add> <add> @Query("MATCH (ps:PatientSnapshot)--(p:Patient) WHERE p.externalId = {patientId} RETURN ps") <add> Set<PatientSnapshot> findByPatient(@Param("patientId") String patientId); <ide> <ide> @Query("MATCH (mod:ModelCreation)-[ii:IMPLANTED_IN]-(s:Sample)-[sf:SAMPLED_FROM]-(ps:PatientSnapshot)" + <ide> "WHERE mod.sourcePdxId = {modelId} " +
JavaScript
mit
bb76969d390e011eb2ca38aa47f5727fbec00fbc
0
jammiemountz/mojsart,jammiemountz/mojsart,mojsart/mojsart,jammiemountz/mojsart,mojsart/mojsart
"use strict"; var mongoose = require('mongoose'); var SongSchema = new mongoose.Schema({ echoData: { artist: String, title: String, // md5 for uploaded songs md5: String, // id for the rest id: String, status: String, audio_summary: { danceability: Number, duration: Number, energy: Number, key: Number, loudness: Number, speechiness: Number, acousticness: Number, liveness: Number, tempo: Number } }, // TODO: Allow User Data userData: { speechiness: Number, acousticness: Number }, uri: String }); SongSchema.methods.adjust = function(compare, increment) { console.log('adjusting', this.echoData.title, 'and', compare.echoData.title, 'with increment', increment); // TODO: write adjusting function }; module.exports = exports = mongoose.model('Song', SongSchema);
server/song/song_model.js
"use strict"; var mongoose = require('mongoose'); var SongSchema = new mongoose.Schema({ echoData: { artist: String, title: String, // md5 for uploaded songs md5: String, // id for the rest id: String, status: String, audio_summary: { danceability: Number, duration: Number, energy: Number, key: Number, loudness: Number, speechiness: Number, acousticness: Number, liveness: Number, tempo: Number } }, // TODO: Allow User Data userData: { speechiness: Number, acousticness: Number }, uri: String }); module.exports = exports = mongoose.model('Song', SongSchema);
Begin work on SongSchema.methods.adjust
server/song/song_model.js
Begin work on SongSchema.methods.adjust
<ide><path>erver/song/song_model.js <ide> uri: String <ide> }); <ide> <add>SongSchema.methods.adjust = function(compare, increment) { <add> console.log('adjusting', this.echoData.title, 'and', compare.echoData.title, 'with increment', increment); <add> // TODO: write adjusting function <add>}; <add> <ide> module.exports = exports = mongoose.model('Song', SongSchema);
Java
apache-2.0
aaf4c901a798ee12b678fcaf5a64a40954b5c0f1
0
sherbold/CrossPare
package de.ugoe.cs.cpdp.training; import java.util.LinkedList; import java.util.List; import org.apache.commons.collections4.list.SetUniqueList; import weka.classifiers.AbstractClassifier; import weka.classifiers.Classifier; import weka.core.Instance; import weka.core.Instances; import org.apache.commons.lang3.ArrayUtils; import org.jgap.Configuration; import org.jgap.InvalidConfigurationException; import org.jgap.gp.CommandGene; import org.jgap.gp.GPProblem; import org.jgap.gp.function.Add; import org.jgap.gp.function.Multiply; import org.jgap.gp.function.Log; import org.jgap.gp.function.Subtract; import org.jgap.gp.function.Divide; import org.jgap.gp.function.Sine; import org.jgap.gp.function.Cosine; import org.jgap.gp.function.Max; import org.jgap.gp.function.Exp; import org.jgap.gp.impl.DeltaGPFitnessEvaluator; import org.jgap.gp.impl.GPConfiguration; import org.jgap.gp.impl.GPGenotype; import org.jgap.gp.impl.TournamentSelector; import org.jgap.gp.terminal.Terminal; import org.jgap.gp.GPFitnessFunction; import org.jgap.gp.IGPProgram; import org.jgap.gp.terminal.Variable; import org.jgap.gp.MathCommand; import org.jgap.util.ICloneable; import de.ugoe.cs.cpdp.util.WekaUtils; import org.jgap.gp.impl.ProgramChromosome; import org.jgap.util.CloneException; /** * Genetic Programming Trainer * * Implementation (mostly) according to Liu et al. Evolutionary Optimization of Software Quality Modeling with Multiple Repositories. * * - GPRun is a Run of a complete Genetic Programm Evolution, we want several complete runs. * - GPVClassifier is the Validation Classifier * - GPVVClassifier is the Validation-Voting Classifier * * config: <setwisetrainer name="GPTraining" param="populationSize:1000,numberRuns:10" /> */ public class GPTraining implements ISetWiseTrainingStrategy, IWekaCompatibleTrainer { private GPVVClassifier classifier = null; // default values from the paper private int populationSize = 1000; private int initMinDepth = 2; private int initMaxDepth = 6; private int tournamentSize = 7; private int maxGenerations = 50; private double errorType2Weight = 15; private int numberRuns = 20; // im paper 20 per errorType2Weight then additional 20 private int maxDepth = 20; // max depth within one program private int maxNodes = 100; // max nodes within one program @Override public void setParameter(String parameters) { String[] params = parameters.split(","); String[] keyvalue = new String[2]; for(int i=0; i < params.length; i++) { keyvalue = params[i].split(":"); switch(keyvalue[0]) { case "populationSize": this.populationSize = Integer.parseInt(keyvalue[1]); break; case "initMinDepth": this.initMinDepth = Integer.parseInt(keyvalue[1]); break; case "tournamentSize": this.tournamentSize = Integer.parseInt(keyvalue[1]); break; case "maxGenerations": this.maxGenerations = Integer.parseInt(keyvalue[1]); break; case "errorType2Weight": this.errorType2Weight = Double.parseDouble(keyvalue[1]); break; case "numberRuns": this.numberRuns = Integer.parseInt(keyvalue[1]); break; case "maxDepth": this.maxDepth = Integer.parseInt(keyvalue[1]); break; case "maxNodes": this.maxNodes = Integer.parseInt(keyvalue[1]); break; } } this.classifier = new GPVVClassifier(); ((GPVClassifier)this.classifier).configure(populationSize, initMinDepth, initMaxDepth, tournamentSize, maxGenerations, errorType2Weight, numberRuns, maxDepth, maxNodes); } @Override public void apply(SetUniqueList<Instances> traindataSet) { try { classifier.buildClassifier(traindataSet); }catch(Exception e) { throw new RuntimeException(e); } } @Override public String getName() { return "GPTraining"; } @Override public Classifier getClassifier() { return this.classifier; } public class InstanceData { private double[][] instances_x; private boolean[] instances_y; public InstanceData(Instances instances) { this.instances_x = new double[instances.numInstances()][instances.numAttributes()-1]; this.instances_y = new boolean[instances.numInstances()]; Instance current; for(int i=0; i < this.instances_x.length; i++) { current = instances.get(i); this.instances_x[i] = WekaUtils.instanceValues(current); this.instances_y[i] = 1.0 == current.classValue(); } } public double[][] getX() { return instances_x; } public boolean[] getY() { return instances_y; } } /** * One Run executed by a GP Classifier */ public class GPRun extends AbstractClassifier { private static final long serialVersionUID = -4250422550107888789L; private int populationSize; private int initMinDepth; private int initMaxDepth; private int tournamentSize; private int maxGenerations; private double errorType2Weight; private int maxDepth; private int maxNodes; private GPGenotype gp; private GPProblem problem; public void configure(int populationSize, int initMinDepth, int initMaxDepth, int tournamentSize, int maxGenerations, double errorType2Weight, int maxDepth, int maxNodes) { this.populationSize = populationSize; this.initMinDepth = initMinDepth; this.initMaxDepth = initMaxDepth; this.tournamentSize = tournamentSize; this.maxGenerations = maxGenerations; this.errorType2Weight = errorType2Weight; this.maxDepth = maxDepth; this.maxNodes = maxNodes; } public GPGenotype getGp() { return this.gp; } public Variable[] getVariables() { return ((CrossPareGP)this.problem).getVariables(); } @Override public void buildClassifier(Instances traindata) throws Exception { InstanceData train = new InstanceData(traindata); this.problem = new CrossPareGP(train.getX(), train.getY(), this.populationSize, this.initMinDepth, this.initMaxDepth, this.tournamentSize, this.errorType2Weight, this.maxDepth, this.maxNodes); this.gp = problem.create(); this.gp.evolve(this.maxGenerations); } /** * GPProblem implementation */ class CrossPareGP extends GPProblem { private double[][] instances; private boolean[] output; private int maxDepth; private int maxNodes; private Variable[] x; public CrossPareGP(double[][] instances, boolean[] output, int populationSize, int minInitDept, int maxInitDepth, int tournamentSize, double errorType2Weight, int maxDepth, int maxNodes) throws InvalidConfigurationException { super(new GPConfiguration()); this.instances = instances; this.output = output; this.maxDepth = maxDepth; this.maxNodes = maxNodes; Configuration.reset(); GPConfiguration config = this.getGPConfiguration(); this.x = new Variable[this.instances[0].length]; for(int j=0; j < this.x.length; j++) { this.x[j] = Variable.create(config, "X"+j, CommandGene.DoubleClass); } config.setGPFitnessEvaluator(new DeltaGPFitnessEvaluator()); // smaller fitness is better //config.setGPFitnessEvaluator(new DefaultGPFitnessEvaluator()); // bigger fitness is better config.setMinInitDepth(minInitDept); config.setMaxInitDepth(maxInitDepth); config.setCrossoverProb((float)0.60); config.setReproductionProb((float)0.10); config.setMutationProb((float)0.30); config.setSelectionMethod(new TournamentSelector(tournamentSize)); config.setPopulationSize(populationSize); config.setMaxCrossoverDepth(4); config.setFitnessFunction(new CrossPareFitness(this.x, this.instances, this.output, errorType2Weight)); config.setStrictProgramCreation(true); } // used for running the fitness function again for testing public Variable[] getVariables() { return this.x; } public GPGenotype create() throws InvalidConfigurationException { GPConfiguration config = this.getGPConfiguration(); // return type Class[] types = {CommandGene.DoubleClass}; // Arguments of result-producing chromosome: none Class[][] argTypes = { {} }; // variables + functions, we set the variables with the values of the instances here CommandGene[] vars = new CommandGene[this.instances[0].length]; for(int j=0; j < this.instances[0].length; j++) { vars[j] = this.x[j]; } CommandGene[] funcs = { new Add(config, CommandGene.DoubleClass), new Subtract(config, CommandGene.DoubleClass), new Multiply(config, CommandGene.DoubleClass), new Divide(config, CommandGene.DoubleClass), new Sine(config, CommandGene.DoubleClass), new Cosine(config, CommandGene.DoubleClass), new Exp(config, CommandGene.DoubleClass), new Log(config, CommandGene.DoubleClass), new GT(config, CommandGene.DoubleClass), new Max(config, CommandGene.DoubleClass), new Terminal(config, CommandGene.DoubleClass, -100.0, 100.0, true), // min, max, whole numbers }; CommandGene[] comb = (CommandGene[])ArrayUtils.addAll(vars, funcs); CommandGene[][] nodeSets = { comb, }; // we only have one chromosome so this suffices int minDepths[] = {config.getMinInitDepth()}; int maxDepths[] = {this.maxDepth}; GPGenotype result = GPGenotype.randomInitialGenotype(config, types, argTypes, nodeSets, minDepths, maxDepths, this.maxNodes, false); // 40 = maxNodes, true = verbose output return result; } } /** * Fitness function */ class CrossPareFitness extends GPFitnessFunction { private static final long serialVersionUID = 75234832484387L; private Variable[] x; private double[][] instances; private boolean[] output; private double errorType2Weight = 1.0; // needed in evaluate //private Object[] NO_ARGS = new Object[0]; private double sfitness = 0.0f; private int errorType1 = 0; private int errorType2 = 0; public CrossPareFitness(Variable[] x, double[][] instances, boolean[] output, double errorType2Weight) { this.x = x; this.instances = instances; this.output = output; this.errorType2Weight = errorType2Weight; } public int getErrorType1() { return this.errorType1; } public int getErrorType2() { return this.errorType2; } public double getSecondFitness() { return this.sfitness; } public int getNumInstances() { return this.instances.length; } /** * This is the fitness function * * Our fitness is best if we have the less wrong classifications, this includes a weight for type2 errors */ @Override protected double evaluate(final IGPProgram program) { double pfitness = 0.0f; this.sfitness = 0.0f; double value = 0.0f; // count classification errors this.errorType1 = 0; this.errorType2 = 0; for(int i=0; i < this.instances.length; i++) { // requires that we have a variable for each column of our dataset (attribute of instance) for(int j=0; j < this.x.length; j++) { this.x[j].set(this.instances[i][j]); } // value gives us a double, if < 0.5 we set this instance as faulty value = program.execute_double(0, this.x); if(value < 0.5) { if(this.output[i] != true) { this.errorType1 += 1; } }else { if(this.output[i] == true) { this.errorType2 += 1; } } } // now calc pfitness pfitness = (this.errorType1 + this.errorType2Weight * this.errorType2) / this.instances.length; // number of nodes in the programm, if lower then 10 we assign sFitness of 10 // we can set metadata with setProgramData to save this if(program.getChromosome(0).getSize(0) < 10) { program.setApplicationData(10.0f); } return pfitness; } } /** * Custom GT implementation used in the GP Algorithm. */ public class GT extends MathCommand implements ICloneable { private static final long serialVersionUID = 113454184817L; public GT(final GPConfiguration a_conf, java.lang.Class a_returnType) throws InvalidConfigurationException { super(a_conf, 2, a_returnType); } public String toString() { return "GT(&1, &2)"; } public String getName() { return "GT"; } public float execute_float(ProgramChromosome c, int n, Object[] args) { float f1 = c.execute_float(n, 0, args); float f2 = c.execute_float(n, 1, args); float ret = 1.0f; if(f1 > f2) { ret = 0.0f; } return ret; } public double execute_double(ProgramChromosome c, int n, Object[] args) { double f1 = c.execute_double(n, 0, args); double f2 = c.execute_double(n, 1, args); double ret = 1; if(f1 > f2) { ret = 0; } return ret; } public Object clone() { try { GT result = new GT(getGPConfiguration(), getReturnType()); return result; }catch(Exception ex) { throw new CloneException(ex); } } } } /** * GP Multiple Data Sets Validation-Voting Classifier * * Basically the same as the GP Multiple Data Sets Validation Classifier. * But here we do keep a model candidate for each training set which may later vote * */ public class GPVVClassifier extends GPVClassifier { private static final long serialVersionUID = -654710583852839901L; private List<Classifier> classifiers = null; @Override public void buildClassifier(Instances arg0) throws Exception { // TODO Auto-generated method stub } /** Build the GP Multiple Data Sets Validation-Voting Classifier * * This is according to Section 6 of the Paper by Liu et al. * It is basically the Multiple Data Sets Validation Classifier but here we keep the best models an let them vote. * * @param traindataSet * @throws Exception */ public void buildClassifier(SetUniqueList<Instances> traindataSet) throws Exception { // each classifier is trained with one project from the set // then is evaluated on the rest classifiers = new LinkedList<>(); for(int i=0; i < traindataSet.size(); i++) { // candidates we get out of evaluation LinkedList<Classifier> candidates = new LinkedList<>(); // number of runs, yields the best of these for(int k=0; k < this.numberRuns; k++) { Classifier classifier = new GPRun(); ((GPRun)classifier).configure(this.populationSize, this.initMinDepth, this.initMaxDepth, this.tournamentSize, this.maxGenerations, this.errorType2Weight, this.maxDepth, this.maxNodes); // one project is training data classifier.buildClassifier(traindataSet.get(i)); double[] errors; // rest of the set is evaluation data, we evaluate now for(int j=0; j < traindataSet.size(); j++) { if(j != i) { // if type1 and type2 errors are < 0.5 we allow the model in the candidates errors = this.evaluate((GPRun)classifier, traindataSet.get(j)); if((errors[0] < 0.5) && (errors[1] < 0.5)) { candidates.add(classifier); } } } } // now after the evaluation we do a model selection where only one model remains for the given training data // we select the model which is best on all evaluation data double smallest_error_count = Double.MAX_VALUE; double[] errors; Classifier best = null; for(int ii=0; ii < candidates.size(); ii++) { double[] errors_eval = {0.0, 0.0}; // we add the errors the candidate makes over the evaldata for(int j=0; j < traindataSet.size(); j++) { if(j != i) { errors = this.evaluate((GPRun)candidates.get(ii), traindataSet.get(j)); errors_eval[0] += errors[0]; errors_eval[1] += errors[1]; } } // if the candidate made fewer errors it is now the best if(errors_eval[0] + errors_eval[1] < smallest_error_count) { best = candidates.get(ii); smallest_error_count = errors_eval[0] + errors_eval[1]; } } // now we have the best classifier for this training data classifiers.add(best); } } /** * Use the best classifiers for each training data in a majority voting */ @Override public double classifyInstance(Instance instance) { int vote_positive = 0; for (int i = 0; i < classifiers.size(); i++) { Classifier classifier = classifiers.get(i); GPGenotype gp = ((GPRun)classifier).getGp(); Variable[] vars = ((GPRun)classifier).getVariables(); IGPProgram fitest = gp.getAllTimeBest(); // all time fitest for(int j = 0; j < instance.numAttributes()-1; j++) { vars[j].set(instance.value(j)); } if(fitest.execute_double(0, vars) < 0.5) { vote_positive += 1; } } if(vote_positive >= (classifiers.size()/2)) { return 1.0; }else { return 0.0; } } } /** * GP Multiple Data Sets Validation Classifier * * We train a Classifier with one training project $numberRun times. * Then we evaluate the classifier on the rest of the training projects and keep the best classifier. * After that we have for each training project the best classifier as per the evaluation on the rest of the data set. * Then we determine the best classifier from these candidates and keep it to be used later. */ public class GPVClassifier extends AbstractClassifier { private List<Classifier> classifiers = null; private Classifier best = null; private static final long serialVersionUID = 3708714057579101522L; protected int populationSize; protected int initMinDepth; protected int initMaxDepth; protected int tournamentSize; protected int maxGenerations; protected double errorType2Weight; protected int numberRuns; protected int maxDepth; protected int maxNodes; /** * Configure the GP Params and number of Runs * * @param populationSize * @param initMinDepth * @param initMaxDepth * @param tournamentSize * @param maxGenerations * @param errorType2Weight */ public void configure(int populationSize, int initMinDepth, int initMaxDepth, int tournamentSize, int maxGenerations, double errorType2Weight, int numberRuns, int maxDepth, int maxNodes) { this.populationSize = populationSize; this.initMinDepth = initMinDepth; this.initMaxDepth = initMaxDepth; this.tournamentSize = tournamentSize; this.maxGenerations = maxGenerations; this.errorType2Weight = errorType2Weight; this.numberRuns = numberRuns; this.maxDepth = maxDepth; this.maxNodes = maxNodes; } /** Build the GP Multiple Data Sets Validation Classifier * * This is according to Section 6 of the Paper by Liu et al. except for the selection of the best model. * Section 4 describes a slightly different approach. * * @param traindataSet * @throws Exception */ public void buildClassifier(SetUniqueList<Instances> traindataSet) throws Exception { // each classifier is trained with one project from the set // then is evaluated on the rest for(int i=0; i < traindataSet.size(); i++) { // candidates we get out of evaluation LinkedList<Classifier> candidates = new LinkedList<>(); // numberRuns full GPRuns, we generate numberRuns models for each traindata for(int k=0; k < this.numberRuns; k++) { Classifier classifier = new GPRun(); ((GPRun)classifier).configure(this.populationSize, this.initMinDepth, this.initMaxDepth, this.tournamentSize, this.maxGenerations, this.errorType2Weight, this.maxDepth, this.maxNodes); classifier.buildClassifier(traindataSet.get(i)); double[] errors; // rest of the set is evaluation data, we evaluate now for(int j=0; j < traindataSet.size(); j++) { if(j != i) { // if type1 and type2 errors are < 0.5 we allow the model in the candidate list errors = this.evaluate((GPRun)classifier, traindataSet.get(j)); if((errors[0] < 0.5) && (errors[1] < 0.5)) { candidates.add(classifier); } } } } // after the numberRuns we have < numberRuns candidate models for this trainData // we now evaluate the candidates // finding the best model is not really described in the paper we go with least errors double smallest_error_count = Double.MAX_VALUE; double[] errors; Classifier best = null; for(int ii=0; ii < candidates.size(); ii++) { for(int j=0; j < traindataSet.size(); j++) { if(j != i) { errors = this.evaluate((GPRun)candidates.get(ii), traindataSet.get(j)); if(errors[0]+errors[1] < smallest_error_count) { best = candidates.get(ii); } } } } // now we have the best classifier for this training data classifiers.add(best); } /* endfor trainData */ // now we have one best classifier for each trainData // we evaluate again to find the best classifier of all time // this selection is now according to section 4 of the paper and not 6 where an average of the 6 models is build double smallest_error_count = Double.MAX_VALUE; double error_count; double errors[]; for(int j=0; j < classifiers.size(); j++) { error_count = 0; Classifier current = classifiers.get(j); for(int i=0; i < traindataSet.size(); i++) { errors = this.evaluate((GPRun)current, traindataSet.get(i)); error_count = errors[0] + errors[1]; } if(error_count < smallest_error_count) { best = current; } } } @Override public void buildClassifier(Instances traindata) throws Exception { final Classifier classifier = new GPRun(); ((GPRun)classifier).configure(populationSize, initMinDepth, initMaxDepth, tournamentSize, maxGenerations, errorType2Weight, this.maxDepth, this.maxNodes); classifier.buildClassifier(traindata); classifiers.add(classifier); } /** * Evaluation of the Classifier * * We evaluate the classifier with the Instances of the evalData. * It basically assigns the instance attribute values to the variables of the s-expression-tree and * then counts the missclassifications. * * @param classifier * @param evalData * @return */ public double[] evaluate(GPRun classifier, Instances evalData) { GPGenotype gp = classifier.getGp(); Variable[] vars = classifier.getVariables(); IGPProgram fitest = gp.getAllTimeBest(); // selects the fitest of all not just the last generation double classification; int error_type1 = 0; int error_type2 = 0; int positive = 0; int negative = 0; for(Instance instance: evalData) { // assign instance attribute values to the variables of the s-expression-tree double[] tmp = WekaUtils.instanceValues(instance); for(int i = 0; i < tmp.length; i++) { vars[i].set(tmp[i]); } classification = fitest.execute_double(0, vars); // we need to count the absolutes of positives for percentage if(instance.classValue() == 1.0) { positive +=1; }else { negative +=1; } // classification < 0.5 we say defective if(classification < 0.5) { if(instance.classValue() != 1.0) { error_type1 += 1; } }else { if(instance.classValue() == 1.0) { error_type2 += 1; } } } // return error types percentages for the types double et1_per = error_type1 / negative; double et2_per = error_type2 / positive; return new double[]{et1_per, et2_per}; } /** * Use only the best classifier from our evaluation phase */ @Override public double classifyInstance(Instance instance) { GPGenotype gp = ((GPRun)best).getGp(); Variable[] vars = ((GPRun)best).getVariables(); IGPProgram fitest = gp.getAllTimeBest(); // all time fitest for(int i = 0; i < instance.numAttributes()-1; i++) { vars[i].set(instance.value(i)); } double classification = fitest.execute_double(0, vars); if(classification < 0.5) { return 1.0; }else { return 0.0; } } } }
CrossPare/src/de/ugoe/cs/cpdp/training/GPTraining.java
package de.ugoe.cs.cpdp.training; import java.util.LinkedList; import java.util.List; import org.apache.commons.collections4.list.SetUniqueList; import weka.classifiers.AbstractClassifier; import weka.classifiers.Classifier; import weka.core.Instance; import weka.core.Instances; import org.apache.commons.lang3.ArrayUtils; import org.jgap.Configuration; import org.jgap.InvalidConfigurationException; import org.jgap.gp.CommandGene; import org.jgap.gp.GPProblem; import org.jgap.gp.function.Add; import org.jgap.gp.function.Multiply; import org.jgap.gp.function.Log; import org.jgap.gp.function.Subtract; import org.jgap.gp.function.Divide; import org.jgap.gp.function.Sine; import org.jgap.gp.function.Cosine; import org.jgap.gp.function.Max; import org.jgap.gp.function.Exp; import org.jgap.gp.impl.DeltaGPFitnessEvaluator; import org.jgap.gp.impl.GPConfiguration; import org.jgap.gp.impl.GPGenotype; import org.jgap.gp.impl.TournamentSelector; import org.jgap.gp.terminal.Terminal; import org.jgap.gp.GPFitnessFunction; import org.jgap.gp.IGPProgram; import org.jgap.gp.terminal.Variable; import org.jgap.gp.MathCommand; import org.jgap.util.ICloneable; import de.ugoe.cs.cpdp.util.WekaUtils; import org.jgap.gp.impl.ProgramChromosome; import org.jgap.util.CloneException; /** * Genetic Programming Trainer * * Implementation (mostly) according to Liu et al. Evolutionary Optimization of Software Quality Modeling with Multiple Repositories. * * - GPRun is a Run of a complete Genetic Programm Evolution, we want several complete runs. * - GPVClassifier is the Validation Classifier * - GPVVClassifier is the Validation-Voting Classifier * * config: <setwisetrainer name="GPTraining" param="populationSize:1000,numberRuns:10" /> */ public class GPTraining implements ISetWiseTrainingStrategy, IWekaCompatibleTrainer { private GPVVClassifier classifier = null; // default values from the paper private int populationSize = 1000; private int initMinDepth = 2; private int initMaxDepth = 6; private int tournamentSize = 7; private int maxGenerations = 50; private double errorType2Weight = 15; private int numberRuns = 20; // im paper 20 per errorType2Weight then additional 20 private int maxDepth = 20; // max depth within one program private int maxNodes = 100; // max nodes within one program @Override public void setParameter(String parameters) { String[] params = parameters.split(","); String[] keyvalue = new String[2]; for(int i=0; i < params.length; i++) { keyvalue = params[i].split(":"); switch(keyvalue[0]) { case "populationSize": this.populationSize = Integer.parseInt(keyvalue[1]); break; case "initMinDepth": this.initMinDepth = Integer.parseInt(keyvalue[1]); break; case "tournamentSize": this.tournamentSize = Integer.parseInt(keyvalue[1]); break; case "maxGenerations": this.maxGenerations = Integer.parseInt(keyvalue[1]); break; case "errorType2Weight": this.errorType2Weight = Double.parseDouble(keyvalue[1]); break; case "numberRuns": this.numberRuns = Integer.parseInt(keyvalue[1]); break; case "maxDepth": this.maxDepth = Integer.parseInt(keyvalue[1]); break; case "maxNodes": this.maxNodes = Integer.parseInt(keyvalue[1]); break; } } this.classifier = new GPVVClassifier(); ((GPVClassifier)this.classifier).configure(populationSize, initMinDepth, initMaxDepth, tournamentSize, maxGenerations, errorType2Weight, numberRuns, maxDepth, maxNodes); } @Override public void apply(SetUniqueList<Instances> traindataSet) { try { classifier.buildClassifier(traindataSet); }catch(Exception e) { throw new RuntimeException(e); } } @Override public String getName() { return "GPTraining"; } @Override public Classifier getClassifier() { return this.classifier; } public class InstanceData { private double[][] instances_x; private boolean[] instances_y; public InstanceData(Instances instances) { this.instances_x = new double[instances.numInstances()][instances.numAttributes()-1]; this.instances_y = new boolean[instances.numInstances()]; Instance current; for(int i=0; i < this.instances_x.length; i++) { current = instances.get(i); this.instances_x[i] = WekaUtils.instanceValues(current); this.instances_y[i] = 1.0 == current.classValue(); } } public double[][] getX() { return instances_x; } public boolean[] getY() { return instances_y; } } /** * One Run executed by a GP Classifier */ public class GPRun extends AbstractClassifier { private static final long serialVersionUID = -4250422550107888789L; private int populationSize; private int initMinDepth; private int initMaxDepth; private int tournamentSize; private int maxGenerations; private double errorType2Weight; private int maxDepth; private int maxNodes; private GPGenotype gp; private GPProblem problem; public void configure(int populationSize, int initMinDepth, int initMaxDepth, int tournamentSize, int maxGenerations, double errorType2Weight, int maxDepth, int maxNodes) { this.populationSize = populationSize; this.initMinDepth = initMinDepth; this.initMaxDepth = initMaxDepth; this.tournamentSize = tournamentSize; this.maxGenerations = maxGenerations; this.errorType2Weight = errorType2Weight; this.maxDepth = maxDepth; this.maxNodes = maxNodes; } public GPGenotype getGp() { return this.gp; } public Variable[] getVariables() { return ((CrossPareGP)this.problem).getVariables(); } @Override public void buildClassifier(Instances traindata) throws Exception { InstanceData train = new InstanceData(traindata); this.problem = new CrossPareGP(train.getX(), train.getY(), this.populationSize, this.initMinDepth, this.initMaxDepth, this.tournamentSize, this.errorType2Weight, this.maxDepth, this.maxNodes); this.gp = problem.create(); this.gp.evolve(this.maxGenerations); } /** * GPProblem implementation */ class CrossPareGP extends GPProblem { private double[][] instances; private boolean[] output; private int maxDepth; private int maxNodes; private Variable[] x; public CrossPareGP(double[][] instances, boolean[] output, int populationSize, int minInitDept, int maxInitDepth, int tournamentSize, double errorType2Weight, int maxDepth, int maxNodes) throws InvalidConfigurationException { super(new GPConfiguration()); this.instances = instances; this.output = output; this.maxDepth = maxDepth; this.maxNodes = maxNodes; Configuration.reset(); GPConfiguration config = this.getGPConfiguration(); this.x = new Variable[this.instances[0].length]; for(int j=0; j < this.x.length; j++) { this.x[j] = Variable.create(config, "X"+j, CommandGene.DoubleClass); } config.setGPFitnessEvaluator(new DeltaGPFitnessEvaluator()); // smaller fitness is better //config.setGPFitnessEvaluator(new DefaultGPFitnessEvaluator()); // bigger fitness is better config.setMinInitDepth(minInitDept); config.setMaxInitDepth(maxInitDepth); config.setCrossoverProb((float)0.60); config.setReproductionProb((float)0.10); config.setMutationProb((float)0.30); config.setSelectionMethod(new TournamentSelector(tournamentSize)); config.setPopulationSize(populationSize); config.setMaxCrossoverDepth(4); config.setFitnessFunction(new CrossPareFitness(this.x, this.instances, this.output, errorType2Weight)); config.setStrictProgramCreation(true); } // used for running the fitness function again for testing public Variable[] getVariables() { return this.x; } public GPGenotype create() throws InvalidConfigurationException { GPConfiguration config = this.getGPConfiguration(); // return type Class[] types = {CommandGene.DoubleClass}; // Arguments of result-producing chromosome: none Class[][] argTypes = { {} }; // variables + functions, we set the variables with the values of the instances here CommandGene[] vars = new CommandGene[this.instances[0].length]; for(int j=0; j < this.instances[0].length; j++) { vars[j] = this.x[j]; } CommandGene[] funcs = { new Add(config, CommandGene.DoubleClass), new Subtract(config, CommandGene.DoubleClass), new Multiply(config, CommandGene.DoubleClass), new Divide(config, CommandGene.DoubleClass), new Sine(config, CommandGene.DoubleClass), new Cosine(config, CommandGene.DoubleClass), new Exp(config, CommandGene.DoubleClass), new Log(config, CommandGene.DoubleClass), new GT(config, CommandGene.DoubleClass), new Max(config, CommandGene.DoubleClass), new Terminal(config, CommandGene.DoubleClass, -100.0, 100.0, true), // min, max, whole numbers }; CommandGene[] comb = (CommandGene[])ArrayUtils.addAll(vars, funcs); CommandGene[][] nodeSets = { comb, }; // we only have one chromosome so this suffices int minDepths[] = {config.getMinInitDepth()}; int maxDepths[] = {this.maxDepth}; GPGenotype result = GPGenotype.randomInitialGenotype(config, types, argTypes, nodeSets, minDepths, maxDepths, this.maxNodes, false); // 40 = maxNodes, true = verbose output return result; } } /** * Fitness function */ class CrossPareFitness extends GPFitnessFunction { private static final long serialVersionUID = 75234832484387L; private Variable[] x; private double[][] instances; private boolean[] output; private double errorType2Weight = 1.0; // needed in evaluate //private Object[] NO_ARGS = new Object[0]; private double sfitness = 0.0f; private int errorType1 = 0; private int errorType2 = 0; public CrossPareFitness(Variable[] x, double[][] instances, boolean[] output, double errorType2Weight) { this.x = x; this.instances = instances; this.output = output; this.errorType2Weight = errorType2Weight; } public int getErrorType1() { return this.errorType1; } public int getErrorType2() { return this.errorType2; } public double getSecondFitness() { return this.sfitness; } public int getNumInstances() { return this.instances.length; } /** * This is the fitness function * * Our fitness is best if we have the less wrong classifications, this includes a weight for type2 errors */ @Override protected double evaluate(final IGPProgram program) { double pfitness = 0.0f; this.sfitness = 0.0f; double value = 0.0f; // count classification errors this.errorType1 = 0; this.errorType2 = 0; for(int i=0; i < this.instances.length; i++) { // requires that we have a variable for each column of our dataset (attribute of instance) for(int j=0; j < this.x.length; j++) { this.x[j].set(this.instances[i][j]); } // value gives us a double, if < 0.5 we set this instance as faulty value = program.execute_double(0, this.x); if(value < 0.5) { if(this.output[i] != true) { this.errorType1 += 1; } }else { if(this.output[i] == true) { this.errorType2 += 1; } } } // now calc pfitness pfitness = (this.errorType1 + this.errorType2Weight * this.errorType2) / this.instances.length; // number of nodes in the programm, if lower then 10 we assign sFitness of 10 // we can set metadata with setProgramData to save this if(program.getChromosome(0).getSize(0) < 10) { program.setApplicationData(10.0f); } return pfitness; } } /** * Custom GT implementation used in the GP Algorithm. */ public class GT extends MathCommand implements ICloneable { private static final long serialVersionUID = 113454184817L; public GT(final GPConfiguration a_conf, java.lang.Class a_returnType) throws InvalidConfigurationException { super(a_conf, 2, a_returnType); } public String toString() { return "GT(&1, &2)"; } public String getName() { return "GT"; } public float execute_float(ProgramChromosome c, int n, Object[] args) { float f1 = c.execute_float(n, 0, args); float f2 = c.execute_float(n, 1, args); float ret = 1.0f; if(f1 > f2) { ret = 0.0f; } return ret; } public double execute_double(ProgramChromosome c, int n, Object[] args) { double f1 = c.execute_double(n, 0, args); double f2 = c.execute_double(n, 1, args); double ret = 1; if(f1 > f2) { ret = 0; } return ret; } public Object clone() { try { GT result = new GT(getGPConfiguration(), getReturnType()); return result; }catch(Exception ex) { throw new CloneException(ex); } } } } /** * GP Multiple Data Sets Validation-Voting Classifier * * Basically the same as the GP Multiple Data Sets Validation Classifier. * But here we do keep a model candidate for each training set which may later vote * */ public class GPVVClassifier extends GPVClassifier { private static final long serialVersionUID = -654710583852839901L; private List<Classifier> classifiers = null; @Override public void buildClassifier(Instances arg0) throws Exception { // TODO Auto-generated method stub } /** Build the GP Multiple Data Sets Validation-Voting Classifier * * This is according to Section 6 of the Paper by Liu et al. * It is basically the Multiple Data Sets Validation Classifier but here we keep the best models an let them vote. * * @param traindataSet * @throws Exception */ public void buildClassifier(SetUniqueList<Instances> traindataSet) throws Exception { // each classifier is trained with one project from the set // then is evaluated on the rest classifiers = new LinkedList<>(); for(int i=0; i < traindataSet.size(); i++) { // candidates we get out of evaluation LinkedList<Classifier> candidates = new LinkedList<>(); // number of runs for(int k=0; k < this.numberRuns; k++) { Classifier classifier = new GPRun(); ((GPRun)classifier).configure(this.populationSize, this.initMinDepth, this.initMaxDepth, this.tournamentSize, this.maxGenerations, this.errorType2Weight, this.maxDepth, this.maxNodes); // one project is training data classifier.buildClassifier(traindataSet.get(i)); double[] errors; // rest of the set is evaluation data, we evaluate now for(int j=0; j < traindataSet.size(); j++) { if(j != i) { // if type1 and type2 errors are < 0.5 we allow the model in the candidates errors = this.evaluate((GPRun)classifier, traindataSet.get(j)); if((errors[0] < 0.5) && (errors[0] < 0.5)) { candidates.add(classifier); } } } } // now after the evaluation we do a model selection where only one model remains for the given training data double smallest_error_count = Double.MAX_VALUE; double[] errors; Classifier best = null; for(int ii=0; ii < candidates.size(); ii++) { for(int j=0; j < traindataSet.size(); j++) { if(j != i) { errors = this.evaluate((GPRun)candidates.get(ii), traindataSet.get(j)); if(errors[0]+errors[1] < smallest_error_count) { best = candidates.get(ii); } } } } // now we have the best classifier for this training data classifiers.add(best); } } /** * Use the best classifiers for each training data in a majority voting */ @Override public double classifyInstance(Instance instance) { int vote_positive = 0; for (int i = 0; i < classifiers.size(); i++) { Classifier classifier = classifiers.get(i); GPGenotype gp = ((GPRun)classifier).getGp(); Variable[] vars = ((GPRun)classifier).getVariables(); IGPProgram fitest = gp.getAllTimeBest(); // all time fitest for(int j = 0; j < instance.numAttributes()-1; j++) { vars[j].set(instance.value(j)); } if(fitest.execute_double(0, vars) < 0.5) { vote_positive += 1; } } if(vote_positive >= (classifiers.size()/2)) { return 1.0; }else { return 0.0; } } } /** * GP Multiple Data Sets Validation Classifier * * We train a Classifier with one training project $numberRun times. * Then we evaluate the classifier on the rest of the training projects and keep the best classifier. * After that we have for each training project the best classifier as per the evaluation on the rest of the data set. * Then we determine the best classifier from these candidates and keep it to be used later. */ public class GPVClassifier extends AbstractClassifier { private List<Classifier> classifiers = null; private Classifier best = null; private static final long serialVersionUID = 3708714057579101522L; protected int populationSize; protected int initMinDepth; protected int initMaxDepth; protected int tournamentSize; protected int maxGenerations; protected double errorType2Weight; protected int numberRuns; protected int maxDepth; protected int maxNodes; /** * Configure the GP Params and number of Runs * * @param populationSize * @param initMinDepth * @param initMaxDepth * @param tournamentSize * @param maxGenerations * @param errorType2Weight */ public void configure(int populationSize, int initMinDepth, int initMaxDepth, int tournamentSize, int maxGenerations, double errorType2Weight, int numberRuns, int maxDepth, int maxNodes) { this.populationSize = populationSize; this.initMinDepth = initMinDepth; this.initMaxDepth = initMaxDepth; this.tournamentSize = tournamentSize; this.maxGenerations = maxGenerations; this.errorType2Weight = errorType2Weight; this.numberRuns = numberRuns; this.maxDepth = maxDepth; this.maxNodes = maxNodes; } /** Build the GP Multiple Data Sets Validation Classifier * * This is according to Section 6 of the Paper by Liu et al. except for the selection of the best model. * Section 4 describes a slightly different approach. * * @param traindataSet * @throws Exception */ public void buildClassifier(SetUniqueList<Instances> traindataSet) throws Exception { // each classifier is trained with one project from the set // then is evaluated on the rest for(int i=0; i < traindataSet.size(); i++) { // candidates we get out of evaluation LinkedList<Classifier> candidates = new LinkedList<>(); // numberRuns full GPRuns, we generate numberRuns models for each traindata for(int k=0; k < this.numberRuns; k++) { Classifier classifier = new GPRun(); ((GPRun)classifier).configure(this.populationSize, this.initMinDepth, this.initMaxDepth, this.tournamentSize, this.maxGenerations, this.errorType2Weight, this.maxDepth, this.maxNodes); classifier.buildClassifier(traindataSet.get(i)); double[] errors; // rest of the set is evaluation data, we evaluate now for(int j=0; j < traindataSet.size(); j++) { if(j != i) { // if type1 and type2 errors are < 0.5 we allow the model in the candidate list errors = this.evaluate((GPRun)classifier, traindataSet.get(j)); if((errors[0] < 0.5) && (errors[0] < 0.5)) { candidates.add(classifier); } } } } // after the numberRuns we have < numberRuns candidate models for this trainData // we now evaluate the candidates // finding the best model is not really described in the paper we go with least errors double smallest_error_count = Double.MAX_VALUE; double[] errors; Classifier best = null; for(int ii=0; ii < candidates.size(); ii++) { for(int j=0; j < traindataSet.size(); j++) { if(j != i) { errors = this.evaluate((GPRun)candidates.get(ii), traindataSet.get(j)); if(errors[0]+errors[1] < smallest_error_count) { best = candidates.get(ii); } } } } // now we have the best classifier for this training data classifiers.add(best); } /* endfor trainData */ // now we have one best classifier for each trainData // we evaluate again to find the best classifier of all time // this selection is now according to section 4 of the paper and not 6 where an average of the 6 models is build double smallest_error_count = Double.MAX_VALUE; double error_count; double errors[]; for(int j=0; j < classifiers.size(); j++) { error_count = 0; Classifier current = classifiers.get(j); for(int i=0; i < traindataSet.size(); i++) { errors = this.evaluate((GPRun)current, traindataSet.get(i)); error_count = errors[0] + errors[1]; } if(error_count < smallest_error_count) { best = current; } } } @Override public void buildClassifier(Instances traindata) throws Exception { final Classifier classifier = new GPRun(); ((GPRun)classifier).configure(populationSize, initMinDepth, initMaxDepth, tournamentSize, maxGenerations, errorType2Weight, this.maxDepth, this.maxNodes); classifier.buildClassifier(traindata); classifiers.add(classifier); } /** * Evaluation of the Classifier * * We evaluate the classifier with the Instances of the evalData. * It basically assigns the instance attribute values to the variables of the s-expression-tree and * then counts the missclassifications. * * @param classifier * @param evalData * @return */ public double[] evaluate(GPRun classifier, Instances evalData) { GPGenotype gp = classifier.getGp(); Variable[] vars = classifier.getVariables(); IGPProgram fitest = gp.getAllTimeBest(); // selects the fitest of all not just the last generation double classification; int error_type1 = 0; int error_type2 = 0; int positive = 0; int negative = 0; for(Instance instance: evalData) { // assign instance attribute values to the variables of the s-expression-tree double[] tmp = WekaUtils.instanceValues(instance); for(int i = 0; i < tmp.length; i++) { vars[i].set(tmp[i]); } classification = fitest.execute_double(0, vars); // we need to count the absolutes of positives for percentage if(instance.classValue() == 1.0) { positive +=1; }else { negative +=1; } // classification < 0.5 we say defective if(classification < 0.5) { if(instance.classValue() != 1.0) { error_type1 += 1; } }else { if(instance.classValue() == 1.0) { error_type2 += 1; } } } // return error types percentages for the types double et1_per = error_type1 / negative; double et2_per = error_type2 / positive; return new double[]{et1_per, et2_per}; } /** * Use only the best classifier from our evaluation phase */ @Override public double classifyInstance(Instance instance) { GPGenotype gp = ((GPRun)best).getGp(); Variable[] vars = ((GPRun)best).getVariables(); IGPProgram fitest = gp.getAllTimeBest(); // all time fitest for(int i = 0; i < instance.numAttributes()-1; i++) { vars[i].set(instance.value(i)); } double classification = fitest.execute_double(0, vars); if(classification < 0.5) { return 1.0; }else { return 0.0; } } } }
evalfix
CrossPare/src/de/ugoe/cs/cpdp/training/GPTraining.java
evalfix
<ide><path>rossPare/src/de/ugoe/cs/cpdp/training/GPTraining.java <ide> // then is evaluated on the rest <ide> classifiers = new LinkedList<>(); <ide> for(int i=0; i < traindataSet.size(); i++) { <del> <add> <ide> // candidates we get out of evaluation <ide> LinkedList<Classifier> candidates = new LinkedList<>(); <ide> <del> // number of runs <add> // number of runs, yields the best of these <ide> for(int k=0; k < this.numberRuns; k++) { <ide> Classifier classifier = new GPRun(); <ide> ((GPRun)classifier).configure(this.populationSize, this.initMinDepth, this.initMaxDepth, this.tournamentSize, this.maxGenerations, this.errorType2Weight, this.maxDepth, this.maxNodes); <ide> if(j != i) { <ide> // if type1 and type2 errors are < 0.5 we allow the model in the candidates <ide> errors = this.evaluate((GPRun)classifier, traindataSet.get(j)); <del> if((errors[0] < 0.5) && (errors[0] < 0.5)) { <add> if((errors[0] < 0.5) && (errors[1] < 0.5)) { <ide> candidates.add(classifier); <ide> } <ide> } <ide> } <ide> } <ide> <add> <ide> // now after the evaluation we do a model selection where only one model remains for the given training data <add> // we select the model which is best on all evaluation data <ide> double smallest_error_count = Double.MAX_VALUE; <ide> double[] errors; <ide> Classifier best = null; <ide> for(int ii=0; ii < candidates.size(); ii++) { <add> double[] errors_eval = {0.0, 0.0}; <add> <add> // we add the errors the candidate makes over the evaldata <ide> for(int j=0; j < traindataSet.size(); j++) { <ide> if(j != i) { <ide> errors = this.evaluate((GPRun)candidates.get(ii), traindataSet.get(j)); <del> <del> if(errors[0]+errors[1] < smallest_error_count) { <del> best = candidates.get(ii); <del> } <add> errors_eval[0] += errors[0]; <add> errors_eval[1] += errors[1]; <ide> } <ide> } <del> } <add> <add> // if the candidate made fewer errors it is now the best <add> if(errors_eval[0] + errors_eval[1] < smallest_error_count) { <add> best = candidates.get(ii); <add> smallest_error_count = errors_eval[0] + errors_eval[1]; <add> } <add> } <add> <ide> <ide> // now we have the best classifier for this training data <ide> classifiers.add(best); <add> <add> <ide> } <ide> } <ide> <ide> if(j != i) { <ide> // if type1 and type2 errors are < 0.5 we allow the model in the candidate list <ide> errors = this.evaluate((GPRun)classifier, traindataSet.get(j)); <del> if((errors[0] < 0.5) && (errors[0] < 0.5)) { <add> if((errors[0] < 0.5) && (errors[1] < 0.5)) { <ide> candidates.add(classifier); <ide> } <ide> }
Java
apache-2.0
75eadb73c4e07733205c531d5ab1bbd1c1691493
0
opendatakit/androidcommon
/* * Copyright (C) 2015 University of Washington * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.opendatakit.common.android.application; import android.annotation.SuppressLint; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.os.AsyncTask; import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.util.Log; import android.view.View; import android.webkit.WebView; import org.opendatakit.common.android.listener.DatabaseConnectionListener; import org.opendatakit.common.android.listener.InitializationListener; import org.opendatakit.common.android.logic.CommonToolProperties; import org.opendatakit.common.android.logic.PropertiesSingleton; import org.opendatakit.common.android.task.InitializationTask; import org.opendatakit.common.android.utilities.ODKFileUtils; import org.opendatakit.common.android.views.ODKWebView; import org.opendatakit.database.DatabaseConsts; import org.opendatakit.database.service.OdkDbInterface; import org.opendatakit.webkitserver.WebkitServerConsts; import org.opendatakit.webkitserver.service.OdkWebkitServerInterface; import java.util.ArrayList; public abstract class CommonApplication extends AppAwareApplication implements InitializationListener { private static final String t = "CommonApplication"; public static final String PERMISSION_WEBSERVER = "org.opendatakit.webkitserver.RUN_WEBSERVER"; public static final String PERMISSION_DATABASE = "org.opendatakit.database.RUN_DATABASE"; // Support for mocking the remote interfaces that are actually accessed // vs. the WebKit service, which is merely started. private static boolean isMocked = false; // Hack to determine whether or not to cascade to the initialize task private static boolean disableInitializeCascade = true; // Hack for handling mock interfaces... private static OdkDbInterface mockDatabaseService = null; private static OdkWebkitServerInterface mockWebkitServerService = null; public static void setMocked() { isMocked = true; } public static boolean isMocked() { return isMocked; } public static boolean isDisableInitializeCascade() { return disableInitializeCascade; } public static void setEnableInitializeCascade() { disableInitializeCascade = false; } public static void setDisableInitializeCascade() { disableInitializeCascade = true; } public static void setMockDatabase(OdkDbInterface mock) { CommonApplication.mockDatabaseService = mock; } public static void setMockWebkitServer(OdkWebkitServerInterface mock) { CommonApplication.mockWebkitServerService = mock; } public static void mockServiceConnected(CommonApplication app, String name) { ComponentName className = null; if (name.equals(WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS)) { className = new ComponentName(WebkitServerConsts.WEBKITSERVER_SERVICE_PACKAGE, WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS); } if (name.equals(DatabaseConsts.DATABASE_SERVICE_CLASS)) { className = new ComponentName(DatabaseConsts.DATABASE_SERVICE_PACKAGE, DatabaseConsts.DATABASE_SERVICE_CLASS); } if ( className == null ) { throw new IllegalStateException("unrecognized mockService"); } app.doServiceConnected(className, null); } public static void mockServiceDisconnected(CommonApplication app, String name) { ComponentName className = null; if (name.equals(WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS)) { className = new ComponentName(WebkitServerConsts.WEBKITSERVER_SERVICE_PACKAGE, WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS); } if (name.equals(DatabaseConsts.DATABASE_SERVICE_CLASS)) { className = new ComponentName(DatabaseConsts.DATABASE_SERVICE_PACKAGE, DatabaseConsts.DATABASE_SERVICE_CLASS); } if ( className == null ) { throw new IllegalStateException("unrecognized mockService"); } app.doServiceDisconnected(className); } /** * Wrapper class for service activation management. * * @author [email protected] * */ private final class ServiceConnectionWrapper implements ServiceConnection { @Override public void onServiceConnected(ComponentName name, IBinder service) { CommonApplication.this.doServiceConnected(name, service); } @Override public void onServiceDisconnected(ComponentName name) { CommonApplication.this.doServiceDisconnected(name); } } /** * Task instances that are preserved until the application dies. * * @author [email protected] * */ private static final class BackgroundTasks { InitializationTask mInitializationTask = null; BackgroundTasks() { }; } /** * Service connections that are preserved until the application dies. * * @author [email protected] * */ private static final class BackgroundServices { private ServiceConnectionWrapper webkitfilesServiceConnection = null; private OdkWebkitServerInterface webkitfilesService = null; private ServiceConnectionWrapper databaseServiceConnection = null; private OdkDbInterface databaseService = null; private boolean isDestroying = false; BackgroundServices() { }; } /** * Creates required directories on the SDCard (or other external storage) * * @return true if there are tables present * @throws RuntimeException * if there is no SDCard or the directory exists as a non directory */ public static void createODKDirs(String appName) throws RuntimeException { ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); } // handed across orientation changes private final BackgroundTasks mBackgroundTasks = new BackgroundTasks(); // handed across orientation changes private final BackgroundServices mBackgroundServices = new BackgroundServices(); // These are expected to be broken down and set up during orientation changes. private InitializationListener mInitializationListener = null; private boolean shuttingDown = false; public CommonApplication() { super(); } @SuppressLint("NewApi") @Override public void onCreate() { shuttingDown = false; super.onCreate(); if (Build.VERSION.SDK_INT >= 19) { WebView.setWebContentsDebuggingEnabled(true); } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); Log.i(t, "onConfigurationChanged"); } @Override public void onTerminate() { cleanShutdown(); super.onTerminate(); Log.i(t, "onTerminate"); } public abstract int getConfigZipResourceId(); public abstract int getSystemZipResourceId(); public abstract int getWebKitResourceId(); public boolean shouldRunInitializationTask(String appName) { if ( isMocked() ) { if ( isDisableInitializeCascade() ) { return false; } } PropertiesSingleton props = CommonToolProperties.get(this, appName); return props.shouldRunInitializationTask(this.getToolName()); } public void clearRunInitializationTask(String appName) { PropertiesSingleton props = CommonToolProperties.get(this, appName); props.clearRunInitializationTask(this.getToolName()); } public void setRunInitializationTask(String appName) { PropertiesSingleton props = CommonToolProperties.get(this, appName); props.setRunInitializationTask(this.getToolName()); } private <T> void executeTask(AsyncTask<T, ?, ?> task, T... args) { int androidVersion = android.os.Build.VERSION.SDK_INT; if (androidVersion < 11) { task.execute(args); } else { // TODO: execute on serial executor in version 11 onward... task.execute(args); // task.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, (Void[]) null); } } private Activity activeActivity = null; private Activity databaseListenerActivity = null; public void onActivityPause(Activity activity) { if ( activeActivity == activity ) { mInitializationListener = null; if (mBackgroundTasks.mInitializationTask != null) { mBackgroundTasks.mInitializationTask.setInitializationListener(null); } } } public void onActivityDestroy(Activity activity) { if ( activeActivity == activity ) { activeActivity = null; mInitializationListener = null; if (mBackgroundTasks.mInitializationTask != null) { mBackgroundTasks.mInitializationTask.setInitializationListener(null); } final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { CommonApplication.this.testForShutdown(); } }, 500); } } private void cleanShutdown() { try { shuttingDown = true; shutdownServices(); } finally { shuttingDown = false; } } private void testForShutdown() { // no other activity has been started -- shut down if ( activeActivity == null ) { cleanShutdown(); } } public void onActivityResume(Activity activity) { databaseListenerActivity = null; activeActivity = activity; if (mBackgroundTasks.mInitializationTask != null) { mBackgroundTasks.mInitializationTask.setInitializationListener(this); } // be sure the services are connected... mBackgroundServices.isDestroying = false; configureView(); // failsafe -- ensure that the services are active... bindToService(); } // ///////////////////////////////////////////////////////////////////////// // service interactions private void unbindWebkitfilesServiceWrapper() { try { ServiceConnectionWrapper tmp = mBackgroundServices.webkitfilesServiceConnection; mBackgroundServices.webkitfilesServiceConnection = null; if ( tmp != null ) { unbindService(tmp); } } catch ( Exception e ) { // ignore e.printStackTrace(); } } private void unbindDatabaseBinderWrapper() { try { ServiceConnectionWrapper tmp = mBackgroundServices.databaseServiceConnection; mBackgroundServices.databaseServiceConnection = null; if ( tmp != null ) { unbindService(tmp); triggerDatabaseEvent(false); } } catch ( Exception e ) { // ignore e.printStackTrace(); } } private void shutdownServices() { Log.i(t, "shutdownServices - Releasing WebServer and database service"); mBackgroundServices.isDestroying = true; mBackgroundServices.webkitfilesService = null; mBackgroundServices.databaseService = null; // release interfaces held by the view configureView(); // release the webkitfilesService unbindWebkitfilesServiceWrapper(); unbindDatabaseBinderWrapper(); } private void bindToService() { if ( isMocked ) { // we directly control all the service binding interactions if we are mocked return; } if (!shuttingDown && !mBackgroundServices.isDestroying) { PackageManager pm = getPackageManager(); boolean useWebServer = (pm.checkPermission(PERMISSION_WEBSERVER, getPackageName()) == PackageManager.PERMISSION_GRANTED); boolean useDatabase = (pm.checkPermission(PERMISSION_DATABASE, getPackageName()) == PackageManager.PERMISSION_GRANTED); // do something if (useWebServer && mBackgroundServices.webkitfilesService == null && mBackgroundServices.webkitfilesServiceConnection == null) { Log.i(t, "Attempting bind to WebServer service"); mBackgroundServices.webkitfilesServiceConnection = new ServiceConnectionWrapper(); Intent bind_intent = new Intent(); bind_intent.setClassName(WebkitServerConsts.WEBKITSERVER_SERVICE_PACKAGE, WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS); bindService( bind_intent, mBackgroundServices.webkitfilesServiceConnection, Context.BIND_AUTO_CREATE | ((Build.VERSION.SDK_INT >= 14) ? Context.BIND_ADJUST_WITH_ACTIVITY : 0)); } if (useDatabase && mBackgroundServices.databaseService == null && mBackgroundServices.databaseServiceConnection == null) { Log.i(t, "Attempting bind to Database service"); mBackgroundServices.databaseServiceConnection = new ServiceConnectionWrapper(); Intent bind_intent = new Intent(); bind_intent.setClassName(DatabaseConsts.DATABASE_SERVICE_PACKAGE, DatabaseConsts.DATABASE_SERVICE_CLASS); bindService( bind_intent, mBackgroundServices.databaseServiceConnection, Context.BIND_AUTO_CREATE | ((Build.VERSION.SDK_INT >= 14) ? Context.BIND_ADJUST_WITH_ACTIVITY : 0)); } } } /** * * @param className * @param service can be null if we are mocked */ private void doServiceConnected(ComponentName className, IBinder service) { if (className.getClassName().equals(WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS)) { Log.i(t, "Bound to WebServer service"); mBackgroundServices.webkitfilesService = (service == null) ? null : OdkWebkitServerInterface.Stub.asInterface(service); } if (className.getClassName().equals(DatabaseConsts.DATABASE_SERVICE_CLASS)) { Log.i(t, "Bound to Database service"); mBackgroundServices.databaseService = (service == null) ? null : OdkDbInterface.Stub.asInterface(service); triggerDatabaseEvent(false); } configureView(); } public OdkDbInterface getDatabase() { if ( isMocked ) { return mockDatabaseService; } else { return mBackgroundServices.databaseService; } } private OdkWebkitServerInterface getWebkitServer() { if ( isMocked ) { return mockWebkitServerService; } else { return mBackgroundServices.webkitfilesService; } } public void configureView() { if ( activeActivity != null ) { Log.i(t, "configureView - possibly updating service information within ODKWebView"); if ( getWebKitResourceId() != -1 ) { View v = activeActivity.findViewById(getWebKitResourceId()); if (v != null && v instanceof ODKWebView) { ODKWebView wv = (ODKWebView) v; if (mBackgroundServices.isDestroying) { wv.serviceChange(false); } else { OdkWebkitServerInterface webkitServerIf = getWebkitServer(); OdkDbInterface dbIf = getDatabase(); wv.serviceChange(webkitServerIf != null && dbIf != null); } } } } } private void doServiceDisconnected(ComponentName className) { if (className.getClassName().equals(WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS)) { if (mBackgroundServices.isDestroying) { Log.i(t, "Unbound from WebServer service (intentionally)"); } else { Log.w(t, "Unbound from WebServer service (unexpected)"); } mBackgroundServices.webkitfilesService = null; unbindWebkitfilesServiceWrapper(); } if (className.getClassName().equals(DatabaseConsts.DATABASE_SERVICE_CLASS)) { if (mBackgroundServices.isDestroying) { Log.i(t, "Unbound from Database service (intentionally)"); } else { Log.w(t, "Unbound from Database service (unexpected)"); } mBackgroundServices.databaseService = null; unbindDatabaseBinderWrapper(); } configureView(); // the bindToService() method decides whether to connect or not... bindToService(); } // ///////////////////////////////////////////////////////////////////////// // registrations /** * Called by an activity when it has been sufficiently initialized so * that it can handle a databaseAvailable() call. * * @param activity */ public void establishDatabaseConnectionListener(Activity activity) { databaseListenerActivity = activity; triggerDatabaseEvent(true); } public void establishDoNotFireDatabaseConnectionListener(Activity activity) { databaseListenerActivity = activity; } public void fireDatabaseConnectionListener() { triggerDatabaseEvent(true); } /** * If the given activity is active, then fire the callback based upon * the availability of the database. * * @param activity * @param listener */ public void possiblyFireDatabaseCallback(Activity activity, DatabaseConnectionListener listener) { if ( activeActivity != null && activeActivity == databaseListenerActivity && databaseListenerActivity == activity ) { if ( this.getDatabase() == null ) { listener.databaseUnavailable(); } else { listener.databaseAvailable(); } } } private void triggerDatabaseEvent(boolean availableOnly) { if ( activeActivity != null && activeActivity == databaseListenerActivity && activeActivity instanceof DatabaseConnectionListener ) { if ( !availableOnly && this.getDatabase() == null ) { ((DatabaseConnectionListener) activeActivity).databaseUnavailable(); } else { ((DatabaseConnectionListener) activeActivity).databaseAvailable(); } } } public void establishInitializationListener(InitializationListener listener) { mInitializationListener = listener; // async task may have completed while we were reorienting... if (mBackgroundTasks.mInitializationTask != null && mBackgroundTasks.mInitializationTask.getStatus() == AsyncTask.Status.FINISHED) { this.initializationComplete(mBackgroundTasks.mInitializationTask.getOverallSuccess(), mBackgroundTasks.mInitializationTask.getResult()); } } // /////////////////////////////////////////////////// // actions public synchronized boolean initializeAppName(String appName, InitializationListener listener) { mInitializationListener = listener; if (mBackgroundTasks.mInitializationTask != null && mBackgroundTasks.mInitializationTask.getStatus() != AsyncTask.Status.FINISHED) { // Toast.makeText(this.getActivity(), // getString(R.string.expansion_in_progress), // Toast.LENGTH_LONG).show(); return true; } else if ( getDatabase() != null ) { InitializationTask cf = new InitializationTask(); cf.setApplication(this); cf.setAppName(appName); cf.setInitializationListener(this); mBackgroundTasks.mInitializationTask = cf; executeTask(mBackgroundTasks.mInitializationTask, (Void) null); return true; } else { return false; } } // ///////////////////////////////////////////////////////////////////////// // clearing tasks // // NOTE: clearing these makes us forget that they are running, but it is // up to the task itself to eventually shutdown. i.e., we don't quite // know when they actually stop. public synchronized void clearInitializationTask() { mInitializationListener = null; if (mBackgroundTasks.mInitializationTask != null) { mBackgroundTasks.mInitializationTask.setInitializationListener(null); if (mBackgroundTasks.mInitializationTask.getStatus() != AsyncTask.Status.FINISHED) { mBackgroundTasks.mInitializationTask.cancel(true); } } mBackgroundTasks.mInitializationTask = null; } // ///////////////////////////////////////////////////////////////////////// // cancel requests // // These maintain communications paths, so that we get a failure // completion callback eventually. public synchronized void cancelInitializationTask() { if (mBackgroundTasks.mInitializationTask != null) { if (mBackgroundTasks.mInitializationTask.getStatus() != AsyncTask.Status.FINISHED) { mBackgroundTasks.mInitializationTask.cancel(true); } } } // ///////////////////////////////////////////////////////////////////////// // callbacks @Override public void initializationComplete(boolean overallSuccess, ArrayList<String> result) { if (mInitializationListener != null) { mInitializationListener.initializationComplete(overallSuccess, result); } } @Override public void initializationProgressUpdate(String status) { if (mInitializationListener != null) { mInitializationListener.initializationProgressUpdate(status); } } }
androidcommon_lib/src/main/java/org/opendatakit/common/android/application/CommonApplication.java
/* * Copyright (C) 2015 University of Washington * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.opendatakit.common.android.application; import android.annotation.SuppressLint; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.os.AsyncTask; import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.util.Log; import android.view.View; import android.webkit.WebView; import org.opendatakit.common.android.listener.DatabaseConnectionListener; import org.opendatakit.common.android.listener.InitializationListener; import org.opendatakit.common.android.logic.CommonToolProperties; import org.opendatakit.common.android.logic.PropertiesSingleton; import org.opendatakit.common.android.task.InitializationTask; import org.opendatakit.common.android.utilities.ODKFileUtils; import org.opendatakit.common.android.views.ODKWebView; import org.opendatakit.database.DatabaseConsts; import org.opendatakit.database.service.OdkDbInterface; import org.opendatakit.webkitserver.WebkitServerConsts; import org.opendatakit.webkitserver.service.OdkWebkitServerInterface; import java.util.ArrayList; public abstract class CommonApplication extends AppAwareApplication implements InitializationListener { private static final String t = "CommonApplication"; public static final String PERMISSION_WEBSERVER = "org.opendatakit.webkitserver.RUN_WEBSERVER"; public static final String PERMISSION_DATABASE = "org.opendatakit.database.RUN_DATABASE"; // Support for mocking the remote interfaces that are actually accessed // vs. the WebKit service, which is merely started. private static boolean isMocked = false; // Hack to determine whether or not to cascade to the initialize task private static boolean disableInitializeCascade = true; // Hack for handling mock interfaces... private static OdkDbInterface mockDatabaseService = null; private static OdkWebkitServerInterface mockWebkitServerService = null; public static void setMocked() { isMocked = true; } public static boolean isMocked() { return isMocked; } public static boolean isDisableInitializeCascade() { return disableInitializeCascade; } public static void setEnableInitializeCascade() { disableInitializeCascade = false; } public static void setDisableInitializeCascade() { disableInitializeCascade = true; } public static void setMockDatabase(OdkDbInterface mock) { CommonApplication.mockDatabaseService = mock; } public static void setMockWebkitServer(OdkWebkitServerInterface mock) { CommonApplication.mockWebkitServerService = mock; } public static void mockServiceConnected(CommonApplication app, String name) { ComponentName className = null; if (name.equals(WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS)) { className = new ComponentName(WebkitServerConsts.WEBKITSERVER_SERVICE_PACKAGE, WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS); } if (name.equals(DatabaseConsts.DATABASE_SERVICE_CLASS)) { className = new ComponentName(DatabaseConsts.DATABASE_SERVICE_PACKAGE, DatabaseConsts.DATABASE_SERVICE_CLASS); } if ( className == null ) { throw new IllegalStateException("unrecognized mockService"); } app.doServiceConnected(className, null); } public static void mockServiceDisconnected(CommonApplication app, String name) { ComponentName className = null; if (name.equals(WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS)) { className = new ComponentName(WebkitServerConsts.WEBKITSERVER_SERVICE_PACKAGE, WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS); } if (name.equals(DatabaseConsts.DATABASE_SERVICE_CLASS)) { className = new ComponentName(DatabaseConsts.DATABASE_SERVICE_PACKAGE, DatabaseConsts.DATABASE_SERVICE_CLASS); } if ( className == null ) { throw new IllegalStateException("unrecognized mockService"); } app.doServiceDisconnected(className); } /** * Wrapper class for service activation management. * * @author [email protected] * */ private final class ServiceConnectionWrapper implements ServiceConnection { @Override public void onServiceConnected(ComponentName name, IBinder service) { CommonApplication.this.doServiceConnected(name, service); } @Override public void onServiceDisconnected(ComponentName name) { CommonApplication.this.doServiceDisconnected(name); } } /** * Task instances that are preserved until the application dies. * * @author [email protected] * */ private static final class BackgroundTasks { InitializationTask mInitializationTask = null; BackgroundTasks() { }; } /** * Service connections that are preserved until the application dies. * * @author [email protected] * */ private static final class BackgroundServices { private ServiceConnectionWrapper webkitfilesServiceConnection = null; private OdkWebkitServerInterface webkitfilesService = null; private ServiceConnectionWrapper databaseServiceConnection = null; private OdkDbInterface databaseService = null; private boolean isDestroying = false; BackgroundServices() { }; } /** * Creates required directories on the SDCard (or other external storage) * * @return true if there are tables present * @throws RuntimeException * if there is no SDCard or the directory exists as a non directory */ public static void createODKDirs(String appName) throws RuntimeException { ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); } // handed across orientation changes private final BackgroundTasks mBackgroundTasks = new BackgroundTasks(); // handed across orientation changes private final BackgroundServices mBackgroundServices = new BackgroundServices(); // These are expected to be broken down and set up during orientation changes. private InitializationListener mInitializationListener = null; private boolean shuttingDown = false; public CommonApplication() { super(); } @SuppressLint("NewApi") @Override public void onCreate() { shuttingDown = false; super.onCreate(); if (Build.VERSION.SDK_INT >= 19) { WebView.setWebContentsDebuggingEnabled(true); } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); Log.i(t, "onConfigurationChanged"); } @Override public void onTerminate() { cleanShutdown(); super.onTerminate(); Log.i(t, "onTerminate"); } public abstract int getConfigZipResourceId(); public abstract int getSystemZipResourceId(); public abstract int getWebKitResourceId(); public boolean shouldRunInitializationTask(String appName) { if ( isMocked() ) { if ( isDisableInitializeCascade() ) { return false; } } PropertiesSingleton props = CommonToolProperties.get(this, appName); return props.shouldRunInitializationTask(this.getToolName()); } public void clearRunInitializationTask(String appName) { PropertiesSingleton props = CommonToolProperties.get(this, appName); props.clearRunInitializationTask(this.getToolName()); } public void setRunInitializationTask(String appName) { PropertiesSingleton props = CommonToolProperties.get(this, appName); props.setRunInitializationTask(this.getToolName()); } private <T> void executeTask(AsyncTask<T, ?, ?> task, T... args) { int androidVersion = android.os.Build.VERSION.SDK_INT; if (androidVersion < 11) { task.execute(args); } else { // TODO: execute on serial executor in version 11 onward... task.execute(args); // task.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, (Void[]) null); } } private Activity activeActivity = null; private Activity databaseListenerActivity = null; public void onActivityPause(Activity activity) { if ( activeActivity == activity ) { mInitializationListener = null; if (mBackgroundTasks.mInitializationTask != null) { mBackgroundTasks.mInitializationTask.setInitializationListener(null); } } } public void onActivityDestroy(Activity activity) { if ( activeActivity == activity ) { activeActivity = null; mInitializationListener = null; if (mBackgroundTasks.mInitializationTask != null) { mBackgroundTasks.mInitializationTask.setInitializationListener(null); } final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { CommonApplication.this.testForShutdown(); } }, 500); } } private void cleanShutdown() { try { shuttingDown = true; shutdownServices(); } finally { shuttingDown = false; } } private void testForShutdown() { // no other activity has been started -- shut down if ( activeActivity == null ) { cleanShutdown(); } } public void onActivityResume(Activity activity) { databaseListenerActivity = null; activeActivity = activity; if (mBackgroundTasks.mInitializationTask != null) { mBackgroundTasks.mInitializationTask.setInitializationListener(this); } // be sure the services are connected... mBackgroundServices.isDestroying = false; configureView(); // failsafe -- ensure that the services are active... bindToService(); } // ///////////////////////////////////////////////////////////////////////// // service interactions private void unbindWebkitfilesServiceWrapper() { try { ServiceConnectionWrapper tmp = mBackgroundServices.webkitfilesServiceConnection; mBackgroundServices.webkitfilesServiceConnection = null; if ( tmp != null ) { unbindService(tmp); } } catch ( Exception e ) { // ignore e.printStackTrace(); } } private void unbindDatabaseBinderWrapper() { try { ServiceConnectionWrapper tmp = mBackgroundServices.databaseServiceConnection; mBackgroundServices.databaseServiceConnection = null; if ( tmp != null ) { unbindService(tmp); triggerDatabaseEvent(false); } } catch ( Exception e ) { // ignore e.printStackTrace(); } } private void shutdownServices() { Log.i(t, "shutdownServices - Releasing WebServer and database service"); mBackgroundServices.isDestroying = true; mBackgroundServices.webkitfilesService = null; mBackgroundServices.databaseService = null; // release interfaces held by the view configureView(); // release the webkitfilesService unbindWebkitfilesServiceWrapper(); unbindDatabaseBinderWrapper(); } private void bindToService() { if ( isMocked ) { // we directly control all the service binding interactions if we are mocked return; } if (!shuttingDown && !mBackgroundServices.isDestroying) { PackageManager pm = getPackageManager(); boolean useWebServer = (pm.checkPermission(PERMISSION_WEBSERVER, getPackageName()) == PackageManager.PERMISSION_GRANTED); boolean useDatabase = (pm.checkPermission(PERMISSION_DATABASE, getPackageName()) == PackageManager.PERMISSION_GRANTED); // do something if (useWebServer && mBackgroundServices.webkitfilesService == null && mBackgroundServices.webkitfilesServiceConnection == null) { Log.i(t, "Attempting bind to WebServer service"); mBackgroundServices.webkitfilesServiceConnection = new ServiceConnectionWrapper(); Intent bind_intent = new Intent(); bind_intent.setClassName(WebkitServerConsts.WEBKITSERVER_SERVICE_PACKAGE, WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS); bindService( bind_intent, mBackgroundServices.webkitfilesServiceConnection, Context.BIND_AUTO_CREATE | ((Build.VERSION.SDK_INT >= 14) ? Context.BIND_ADJUST_WITH_ACTIVITY : 0)); } if (useDatabase && mBackgroundServices.databaseService == null && mBackgroundServices.databaseServiceConnection == null) { Log.i(t, "Attempting bind to Database service"); mBackgroundServices.databaseServiceConnection = new ServiceConnectionWrapper(); Intent bind_intent = new Intent(); bind_intent.setClassName(DatabaseConsts.DATABASE_SERVICE_PACKAGE, DatabaseConsts.DATABASE_SERVICE_CLASS); bindService( bind_intent, mBackgroundServices.databaseServiceConnection, Context.BIND_AUTO_CREATE | ((Build.VERSION.SDK_INT >= 14) ? Context.BIND_ADJUST_WITH_ACTIVITY : 0)); } } } /** * * @param className * @param service can be null if we are mocked */ private void doServiceConnected(ComponentName className, IBinder service) { if (className.getClassName().equals(WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS)) { Log.i(t, "Bound to WebServer service"); mBackgroundServices.webkitfilesService = (service == null) ? null : OdkWebkitServerInterface.Stub.asInterface(service); } if (className.getClassName().equals(DatabaseConsts.DATABASE_SERVICE_CLASS)) { Log.i(t, "Bound to Database service"); mBackgroundServices.databaseService = (service == null) ? null : OdkDbInterface.Stub.asInterface(service); triggerDatabaseEvent(false); } configureView(); } public OdkDbInterface getDatabase() { if ( isMocked ) { return mockDatabaseService; } else { return mBackgroundServices.databaseService; } } private OdkWebkitServerInterface getWebkitServer() { if ( isMocked ) { return mockWebkitServerService; } else { return mBackgroundServices.webkitfilesService; } } public void configureView() { if ( activeActivity != null ) { Log.i(t, "configureView - possibly updating service information within ODKWebView"); if ( getWebKitResourceId() != -1 ) { View v = activeActivity.findViewById(getWebKitResourceId()); if (v != null && v instanceof ODKWebView) { ODKWebView wv = (ODKWebView) v; if (mBackgroundServices.isDestroying) { wv.serviceChange(false); } else { OdkWebkitServerInterface webkitServerIf = getWebkitServer(); OdkDbInterface dbIf = getDatabase(); wv.serviceChange(webkitServerIf != null && dbIf != null); } } } } } private void doServiceDisconnected(ComponentName className) { if (className.getClassName().equals(WebkitServerConsts.WEBKITSERVER_SERVICE_CLASS)) { if (mBackgroundServices.isDestroying) { Log.i(t, "Unbound from WebServer service (intentionally)"); } else { Log.w(t, "Unbound from WebServer service (unexpected)"); } mBackgroundServices.webkitfilesService = null; unbindWebkitfilesServiceWrapper(); } if (className.getClassName().equals(DatabaseConsts.DATABASE_SERVICE_CLASS)) { if (mBackgroundServices.isDestroying) { Log.i(t, "Unbound from Database service (intentionally)"); } else { Log.w(t, "Unbound from Database service (unexpected)"); } mBackgroundServices.databaseService = null; unbindDatabaseBinderWrapper(); } configureView(); // the bindToService() method decides whether to connect or not... bindToService(); } // ///////////////////////////////////////////////////////////////////////// // registrations /** * Called by an activity when it has been sufficiently initialized so * that it can handle a databaseAvailable() call. * * @param activity */ public void establishDatabaseConnectionListener(Activity activity) { databaseListenerActivity = activity; triggerDatabaseEvent(true); } /** * If the given activity is active, then fire the callback based upon * the availability of the database. * * @param activity * @param listener */ public void possiblyFireDatabaseCallback(Activity activity, DatabaseConnectionListener listener) { if ( activeActivity != null && activeActivity == databaseListenerActivity && databaseListenerActivity == activity ) { if ( this.getDatabase() == null ) { listener.databaseUnavailable(); } else { listener.databaseAvailable(); } } } private void triggerDatabaseEvent(boolean availableOnly) { if ( activeActivity != null && activeActivity == databaseListenerActivity && activeActivity instanceof DatabaseConnectionListener ) { if ( !availableOnly && this.getDatabase() == null ) { ((DatabaseConnectionListener) activeActivity).databaseUnavailable(); } else { ((DatabaseConnectionListener) activeActivity).databaseAvailable(); } } } public void establishInitializationListener(InitializationListener listener) { mInitializationListener = listener; // async task may have completed while we were reorienting... if (mBackgroundTasks.mInitializationTask != null && mBackgroundTasks.mInitializationTask.getStatus() == AsyncTask.Status.FINISHED) { this.initializationComplete(mBackgroundTasks.mInitializationTask.getOverallSuccess(), mBackgroundTasks.mInitializationTask.getResult()); } } // /////////////////////////////////////////////////// // actions public synchronized boolean initializeAppName(String appName, InitializationListener listener) { mInitializationListener = listener; if (mBackgroundTasks.mInitializationTask != null && mBackgroundTasks.mInitializationTask.getStatus() != AsyncTask.Status.FINISHED) { // Toast.makeText(this.getActivity(), // getString(R.string.expansion_in_progress), // Toast.LENGTH_LONG).show(); return true; } else if ( getDatabase() != null ) { InitializationTask cf = new InitializationTask(); cf.setApplication(this); cf.setAppName(appName); cf.setInitializationListener(this); mBackgroundTasks.mInitializationTask = cf; executeTask(mBackgroundTasks.mInitializationTask, (Void) null); return true; } else { return false; } } // ///////////////////////////////////////////////////////////////////////// // clearing tasks // // NOTE: clearing these makes us forget that they are running, but it is // up to the task itself to eventually shutdown. i.e., we don't quite // know when they actually stop. public synchronized void clearInitializationTask() { mInitializationListener = null; if (mBackgroundTasks.mInitializationTask != null) { mBackgroundTasks.mInitializationTask.setInitializationListener(null); if (mBackgroundTasks.mInitializationTask.getStatus() != AsyncTask.Status.FINISHED) { mBackgroundTasks.mInitializationTask.cancel(true); } } mBackgroundTasks.mInitializationTask = null; } // ///////////////////////////////////////////////////////////////////////// // cancel requests // // These maintain communications paths, so that we get a failure // completion callback eventually. public synchronized void cancelInitializationTask() { if (mBackgroundTasks.mInitializationTask != null) { if (mBackgroundTasks.mInitializationTask.getStatus() != AsyncTask.Status.FINISHED) { mBackgroundTasks.mInitializationTask.cancel(true); } } } // ///////////////////////////////////////////////////////////////////////// // callbacks @Override public void initializationComplete(boolean overallSuccess, ArrayList<String> result) { if (mInitializationListener != null) { mInitializationListener.initializationComplete(overallSuccess, result); } } @Override public void initializationProgressUpdate(String status) { if (mInitializationListener != null) { mInitializationListener.initializationProgressUpdate(status); } } }
Define split API for finer control within class hierarchy
androidcommon_lib/src/main/java/org/opendatakit/common/android/application/CommonApplication.java
Define split API for finer control within class hierarchy
<ide><path>ndroidcommon_lib/src/main/java/org/opendatakit/common/android/application/CommonApplication.java <ide> triggerDatabaseEvent(true); <ide> } <ide> <add> public void establishDoNotFireDatabaseConnectionListener(Activity activity) { <add> databaseListenerActivity = activity; <add> } <add> <add> public void fireDatabaseConnectionListener() { <add> triggerDatabaseEvent(true); <add> } <add> <ide> /** <ide> * If the given activity is active, then fire the callback based upon <ide> * the availability of the database.
Java
apache-2.0
dac1aa0251d936c9cb84cd089c7a3abdfec553ca
0
paulk-asert/incubator-groovy,paulk-asert/incubator-groovy,shils/groovy,apache/incubator-groovy,shils/incubator-groovy,apache/incubator-groovy,shils/groovy,paulk-asert/groovy,apache/incubator-groovy,shils/incubator-groovy,apache/groovy,apache/groovy,paulk-asert/groovy,apache/incubator-groovy,apache/groovy,paulk-asert/incubator-groovy,apache/groovy,paulk-asert/groovy,paulk-asert/incubator-groovy,shils/groovy,paulk-asert/incubator-groovy,paulk-asert/groovy,shils/groovy,shils/incubator-groovy,shils/incubator-groovy
/* * 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 org.codehaus.groovy.tools.groovydoc; import groovy.util.CharsetToolkit; import org.apache.tools.ant.BuildFileRule; import org.codehaus.groovy.runtime.ResourceGroovyMethods; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.File; import java.nio.charset.StandardCharsets; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class GroovyDocTest { @Rule public BuildFileRule rule = new BuildFileRule(); private File tmpDir; private static final String SRC_TESTFILES; static { String groovyDocResourcesPathInSubproject = "src/test/resources/groovydoc/"; String groovyDocResourcesPathFromMainProject = "subprojects/groovy-groovydoc/" + groovyDocResourcesPathInSubproject; if (new File(groovyDocResourcesPathInSubproject).exists()) { SRC_TESTFILES = groovyDocResourcesPathInSubproject; } else if (new File(groovyDocResourcesPathFromMainProject).exists()) { SRC_TESTFILES = groovyDocResourcesPathFromMainProject; } else { SRC_TESTFILES = null; } } @Before public void setUp() { if (SRC_TESTFILES == null) { throw new RuntimeException("Could not identify path to resources dir."); } rule.configureProject(SRC_TESTFILES + "groovyDocTests.xml"); tmpDir = new File(rule.getProject().getProperty("tmpdir")); } @After public void tearDown() { ResourceGroovyMethods.deleteDir(tmpDir); } @Test public void testCustomClassTemplate() throws Exception { rule.executeTarget("testCustomClassTemplate"); final File testfilesPackageDir = new File(tmpDir, "org/codehaus/groovy/tools/groovydoc/testfiles"); final String[] list = testfilesPackageDir.list((file, name) -> name.equals("DocumentedClass.html")); assertNotNull("Dir not found: " + testfilesPackageDir.getAbsolutePath(), list); assertEquals(1, list.length); File documentedClassHtmlDoc = new File(testfilesPackageDir, list[0]); List<String> lines = ResourceGroovyMethods.readLines(documentedClassHtmlDoc); assertTrue("\"<title>DocumentedClass</title>\" not in: " + lines, lines.contains("<title>DocumentedClass</title>")); assertTrue("\"This is a custom class template.\" not in: " + lines, lines.contains("This is a custom class template.")); } @Test public void testFileEncoding() throws Exception { rule.executeTarget("testFileEncoding"); final File testfilesPackageDir = new File(tmpDir, "org/codehaus/groovy/tools/groovydoc/testfiles"); final String[] list = testfilesPackageDir.list((file, name) -> name.equals("DocumentedClass.html")); File documentedClassHtmlDoc = new File(testfilesPackageDir, list[0]); CharsetToolkit charsetToolkit = new CharsetToolkit(documentedClassHtmlDoc); assertEquals("The generated groovydoc must be in 'UTF-16LE' file encoding.'", StandardCharsets.UTF_16LE, charsetToolkit.getCharset()); } }
subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocTest.java
/* * 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 org.codehaus.groovy.tools.groovydoc; import groovy.util.CharsetToolkit; import org.apache.tools.ant.BuildFileTest; import org.codehaus.groovy.runtime.ResourceGroovyMethods; import java.io.File; import java.io.FilenameFilter; import java.nio.charset.Charset; import java.util.List; public class GroovyDocTest extends BuildFileTest { private static final String SRC_TESTFILES; private File tmpDir; static{ String groovyDocResourcesPathInSubproject = "src/test/resources/groovydoc/"; String groovyDocResourcesPathFromMainProject = "subprojects/groovy-groovydoc/" + groovyDocResourcesPathInSubproject; if (new File(groovyDocResourcesPathInSubproject).exists()){ SRC_TESTFILES = groovyDocResourcesPathInSubproject; } else if (new File(groovyDocResourcesPathFromMainProject).exists()){ SRC_TESTFILES = groovyDocResourcesPathFromMainProject; } else { fail("Could not identify path to resources dir."); SRC_TESTFILES = ""; } } public GroovyDocTest(String name) { super(name); } @Override public void setUp() throws Exception { configureProject(SRC_TESTFILES + "groovyDocTests.xml"); tmpDir = new File(getProject().getProperty("tmpdir")); } @Override protected void tearDown() throws Exception { ResourceGroovyMethods.deleteDir(tmpDir); super.tearDown(); } public void testCustomClassTemplate() throws Exception { executeTarget("testCustomClassTemplate"); final File testfilesPackageDir = new File(tmpDir, "org/codehaus/groovy/tools/groovydoc/testfiles"); System.err.println("testfilesPackageDir = " + testfilesPackageDir); final String[] list = testfilesPackageDir.list(new FilenameFilter() { public boolean accept(File file, String name) { return name.equals("DocumentedClass.html"); } }); assertNotNull("Dir not found: " + testfilesPackageDir.getAbsolutePath(), list); assertEquals(1, list.length); File documentedClassHtmlDoc = new File(testfilesPackageDir, list[0]); List<String> lines = ResourceGroovyMethods.readLines(documentedClassHtmlDoc); assertTrue("\"<title>DocumentedClass</title>\" not in: " + lines, lines.contains("<title>DocumentedClass</title>")); assertTrue("\"This is a custom class template.\" not in: " + lines, lines.contains("This is a custom class template.")); } public void testFileEncoding() throws Exception { executeTarget("testFileEncoding"); final File testfilesPackageDir = new File(tmpDir, "org/codehaus/groovy/tools/groovydoc/testfiles"); System.err.println("testfilesPackageDir = " + testfilesPackageDir); final String[] list = testfilesPackageDir.list(new FilenameFilter() { public boolean accept(File file, String name) { return name.equals("DocumentedClass.html"); } }); File documentedClassHtmlDoc = new File(testfilesPackageDir, list[0]); CharsetToolkit charsetToolkit = new CharsetToolkit(documentedClassHtmlDoc); assertEquals("The generated groovydoc must be in 'UTF-16LE' file encoding.'", Charset.forName("UTF-16LE"), charsetToolkit.getCharset()); } }
use JUnit4 rather than JUnit 3 style to avoid using deprecated method
subprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocTest.java
use JUnit4 rather than JUnit 3 style to avoid using deprecated method
<ide><path>ubprojects/groovy-groovydoc/src/test/groovy/org/codehaus/groovy/tools/groovydoc/GroovyDocTest.java <ide> package org.codehaus.groovy.tools.groovydoc; <ide> <ide> import groovy.util.CharsetToolkit; <del>import org.apache.tools.ant.BuildFileTest; <add>import org.apache.tools.ant.BuildFileRule; <ide> import org.codehaus.groovy.runtime.ResourceGroovyMethods; <add>import org.junit.After; <add>import org.junit.Before; <add>import org.junit.Rule; <add>import org.junit.Test; <ide> <ide> import java.io.File; <del>import java.io.FilenameFilter; <del>import java.nio.charset.Charset; <add>import java.nio.charset.StandardCharsets; <ide> import java.util.List; <ide> <del>public class GroovyDocTest extends BuildFileTest { <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertNotNull; <add>import static org.junit.Assert.assertTrue; <ide> <add>public class GroovyDocTest { <add> <add> @Rule <add> public BuildFileRule rule = new BuildFileRule(); <add> <add> private File tmpDir; <ide> private static final String SRC_TESTFILES; <ide> <del> private File tmpDir; <del> <del> static{ <add> static { <ide> String groovyDocResourcesPathInSubproject = "src/test/resources/groovydoc/"; <ide> String groovyDocResourcesPathFromMainProject = "subprojects/groovy-groovydoc/" + groovyDocResourcesPathInSubproject; <del> if (new File(groovyDocResourcesPathInSubproject).exists()){ <add> if (new File(groovyDocResourcesPathInSubproject).exists()) { <ide> SRC_TESTFILES = groovyDocResourcesPathInSubproject; <del> } <del> else if (new File(groovyDocResourcesPathFromMainProject).exists()){ <add> } else if (new File(groovyDocResourcesPathFromMainProject).exists()) { <ide> SRC_TESTFILES = groovyDocResourcesPathFromMainProject; <del> } <del> else { <del> fail("Could not identify path to resources dir."); <del> SRC_TESTFILES = ""; <add> } else { <add> SRC_TESTFILES = null; <ide> } <ide> } <ide> <del> public GroovyDocTest(String name) { <del> super(name); <add> @Before <add> public void setUp() { <add> if (SRC_TESTFILES == null) { <add> throw new RuntimeException("Could not identify path to resources dir."); <add> } <add> rule.configureProject(SRC_TESTFILES + "groovyDocTests.xml"); <add> tmpDir = new File(rule.getProject().getProperty("tmpdir")); <ide> } <ide> <del> @Override <del> public void setUp() throws Exception { <del> configureProject(SRC_TESTFILES + "groovyDocTests.xml"); <del> tmpDir = new File(getProject().getProperty("tmpdir")); <add> @After <add> public void tearDown() { <add> ResourceGroovyMethods.deleteDir(tmpDir); <ide> } <ide> <del> @Override <del> protected void tearDown() throws Exception { <del> ResourceGroovyMethods.deleteDir(tmpDir); <del> super.tearDown(); <del> } <del> <add> @Test <ide> public void testCustomClassTemplate() throws Exception { <del> executeTarget("testCustomClassTemplate"); <add> rule.executeTarget("testCustomClassTemplate"); <ide> <ide> final File testfilesPackageDir = new File(tmpDir, "org/codehaus/groovy/tools/groovydoc/testfiles"); <del> System.err.println("testfilesPackageDir = " + testfilesPackageDir); <del> final String[] list = testfilesPackageDir.list(new FilenameFilter() { <del> public boolean accept(File file, String name) { <del> return name.equals("DocumentedClass.html"); <del> } <del> }); <add> final String[] list = testfilesPackageDir.list((file, name) -> name.equals("DocumentedClass.html")); <ide> <ide> assertNotNull("Dir not found: " + testfilesPackageDir.getAbsolutePath(), list); <ide> assertEquals(1, list.length); <ide> assertTrue("\"This is a custom class template.\" not in: " + lines, lines.contains("This is a custom class template.")); <ide> } <ide> <add> @Test <ide> public void testFileEncoding() throws Exception { <del> executeTarget("testFileEncoding"); <add> rule.executeTarget("testFileEncoding"); <ide> <ide> final File testfilesPackageDir = new File(tmpDir, "org/codehaus/groovy/tools/groovydoc/testfiles"); <del> System.err.println("testfilesPackageDir = " + testfilesPackageDir); <del> final String[] list = testfilesPackageDir.list(new FilenameFilter() { <del> public boolean accept(File file, String name) { <del> return name.equals("DocumentedClass.html"); <del> } <del> }); <add> final String[] list = testfilesPackageDir.list((file, name) -> name.equals("DocumentedClass.html")); <ide> <ide> File documentedClassHtmlDoc = new File(testfilesPackageDir, list[0]); <ide> CharsetToolkit charsetToolkit = new CharsetToolkit(documentedClassHtmlDoc); <ide> <del> assertEquals("The generated groovydoc must be in 'UTF-16LE' file encoding.'", Charset.forName("UTF-16LE"), charsetToolkit.getCharset()); <add> assertEquals("The generated groovydoc must be in 'UTF-16LE' file encoding.'", StandardCharsets.UTF_16LE, charsetToolkit.getCharset()); <ide> } <ide> }
Java
mit
974e5429274cd302ed831717e4372a187fa70a4b
0
lemmy/tlaplus,tlaplus/tlaplus,lemmy/tlaplus,tlaplus/tlaplus,lemmy/tlaplus,tlaplus/tlaplus,lemmy/tlaplus,tlaplus/tlaplus
// Copyright (c) 2011 Microsoft Corporation. All rights reserved. package tlc2.tool.fp; import java.io.File; import java.io.IOException; import java.text.DecimalFormat; import java.util.Date; import org.junit.After; import org.junit.Before; public abstract class AbstractFPSetTest { protected static final long RNG_SEED = 15041980L; protected static final String tmpdir = System.getProperty("java.io.tmpdir") + File.separator + "FPSetTest" + System.currentTimeMillis(); protected static final String filename = "FPSetTestTest"; protected static final DecimalFormat df = new DecimalFormat("###,###.###"); protected static final DecimalFormat pf = new DecimalFormat("#.##"); protected long previousTimestamp; protected long previousSize; protected long startTimestamp; protected Date endTimeStamp; private File dir; /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ @Before public void setUp() throws Exception { // create temp folder dir = new File(tmpdir); dir.mkdirs(); previousTimestamp = startTimestamp = System.currentTimeMillis(); previousSize = 0L; System.out.println("Test started at " + new Date()); } /* (non-Javadoc) * @see junit.framework.TestCase#tearDown() */ @After public void tearDown() { if (endTimeStamp == null) { endTimeStamp = new Date(); } System.out.println("Test finished at " + endTimeStamp); // delete all nested files final File[] listFiles = dir.listFiles(); for (int i = 0; i < listFiles.length; i++) { final File aFile = listFiles[i]; aFile.delete(); } dir.delete(); } /** * @param freeMemory * @return A new {@link FPSet} instance * @throws IOException */ protected abstract FPSet getFPSet(final FPSetConfiguration fpSetConfig) throws IOException; protected FPSet getFPSetInitialized() throws IOException { return getFPSetInitialized(1); } protected FPSet getFPSetInitialized(int numThreads) throws IOException { final FPSet fpSet = getFPSet(new FPSetConfiguration()); fpSet.init(numThreads, tmpdir, filename); if (fpSet instanceof FPSetStatistic) { FPSetStatistic fpSetStats = (FPSetStatistic) fpSet; long maxTblCnt = fpSetStats.getMaxTblCnt(); System.out.println("Maximum FPSet table count is: " + df.format(maxTblCnt) + " (approx: " + df.format(maxTblCnt * FPSet.LongSize >> 20) + " GiB)"); System.out.println("FPSet lock count is: " + fpSetStats.getLockCnt()); System.out.println("FPSet bucket count is: " + fpSetStats.getTblCapacity()); } System.out.println("Testing " + fpSet.getClass().getCanonicalName()); return fpSet; } // insertion speed public void printInsertionSpeed(final FPSet fpSet) { // print every minute long now = System.currentTimeMillis(); final double factor = (now - previousTimestamp) / 60000d; if (factor >= 1d) { final long currentSize = fpSet.size(); long insertions = (long) ((currentSize - previousSize) * factor); if (fpSet instanceof FPSetStatistic) { FPSetStatistic fpSetStatistics = (FPSetStatistic) fpSet; System.out.println(System.currentTimeMillis() + " s; " + df.format(insertions) + " insertions/min; " + pf.format(fpSetStatistics.getLoadFactor()) + " load factor"); } else { System.out.println(System.currentTimeMillis() + " s (epoch); " + df.format(insertions) + " insertions/min"); } previousTimestamp = now; previousSize = currentSize; } } public void printInsertionSpeed(final FPSet fpSet, long start, long end) { final long size = fpSet.size(); // Normalize insertions to minutes. final long duration = Math.max(end - start, 1); //ms (avoid div-by-zero) final long insertions = (long) ((size / duration) * 60000L); if (fpSet instanceof FPSetStatistic) { FPSetStatistic fpSetStatistics = (FPSetStatistic) fpSet; System.out.println(System.currentTimeMillis() + " s; " + df.format(insertions) + " insertions/min; " + pf.format(fpSetStatistics.getLoadFactor()) + " load factor"); } else { System.out.println(System.currentTimeMillis() + " s (epoch); " + df.format(insertions) + " insertions/min"); } } }
tlatools/test/tlc2/tool/fp/AbstractFPSetTest.java
// Copyright (c) 2011 Microsoft Corporation. All rights reserved. package tlc2.tool.fp; import java.io.File; import java.io.IOException; import java.text.DecimalFormat; import java.util.Date; import org.junit.After; import org.junit.Before; public abstract class AbstractFPSetTest { protected static final long RNG_SEED = 15041980L; protected static final String tmpdir = System.getProperty("java.io.tmpdir") + File.separator + "FPSetTest" + System.currentTimeMillis(); protected static final String filename = "FPSetTestTest"; protected static final DecimalFormat df = new DecimalFormat("###,###.###"); protected static final DecimalFormat pf = new DecimalFormat("#.##"); protected long previousTimestamp; protected long previousSize; protected long startTimestamp; protected Date endTimeStamp; private File dir; /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ @Before public void setUp() throws Exception { // create temp folder dir = new File(tmpdir); dir.mkdirs(); previousTimestamp = startTimestamp = System.currentTimeMillis(); previousSize = 0L; System.out.println("Test started at " + new Date()); } /* (non-Javadoc) * @see junit.framework.TestCase#tearDown() */ @After public void tearDown() { if (endTimeStamp == null) { endTimeStamp = new Date(); } System.out.println("Test finished at " + endTimeStamp); // delete all nested files final File[] listFiles = dir.listFiles(); for (int i = 0; i < listFiles.length; i++) { final File aFile = listFiles[i]; aFile.delete(); } dir.delete(); } /** * @param freeMemory * @return A new {@link FPSet} instance * @throws IOException */ protected abstract FPSet getFPSet(final FPSetConfiguration fpSetConfig) throws IOException; protected FPSet getFPSetInitialized() throws IOException { return getFPSetInitialized(1); } protected FPSet getFPSetInitialized(int numThreads) throws IOException { final FPSet fpSet = getFPSet(new FPSetConfiguration()); fpSet.init(numThreads, tmpdir, filename); if (fpSet instanceof FPSetStatistic) { FPSetStatistic fpSetStats = (FPSetStatistic) fpSet; long maxTblCnt = fpSetStats.getMaxTblCnt(); System.out.println("Maximum FPSet table count is: " + df.format(maxTblCnt) + " (approx: " + df.format(maxTblCnt * FPSet.LongSize >> 20) + " GiB)"); System.out.println("FPSet lock count is: " + fpSetStats.getLockCnt()); System.out.println("FPSet bucket count is: " + fpSetStats.getTblCapacity()); } System.out.println("Testing " + fpSet.getClass().getCanonicalName()); return fpSet; } // insertion speed public void printInsertionSpeed(final FPSet fpSet) { // print every minute long now = System.currentTimeMillis(); final double factor = (now - previousTimestamp) / 60000d; if (factor >= 1d) { final long currentSize = fpSet.size(); long insertions = (long) ((currentSize - previousSize) * factor); if (fpSet instanceof FPSetStatistic) { FPSetStatistic fpSetStatistics = (FPSetStatistic) fpSet; System.out.println(System.currentTimeMillis() + " s; " + df.format(insertions) + " insertions/min; " + pf.format(fpSetStatistics.getLoadFactor()) + " load factor"); } else { System.out.println(System.currentTimeMillis() + " s (epoch); " + df.format(insertions) + " insertions/min"); } previousTimestamp = now; previousSize = currentSize; } } public void printInsertionSpeed(final FPSet fpSet, long start, long end) { final long size = fpSet.size(); // Normalize insertions to minutes. final long duration = (end - start) / 1000L; //seconds final long insertions = (long) ((size / duration) * 60); if (fpSet instanceof FPSetStatistic) { FPSetStatistic fpSetStatistics = (FPSetStatistic) fpSet; System.out.println(System.currentTimeMillis() + " s; " + df.format(insertions) + " insertions/min; " + pf.format(fpSetStatistics.getLoadFactor()) + " load factor"); } else { System.out.println(System.currentTimeMillis() + " s (epoch); " + df.format(insertions) + " insertions/min"); } } }
Handle div-by-zero. [Tests][TLC]
tlatools/test/tlc2/tool/fp/AbstractFPSetTest.java
Handle div-by-zero.
<ide><path>latools/test/tlc2/tool/fp/AbstractFPSetTest.java <ide> public void printInsertionSpeed(final FPSet fpSet, long start, long end) { <ide> final long size = fpSet.size(); <ide> // Normalize insertions to minutes. <del> final long duration = (end - start) / 1000L; //seconds <del> final long insertions = (long) ((size / duration) * 60); <add> final long duration = Math.max(end - start, 1); //ms (avoid div-by-zero) <add> final long insertions = (long) ((size / duration) * 60000L); <ide> if (fpSet instanceof FPSetStatistic) { <ide> FPSetStatistic fpSetStatistics = (FPSetStatistic) fpSet; <ide> System.out.println(System.currentTimeMillis() + " s; " + df.format(insertions) + " insertions/min; " + pf.format(fpSetStatistics.getLoadFactor()) + " load factor");
Java
apache-2.0
9a5a60dd738d819fe430b7657f4232d50b5522dd
0
CloudSlang/cloud-slang,CloudSlang/cloud-slang,CloudSlang/cloud-slang,CloudSlang/cloud-slang
/** * **************************************************************************** * (c) Copyright 2014 Hewlett-Packard Development Company, L.P. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License v2.0 which accompany this distribution. * <p/> * The Apache License is available at * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * ***************************************************************************** */ package io.cloudslang.lang.entities.bindings.values; import com.fasterxml.jackson.annotation.JsonIgnore; import io.cloudslang.lang.entities.encryption.EncryptionProvider; import javassist.util.proxy.ProxyObjectInputStream; import javassist.util.proxy.ProxyObjectOutputStream; import org.python.apache.commons.compress.utils.IOUtils; import org.python.apache.xerces.impl.dv.util.Base64; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /** * Sensitive InOutParam value * * Created by Ifat Gavish on 19/04/2016 */ public class SensitiveValue implements Value { public static final String SENSITIVE_VALUE_MASK = "********"; private String content = null; private Serializable originalContent = null; @SuppressWarnings("unused") protected SensitiveValue() { } protected SensitiveValue(Serializable content) { originalContent = content; encrypt(); } public void encrypt() { content = encrypt(originalContent); originalContent = null; } public void decrypt() { originalContent = decrypt(content); content = null; } public String getContent() { return content; } protected void setContent(String content) { this.content = content; } @Override public Serializable get() { return decrypt(content); } @JsonIgnore @Override public boolean isSensitive() { return true; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SensitiveValue that = (SensitiveValue) o; return content != null ? content.equals(that.content) : that.content == null; } @Override public int hashCode() { return content != null ? content.hashCode() : 0; } @Override public String toString() { return SENSITIVE_VALUE_MASK; } private String encrypt(Serializable originalContent) { if(originalContent != null) { byte[] serialized = serialize(originalContent); String encoded = Base64.encode(serialized); return EncryptionProvider.get().encrypt(encoded.toCharArray()); } return null; } private Serializable decrypt(String content) { if(content != null) { char[] decrypted = EncryptionProvider.get().decrypt(content); byte[] decoded = Base64.decode(new String(decrypted)); return deserialize(decoded); } return null; } private byte[] serialize(Serializable data) { ObjectOutputStream oos = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); oos = new ProxyObjectOutputStream(baos); oos.writeObject(data); return baos.toByteArray(); } catch (Exception e) { throw new RuntimeException("Failed to serialize object", e); } finally { if (oos != null) { IOUtils.closeQuietly(oos); } } } private Serializable deserialize(byte[] data) { ObjectInputStream ois = null; try { ByteArrayInputStream bais = new ByteArrayInputStream(data); ois = new ProxyObjectInputStream(bais); return (Serializable)ois.readObject(); } catch (Exception e) { throw new RuntimeException("Failed to deserialize object", e); } finally { if (ois != null) { IOUtils.closeQuietly(ois); } } } }
cloudslang-entities/src/main/java/io/cloudslang/lang/entities/bindings/values/SensitiveValue.java
/** * **************************************************************************** * (c) Copyright 2014 Hewlett-Packard Development Company, L.P. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License v2.0 which accompany this distribution. * <p/> * The Apache License is available at * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * ***************************************************************************** */ package io.cloudslang.lang.entities.bindings.values; import com.fasterxml.jackson.annotation.JsonIgnore; import io.cloudslang.lang.entities.encryption.EncryptionProvider; import javassist.util.proxy.ProxyObjectInputStream; import javassist.util.proxy.ProxyObjectOutputStream; import org.python.apache.commons.compress.utils.IOUtils; import org.python.apache.xerces.impl.dv.util.Base64; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /** * Sensitive InOutParam value * * Created by Ifat Gavish on 19/04/2016 */ public class SensitiveValue implements Value { public static final String SENSITIVE_VALUE_MASK = "********"; private String content; @SuppressWarnings("unused") protected SensitiveValue() { } protected SensitiveValue(Serializable content) { byte[] serialized = serialize(content); String encoded = Base64.encode(serialized); this.content = EncryptionProvider.get().encrypt(encoded.toCharArray()); } public String getContent() { return content; } protected void setContent(String content) { this.content = content; } @Override public Serializable get() { char[] decrypted = EncryptionProvider.get().decrypt(content); byte[] decoded = Base64.decode(new String(decrypted)); return deserialize(decoded); } @JsonIgnore @Override public boolean isSensitive() { return true; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SensitiveValue that = (SensitiveValue) o; return content != null ? content.equals(that.content) : that.content == null; } @Override public int hashCode() { return content != null ? content.hashCode() : 0; } @Override public String toString() { return SENSITIVE_VALUE_MASK; } private byte[] serialize(Serializable data) { ObjectOutputStream oos = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); oos = new ProxyObjectOutputStream(baos); oos.writeObject(data); return baos.toByteArray(); } catch (Exception e) { throw new RuntimeException("Failed to serialize object", e); } finally { if (oos != null) { IOUtils.closeQuietly(oos); } } } private Serializable deserialize(byte[] data) { ObjectInputStream ois = null; try { ByteArrayInputStream bais = new ByteArrayInputStream(data); ois = new ProxyObjectInputStream(bais); return (Serializable)ois.readObject(); } catch (Exception e) { throw new RuntimeException("Failed to deserialize object", e); } finally { if (ois != null) { IOUtils.closeQuietly(ois); } } } }
sensitive value can be container for encrypted and not encrypted content
cloudslang-entities/src/main/java/io/cloudslang/lang/entities/bindings/values/SensitiveValue.java
sensitive value can be container for encrypted and not encrypted content
<ide><path>loudslang-entities/src/main/java/io/cloudslang/lang/entities/bindings/values/SensitiveValue.java <ide> <ide> public static final String SENSITIVE_VALUE_MASK = "********"; <ide> <del> private String content; <add> private String content = null; <add> private Serializable originalContent = null; <ide> <ide> @SuppressWarnings("unused") <ide> protected SensitiveValue() { <ide> } <ide> <ide> protected SensitiveValue(Serializable content) { <del> byte[] serialized = serialize(content); <del> String encoded = Base64.encode(serialized); <del> this.content = EncryptionProvider.get().encrypt(encoded.toCharArray()); <add> originalContent = content; <add> encrypt(); <add> } <add> <add> public void encrypt() { <add> content = encrypt(originalContent); <add> originalContent = null; <add> } <add> <add> public void decrypt() { <add> originalContent = decrypt(content); <add> content = null; <ide> } <ide> <ide> public String getContent() { <ide> <ide> @Override <ide> public Serializable get() { <del> char[] decrypted = EncryptionProvider.get().decrypt(content); <del> byte[] decoded = Base64.decode(new String(decrypted)); <del> return deserialize(decoded); <add> return decrypt(content); <ide> } <ide> <ide> @JsonIgnore <ide> @Override <ide> public String toString() { <ide> return SENSITIVE_VALUE_MASK; <add> } <add> <add> private String encrypt(Serializable originalContent) { <add> if(originalContent != null) { <add> byte[] serialized = serialize(originalContent); <add> String encoded = Base64.encode(serialized); <add> return EncryptionProvider.get().encrypt(encoded.toCharArray()); <add> } <add> return null; <add> } <add> <add> private Serializable decrypt(String content) { <add> if(content != null) { <add> char[] decrypted = EncryptionProvider.get().decrypt(content); <add> byte[] decoded = Base64.decode(new String(decrypted)); <add> return deserialize(decoded); <add> } <add> return null; <ide> } <ide> <ide> private byte[] serialize(Serializable data) {
Java
mit
9090e1ff4743cc8c8e7b6accd1e068281b1f2c83
0
sormuras/bach,sormuras/bach
/* * Bach - Java Shell Builder * Copyright (C) 2019 Christian Stein * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.sormuras.bach; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.function.Consumer; import java.util.function.UnaryOperator; import java.util.stream.Collectors; /*BODY*/ /** Command-line program argument list builder. */ public /*STATIC*/ class Command { private final String name; private final List<String> list = new ArrayList<>(); /** Initialize Command instance with zero or more arguments. */ Command(String name, Object... args) { this.name = name; addEach(args); } /** Add single argument by invoking {@link Object#toString()} on the given argument. */ Command add(Object argument) { list.add(argument.toString()); return this; } /** Add two arguments by invoking {@link #add(Object)} for the key and value elements. */ Command add(Object key, Object value) { return add(key).add(value); } /** Add two (or zero) arguments, the key and the paths joined by system's path separator. */ Command add(Object key, Collection<Path> paths) { return add(key, paths, UnaryOperator.identity()); } /** Add two (or zero) arguments, the key and the paths joined by system's path separator. */ Command add(Object key, Collection<Path> paths, UnaryOperator<String> operator) { var stream = paths.stream().filter(Files::exists).map(Object::toString); var value = stream.collect(Collectors.joining(File.pathSeparator)); if (value.isEmpty()) { return this; } return add(key, operator.apply(value)); } /** Add all arguments by invoking {@link #add(Object)} for each element. */ Command addEach(Object... arguments) { return addEach(List.of(arguments)); } /** Add all arguments by invoking {@link #add(Object)} for each element. */ Command addEach(Iterable<?> arguments) { arguments.forEach(this::add); return this; } /** Add a single argument iff the conditions is {@code true}. */ Command addIff(boolean condition, Object argument) { return condition ? add(argument) : this; } /** Add two arguments iff the conditions is {@code true}. */ Command addIff(boolean condition, Object key, Object value) { return condition ? add(key, value) : this; } /** Add two arguments iff the given optional value is present. */ @SuppressWarnings("OptionalUsedAsFieldOrParameterType") Command addIff(Object key, Optional<?> optionalValue) { return optionalValue.isPresent() ? add(key, optionalValue.get()) : this; } /** Let the consumer visit, usually modify, this instance iff the conditions is {@code true}. */ Command addIff(boolean condition, Consumer<Command> visitor) { if (condition) { visitor.accept(this); } return this; } /** Return the command's name. */ public String getName() { return name; } /** Return the command's arguments. */ public List<String> getList() { return list; } @Override public String toString() { var args = list.isEmpty() ? "<empty>" : "'" + String.join("', '", list) + "'"; return "Command{name='" + name + "', list=[" + args + "]}"; } /** Returns an array of {@link String} containing all of the collected arguments. */ String[] toStringArray() { return list.toArray(String[]::new); } }
src/modules/de.sormuras.bach/main/java/de/sormuras/bach/Command.java
/* * Bach - Java Shell Builder * Copyright (C) 2019 Christian Stein * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.sormuras.bach; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.function.Consumer; import java.util.function.UnaryOperator; import java.util.stream.Collectors; /*BODY*/ /** Command-line program argument list builder. */ public /*STATIC*/ class Command { private final String name; private final List<String> list = new ArrayList<>(); /** Initialize Command instance with zero or more arguments. */ Command(String name, Object... args) { this.name = name; addEach(args); } /** Add single argument by invoking {@link Object#toString()} on the given argument. */ Command add(Object argument) { list.add(argument.toString()); return this; } /** Add two arguments by invoking {@link #add(Object)} for the key and value elements. */ Command add(Object key, Object value) { return add(key).add(value); } /** Add two (or zero) arguments, the key and the paths joined by system's path separator. */ Command add(Object key, Collection<Path> paths) { return add(key, paths, UnaryOperator.identity()); } /** Add two (or zero) arguments, the key and the paths joined by system's path separator. */ Command add(Object key, Collection<Path> paths, UnaryOperator<String> operator) { var stream = paths.stream().filter(Files::exists).map(Object::toString); var value = stream.collect(Collectors.joining(File.pathSeparator)); if (value.isEmpty()) { return this; } return add(key, operator.apply(value)); } /** Add all arguments by invoking {@link #add(Object)} for each element. */ Command addEach(Object... arguments) { return addEach(List.of(arguments)); } /** Add all arguments by invoking {@link #add(Object)} for each element. */ Command addEach(Iterable<?> arguments) { arguments.forEach(this::add); return this; } /** Add a single argument iff the conditions is {@code true}. */ Command addIff(boolean condition, Object argument) { return condition ? add(argument) : this; } /** Add two arguments iff the conditions is {@code true}. */ Command addIff(boolean condition, Object key, Object value) { return condition ? add(key, value) : this; } /** Add two arguments iff the given optional value is present. */ @SuppressWarnings("OptionalUsedAsFieldOrParameterType") Command addIff(Object key, Optional<?> optionalValue) { return optionalValue.isPresent() ? add(key, optionalValue.get()) : this; } /** Let the consumer visit, usually modify, this instance iff the conditions is {@code true}. */ Command addIff(boolean condition, Consumer<Command> visitor) { if (condition) { visitor.accept(this); } return this; } /** Return the command's name. */ public String getName() { return name; } @Override public String toString() { var args = list.isEmpty() ? "<empty>" : "'" + String.join("', '", list) + "'"; return "Command{name='" + name + "', list=[" + args + "]}"; } /** Returns an array of {@link String} containing all of the collected arguments. */ String[] toStringArray() { return list.toArray(String[]::new); } }
Add list of arguments getter
src/modules/de.sormuras.bach/main/java/de/sormuras/bach/Command.java
Add list of arguments getter
<ide><path>rc/modules/de.sormuras.bach/main/java/de/sormuras/bach/Command.java <ide> return name; <ide> } <ide> <add> /** Return the command's arguments. */ <add> public List<String> getList() { <add> return list; <add> } <add> <ide> @Override <ide> public String toString() { <ide> var args = list.isEmpty() ? "<empty>" : "'" + String.join("', '", list) + "'";
Java
epl-1.0
bd8571d5d31c4d342587ea5b401e23c02be9be47
0
kopl/SPLevo,kopl/SPLevo
/******************************************************************************* * Copyright (c) 2014 * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Benjamin Klatt *******************************************************************************/ package org.splevo.ui.wizard.consolidation; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.splevo.project.SPLevoProject; /** * Second page of the New Consolidation Project Wizard in which leading and integration projects * have to be specified. * * @author Radoslav Yankov */ @SuppressWarnings("restriction") public class ProjectsSelectionWizardPage extends WizardPage { private SPLevoProject projectConfiguration; private Text leadingVariantNameField; private Text integrationVariantNameField; private Table leadingProjectsTable; private Table integrationProjectsTable; /** * Constructor preparing the wizard page infrastructure. * * @param projectConfiguration The SPLevo project model. */ public ProjectsSelectionWizardPage(SPLevoProject projectConfiguration) { super("Projects Selection Page"); setTitle("Projects selection"); setDescription("Define the projects to be consolidated."); setPageComplete(false); this.projectConfiguration = projectConfiguration; } @Override public void createControl(Composite parent) { GridLayout layout = new GridLayout(4, false); layout.verticalSpacing = 15; layout.horizontalSpacing = 10; Composite container = new Composite(parent, SWT.NONE); container.setLayout(layout); GridData gridDataSpanCells = new GridData(GridData.FILL_HORIZONTAL); gridDataSpanCells.horizontalSpan = 2; gridDataSpanCells.grabExcessHorizontalSpace = true; createLabel(container, "Leading projects:", gridDataSpanCells); createLabel(container, "Integration projects:", gridDataSpanCells); createLabel(container, "Variant name:", null); leadingVariantNameField = createVariantNameField(container, new CheckPageCompletedListener()); createLabel(container, "Variant name:", null); integrationVariantNameField = createVariantNameField(container, new CheckPageCompletedListener()); leadingProjectsTable = createProjectsTable(container, new CheckPageCompletedListener()); integrationProjectsTable = createProjectsTable(container, new CheckPageCompletedListener()); setControl(container); } /** * Set variant names and the chosen leading and integration projects to the SPLevo project * configuration */ public void setSPLevoProjectConfiguration() { projectConfiguration.setVariantNameLeading(leadingVariantNameField.getText().trim()); projectConfiguration.setVariantNameIntegration(integrationVariantNameField.getText().trim()); for (String chosenLeadingProjectName : getChosenProjectsNames(leadingProjectsTable)) { projectConfiguration.getLeadingProjects().add(chosenLeadingProjectName); } for (String chosenIntegrationProjectName : getChosenProjectsNames(integrationProjectsTable)) { projectConfiguration.getIntegrationProjects().add(chosenIntegrationProjectName); } } private void createLabel(Composite container, String labelText, GridData layoutData) { Label label = new Label(container, SWT.NONE); label.setText(labelText); if (layoutData != null) { label.setLayoutData(layoutData); } } private Text createVariantNameField(Composite container, Listener listener) { Text variantNameField = new Text(container, SWT.BORDER); variantNameField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); variantNameField.addListener(SWT.Modify, listener); return variantNameField; } private Table createProjectsTable(Composite container, Listener listener) { Composite innerContainer = new Composite(container, SWT.NONE); innerContainer.setLayout(new GridLayout(1, false)); GridData twoColumns = new GridData(SWT.FILL, SWT.FILL, true, true); twoColumns.horizontalSpan = 2; innerContainer.setLayoutData(twoColumns); Label label = new Label(innerContainer, SWT.NONE); label.setText("Projects:"); Table projectsTable = createProjectsTableViewer(innerContainer).getTable(); projectsTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); projectsTable.addListener(SWT.Selection, listener); return projectsTable; } /** * Create a table viewer with check box elements. * * @param container * Container in which the table viewer will be created. * @return The created table viewer. */ private TableViewer createProjectsTableViewer(Composite container) { TableViewer projectsTableViewer = new TableViewer(container, SWT.BORDER | SWT.CHECK); projectsTableViewer.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { IProject project = (IProject) element; return project.getName(); } @Override public Image getImage(Object element) { JavaUILabelProvider provider = new JavaUILabelProvider(); return provider.getImage(element); } }); projectsTableViewer.setContentProvider(ArrayContentProvider.getInstance()); projectsTableViewer.setInput(getProjectsFromWorkspace()); return projectsTableViewer; } /** * Get all projects that are currently in the workspace. * * @return List with all projects from the workspace. */ private IProject[] getProjectsFromWorkspace() { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = workspace.getRoot(); IProject[] projects = root.getProjects(); return projects; } /** * @return true if all fields are filled and at least one leading and one integration project is * chosen, otherwise false. */ private boolean isProjectSelectionPageComplete() { boolean isLeadingProjectSelected = isAtLeastOneItemSelected(leadingProjectsTable); boolean isIntergrationProjectSelected = isAtLeastOneItemSelected(integrationProjectsTable); boolean isIntegrationVariantNameFilled = isNotEmpty(integrationVariantNameField); boolean isLeadingVariantNameFilled = isNotEmpty(leadingVariantNameField); return isLeadingVariantNameFilled && isIntegrationVariantNameFilled && isLeadingProjectSelected && isIntergrationProjectSelected; } private boolean isNotEmpty(Text textField) { return textField.getText() != null && textField.getText().trim().length() > 0; } private boolean isAtLeastOneItemSelected(Table table) { boolean leadingProjectSelected = false; for (TableItem item : table.getItems()) { if (item.getChecked()) { leadingProjectSelected = true; break; } } return leadingProjectSelected; } /** * Get the names of the projects the user has chosen. * * @param projectsTable * The table where the projects are placed. * @return List with the names of the chosen projects. */ private List<String> getChosenProjectsNames(Table projectsTable) { TableItem[] allProjects = projectsTable.getItems(); List<String> chosenProjectsNames = new ArrayList<String>(); for (TableItem project : allProjects) { if (project.getChecked()) { chosenProjectsNames.add(project.getText()); } } return chosenProjectsNames; } /** * Listener to react on events and trigger the page to check its completeness. */ private class CheckPageCompletedListener implements Listener { @Override public void handleEvent(Event event) { setPageComplete(isProjectSelectionPageComplete()); } } }
UI/org.splevo.ui.wizard.consolidation/src/org/splevo/ui/wizard/consolidation/ProjectsSelectionWizardPage.java
/******************************************************************************* * Copyright (c) 2014 * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Benjamin Klatt *******************************************************************************/ package org.splevo.ui.wizard.consolidation; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.splevo.project.SPLevoProject; /** * Second page of the New Consolidation Project Wizard in which leading and integration projects * have to be specified. * * @author Radoslav Yankov */ @SuppressWarnings("restriction") public class ProjectsSelectionWizardPage extends WizardPage { private SPLevoProject projectConfiguration; private Text leadingVariantNameField; private Text integrationVariantNameField; private Table leadingProjectsTable; private Table integrationProjectsTable; /** * Constructor preparing the wizard page infrastructure. * * @param projectConfiguration The SPLevo project model. */ public ProjectsSelectionWizardPage(SPLevoProject projectConfiguration) { super("Projects Selection Page"); setTitle("Projects selection"); setDescription("Define the projects to be consolidated."); setPageComplete(false); this.projectConfiguration = projectConfiguration; } @Override public void createControl(Composite parent) { GridLayout layout = new GridLayout(4, false); layout.verticalSpacing = 15; layout.horizontalSpacing = 10; Composite container = new Composite(parent, SWT.NONE); container.setLayout(layout); GridData gridDataSpanCells = new GridData(GridData.FILL_HORIZONTAL); gridDataSpanCells.horizontalSpan = 2; gridDataSpanCells.grabExcessHorizontalSpace = true; createLabel(container, "Leading projects:", gridDataSpanCells); createLabel(container, "Integration projects:", gridDataSpanCells); createLabel(container, "Variant name:", null); leadingVariantNameField = createVariantNameField(container, new CheckPageCompletedListener()); createLabel(container, "Variant name:", null); integrationVariantNameField = createVariantNameField(container, new CheckPageCompletedListener()); leadingProjectsTable = createProjectsTable(container, new CheckPageCompletedListener()); integrationProjectsTable = createProjectsTable(container, new CheckPageCompletedListener()); setControl(container); } @Override public IWizardPage getNextPage() { projectConfiguration.setVariantNameLeading(leadingVariantNameField.getText().trim()); projectConfiguration.setVariantNameIntegration(integrationVariantNameField.getText().trim()); for (String chosenLeadingProjectName : getChosenProjectsNames(leadingProjectsTable)) { projectConfiguration.getLeadingProjects().add(chosenLeadingProjectName); } for (String chosenIntegrationProjectName : getChosenProjectsNames(integrationProjectsTable)) { projectConfiguration.getIntegrationProjects().add(chosenIntegrationProjectName); } return super.getNextPage(); } private void createLabel(Composite container, String labelText, GridData layoutData) { Label label = new Label(container, SWT.NONE); label.setText(labelText); if (layoutData != null) { label.setLayoutData(layoutData); } } private Text createVariantNameField(Composite container, Listener listener) { Text variantNameField = new Text(container, SWT.BORDER); variantNameField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); variantNameField.addListener(SWT.Modify, listener); return variantNameField; } private Table createProjectsTable(Composite container, Listener listener) { Composite innerContainer = new Composite(container, SWT.NONE); innerContainer.setLayout(new GridLayout(1, false)); GridData twoColumns = new GridData(SWT.FILL, SWT.FILL, true, true); twoColumns.horizontalSpan = 2; innerContainer.setLayoutData(twoColumns); Label label = new Label(innerContainer, SWT.NONE); label.setText("Projects:"); Table projectsTable = createProjectsTableViewer(innerContainer).getTable(); projectsTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); projectsTable.addListener(SWT.Selection, listener); return projectsTable; } /** * Create a table viewer with check box elements. * * @param container * Container in which the table viewer will be created. * @return The created table viewer. */ private TableViewer createProjectsTableViewer(Composite container) { TableViewer projectsTableViewer = new TableViewer(container, SWT.BORDER | SWT.CHECK); projectsTableViewer.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { IProject project = (IProject) element; return project.getName(); } @Override public Image getImage(Object element) { JavaUILabelProvider provider = new JavaUILabelProvider(); return provider.getImage(element); } }); projectsTableViewer.setContentProvider(ArrayContentProvider.getInstance()); projectsTableViewer.setInput(getProjectsFromWorkspace()); return projectsTableViewer; } /** * Get all projects that are currently in the workspace. * * @return List with all projects from the workspace. */ private IProject[] getProjectsFromWorkspace() { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = workspace.getRoot(); IProject[] projects = root.getProjects(); return projects; } /** * @return true if all fields are filled and at least one leading and one integration project is * chosen, otherwise false. */ private boolean isProjectSelectionPageComplete() { boolean isLeadingProjectSelected = isAtLeastOneItemSelected(leadingProjectsTable); boolean isIntergrationProjectSelected = isAtLeastOneItemSelected(integrationProjectsTable); boolean isIntegrationVariantNameFilled = isNotEmpty(integrationVariantNameField); boolean isLeadingVariantNameFilled = isNotEmpty(leadingVariantNameField); return isLeadingVariantNameFilled && isIntegrationVariantNameFilled && isLeadingProjectSelected && isIntergrationProjectSelected; } private boolean isNotEmpty(Text textField) { return textField.getText() != null && textField.getText().trim().length() > 0; } private boolean isAtLeastOneItemSelected(Table table) { boolean leadingProjectSelected = false; for (TableItem item : table.getItems()) { if (item.getChecked()) { leadingProjectSelected = true; break; } } return leadingProjectSelected; } /** * Get the names of the projects the user has chosen. * * @param projectsTable * The table where the projects are placed. * @return List with the names of the chosen projects. */ private List<String> getChosenProjectsNames(Table projectsTable) { TableItem[] allProjects = projectsTable.getItems(); List<String> chosenProjectsNames = new ArrayList<String>(); for (TableItem project : allProjects) { if (project.getChecked()) { chosenProjectsNames.add(project.getText()); } } return chosenProjectsNames; } /** * Listener to react on events and trigger the page to check its completeness. */ private class CheckPageCompletedListener implements Listener { @Override public void handleEvent(Event event) { setPageComplete(isProjectSelectionPageComplete()); } } }
SPLEVO-308 Consolidation Wizard: Package Scope Definition Page: defined setSPLevoProjectConfiguration method
UI/org.splevo.ui.wizard.consolidation/src/org/splevo/ui/wizard/consolidation/ProjectsSelectionWizardPage.java
SPLEVO-308 Consolidation Wizard: Package Scope Definition Page: defined setSPLevoProjectConfiguration method
<ide><path>I/org.splevo.ui.wizard.consolidation/src/org/splevo/ui/wizard/consolidation/ProjectsSelectionWizardPage.java <ide> import org.eclipse.jface.viewers.ArrayContentProvider; <ide> import org.eclipse.jface.viewers.ColumnLabelProvider; <ide> import org.eclipse.jface.viewers.TableViewer; <del>import org.eclipse.jface.wizard.IWizardPage; <ide> import org.eclipse.jface.wizard.WizardPage; <ide> import org.eclipse.swt.SWT; <ide> import org.eclipse.swt.graphics.Image; <ide> setControl(container); <ide> } <ide> <del> @Override <del> public IWizardPage getNextPage() { <add> /** <add> * Set variant names and the chosen leading and integration projects to the SPLevo project <add> * configuration <add> */ <add> public void setSPLevoProjectConfiguration() { <ide> projectConfiguration.setVariantNameLeading(leadingVariantNameField.getText().trim()); <ide> projectConfiguration.setVariantNameIntegration(integrationVariantNameField.getText().trim()); <ide> <ide> <ide> for (String chosenIntegrationProjectName : getChosenProjectsNames(integrationProjectsTable)) { <ide> projectConfiguration.getIntegrationProjects().add(chosenIntegrationProjectName); <del> } <del> <del> return super.getNextPage(); <add> } <ide> } <ide> <ide> private void createLabel(Composite container, String labelText, GridData layoutData) {
Java
mit
13830fd507aee38121f8f4ced954e171695ee5fc
0
bensku/VoxelSniper,LinkBR/VoxelSniper,josiahseaman/VoxelSniper
src/main/java/com/thevoxelbox/voxelsniper/brush/Mixer.java
package com.thevoxelbox.voxelsniper.brush; import java.util.Random; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.entity.Player; import com.thevoxelbox.voxelsniper.vMessage; public class Mixer extends Brush{ private int dx = 5, dy = 5, dz = 5; // Dimensions to mix in private Random rand = new Random(); public Mixer() { name = "mixer"; } @Override public void info(vMessage vm) { vm.brushName(name); vm.voxel(); } @Override protected void arrow(com.thevoxelbox.voxelsniper.vData v) { for (int x = 0; x < dx; x++) { for (int y = 0; y < dy; y++) { for (int z = 0; z < dz; z++) { Location l = new Location(tb.getWorld(), tb.getX() + x - (Integer) (dx / 2), tb.getY() + y - (Integer) (dy - 1), tb.getZ() + z - (Integer) (dz / 2)); int random = rand.nextInt(10); if (random <= 3 && l.getWorld().getBlockAt(l).getTypeId() != 0) l.getWorld().getBlockAt(l).setTypeId(v.voxelId); } } } } @Override protected void powder(com.thevoxelbox.voxelsniper.vData v) { arrow(v); } @Override public void parameters(String[] par, com.thevoxelbox.voxelsniper.vData v) { if (par[1].equalsIgnoreCase("info")) { v.sendMessage(ChatColor.GOLD + "Mixer Brush Parameters:"); v.sendMessage(ChatColor.AQUA + "/b mixer dim [x] [y] [z] -- set dimension size by x, y, and z."); } else if (par[1].equalsIgnoreCase("dim")) { try { dx = Integer.parseInt(par[2]); dy = Integer.parseInt(par[3]); dz = Integer.parseInt(par[4]); v.sendMessage(ChatColor.GREEN + "Dimensions set."); if (dx >= 100 || dy >= 100 || dz >= 100) v.sendMessage(ChatColor.RED + "Warning: One of the dimensions is very large."); } catch (Exception e) { v.sendMessage(ChatColor.RED + "An error occurred. Make sure the parameters are correct."); } } else { v.sendMessage(ChatColor.RED + "Invalid brush parameters! use the info parameter to display parameter info."); } } }
Removed mixer file.
src/main/java/com/thevoxelbox/voxelsniper/brush/Mixer.java
Removed mixer file.
<ide><path>rc/main/java/com/thevoxelbox/voxelsniper/brush/Mixer.java <del>package com.thevoxelbox.voxelsniper.brush; <del> <del>import java.util.Random; <del> <del>import org.bukkit.ChatColor; <del>import org.bukkit.Location; <del>import org.bukkit.entity.Player; <del> <del>import com.thevoxelbox.voxelsniper.vMessage; <del> <del>public class Mixer extends Brush{ <del> <del> private int dx = 5, dy = 5, dz = 5; // Dimensions to mix in <del> private Random rand = new Random(); <del> <del> public Mixer() { <del> name = "mixer"; <del> } <del> <del> @Override <del> public void info(vMessage vm) { <del> vm.brushName(name); <del> vm.voxel(); <del> } <del> <del> @Override <del> protected void arrow(com.thevoxelbox.voxelsniper.vData v) { <del> for (int x = 0; x < dx; x++) { <del> for (int y = 0; y < dy; y++) { <del> for (int z = 0; z < dz; z++) { <del> Location l = new Location(tb.getWorld(), tb.getX() + x - (Integer) (dx / 2), tb.getY() + y - (Integer) (dy - 1), tb.getZ() + z - (Integer) (dz / 2)); <del> <del> int random = rand.nextInt(10); <del> if (random <= 3 && l.getWorld().getBlockAt(l).getTypeId() != 0) <del> l.getWorld().getBlockAt(l).setTypeId(v.voxelId); <del> } <del> } <del> } <del> } <del> <del> @Override <del> protected void powder(com.thevoxelbox.voxelsniper.vData v) { <del> arrow(v); <del> } <del> <del> @Override <del> public void parameters(String[] par, com.thevoxelbox.voxelsniper.vData v) { <del> if (par[1].equalsIgnoreCase("info")) { <del> v.sendMessage(ChatColor.GOLD + "Mixer Brush Parameters:"); <del> v.sendMessage(ChatColor.AQUA + "/b mixer dim [x] [y] [z] -- set dimension size by x, y, and z."); <del> } else if (par[1].equalsIgnoreCase("dim")) { <del> try { <del> dx = Integer.parseInt(par[2]); <del> dy = Integer.parseInt(par[3]); <del> dz = Integer.parseInt(par[4]); <del> <del> v.sendMessage(ChatColor.GREEN + "Dimensions set."); <del> if (dx >= 100 || dy >= 100 || dz >= 100) <del> v.sendMessage(ChatColor.RED + "Warning: One of the dimensions is very large."); <del> <del> } catch (Exception e) { <del> v.sendMessage(ChatColor.RED + "An error occurred. Make sure the parameters are correct."); <del> } <del> } else { <del> v.sendMessage(ChatColor.RED + "Invalid brush parameters! use the info parameter to display parameter info."); <del> } <del> } <del> <del>}
Java
apache-2.0
b2f25bc87cf87d839d488d96c22cf3bcc2ec1cf6
0
kalaspuffar/pdfbox,apache/pdfbox,kalaspuffar/pdfbox,apache/pdfbox
/* * 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 org.apache.pdfbox.debugger; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.FileDialog; import java.awt.Toolkit; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowEvent; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.URL; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JScrollPane; import javax.swing.KeyStroke; import javax.swing.TransferHandler; import javax.swing.UIManager; import javax.swing.border.BevelBorder; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.filechooser.FileFilter; import javax.swing.tree.TreePath; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSBoolean; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSFloat; import org.apache.pdfbox.cos.COSInteger; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSNull; import org.apache.pdfbox.cos.COSObject; import org.apache.pdfbox.cos.COSStream; import org.apache.pdfbox.cos.COSString; import org.apache.pdfbox.debugger.colorpane.CSArrayBased; import org.apache.pdfbox.debugger.colorpane.CSDeviceN; import org.apache.pdfbox.debugger.colorpane.CSIndexed; import org.apache.pdfbox.debugger.colorpane.CSSeparation; import org.apache.pdfbox.debugger.flagbitspane.FlagBitsPane; import org.apache.pdfbox.debugger.fontencodingpane.FontEncodingPaneController; import org.apache.pdfbox.debugger.pagepane.PagePane; import org.apache.pdfbox.debugger.streampane.StreamPane; import org.apache.pdfbox.debugger.stringpane.StringPane; import org.apache.pdfbox.debugger.treestatus.TreeStatus; import org.apache.pdfbox.debugger.treestatus.TreeStatusPane; import org.apache.pdfbox.debugger.ui.ArrayEntry; import org.apache.pdfbox.debugger.ui.DocumentEntry; import org.apache.pdfbox.debugger.ui.ErrorDialog; import org.apache.pdfbox.debugger.ui.ExtensionFileFilter; import org.apache.pdfbox.debugger.ui.FileOpenSaveDialog; import org.apache.pdfbox.debugger.ui.LogDialog; import org.apache.pdfbox.debugger.ui.MapEntry; import org.apache.pdfbox.debugger.ui.OSXAdapter; import org.apache.pdfbox.debugger.ui.PDFTreeCellRenderer; import org.apache.pdfbox.debugger.ui.PDFTreeModel; import org.apache.pdfbox.debugger.ui.PageEntry; import org.apache.pdfbox.debugger.ui.ReaderBottomPanel; import org.apache.pdfbox.debugger.ui.RecentFiles; import org.apache.pdfbox.debugger.ui.RotationMenu; import org.apache.pdfbox.debugger.ui.Tree; import org.apache.pdfbox.debugger.ui.ZoomMenu; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.common.PDPageLabels; import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException; import org.apache.pdfbox.printing.PDFPageable; /** * PDF Debugger. * * @author wurtz * @author Ben Litchfield * @author Khyrul Bashar */ public class PDFDebugger extends JFrame { private static final Set<COSName> SPECIALCOLORSPACES = new HashSet<COSName>(Arrays.asList(COSName.INDEXED, COSName.SEPARATION, COSName.DEVICEN)); private static final Set<COSName> OTHERCOLORSPACES = new HashSet<COSName>(Arrays.asList(COSName.ICCBASED, COSName.PATTERN, COSName.CALGRAY, COSName.CALRGB, COSName.LAB)); private static final String PASSWORD = "-password"; private static final String VIEW_STRUCTURE = "-viewstructure"; private static final int SHORCUT_KEY_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); private static final String OS_NAME = System.getProperty("os.name").toLowerCase(); private static final boolean IS_MAC_OS = OS_NAME.startsWith("mac os x"); private final JPanel documentPanel = new JPanel(); private TreeStatusPane statusPane; private RecentFiles recentFiles; private boolean isPageMode; private PDDocument document; private String currentFilePath; private JScrollPane jScrollPane1; private JScrollPane jScrollPane2; private javax.swing.JSplitPane jSplitPane1; private javax.swing.JTextPane jTextPane1; private ReaderBottomPanel statusBar; private Tree tree; // file menu private JMenuItem saveAsMenuItem; private JMenuItem saveMenuItem; private JMenu recentFilesMenu; private JMenuItem printMenuItem; private JMenuItem reopenMenuItem; // edit > find menu private JMenu findMenu; private JMenuItem findMenuItem; private JMenuItem findNextMenuItem; private JMenuItem findPreviousMenuItem; // view menu private JMenuItem viewModeItem; public static JCheckBoxMenuItem showTextStripper; public static JCheckBoxMenuItem showTextStripperBeads; public static JCheckBoxMenuItem showFontBBox; public static JCheckBoxMenuItem showGlyphBounds; // configuration public static Properties configuration = new Properties(); /** * Constructor. */ public PDFDebugger() { this(false); } /** * Constructor. */ public PDFDebugger(boolean viewPages) { isPageMode = viewPages; loadConfiguration(); initComponents(); // use our custom logger LogDialog.init(this, statusBar.getLogLabel()); System.setProperty("org.apache.commons.logging.Log", "org.apache.pdfbox.debugger.ui.DebugLog"); } /** * Entry point. * * @param args the command line arguments * @throws Exception If anything goes wrong. */ public static void main(String[] args) throws Exception { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); if (System.getProperty("apple.laf.useScreenMenuBar") == null) { System.setProperty("apple.laf.useScreenMenuBar", "true"); } // handle uncaught exceptions Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable throwable) { new ErrorDialog(throwable).setVisible(true); } }); // open file, if any String filename = null; String password = ""; boolean viewPages = true; for( int i = 0; i < args.length; i++ ) { if( args[i].equals( PASSWORD ) ) { i++; if( i >= args.length ) { usage(); } password = args[i]; } else if( args[i].equals(VIEW_STRUCTURE) ) { viewPages = false; } else { filename = args[i]; } } final PDFDebugger viewer = new PDFDebugger(viewPages); if (filename != null) { File file = new File(filename); if (file.exists()) { viewer.readPDFFile(filename, password); } } viewer.setVisible(true); } /** * This will print out a message telling how to use this utility. */ private static void usage() { String message = "Usage: java -jar pdfbox-app-x.y.z.jar PDFDebugger [options] <inputfile>\n" + "\nOptions:\n" + " -password <password> : Password to decrypt the document\n" + " -viewstructure : activate structure mode on startup\n" + " <inputfile> : The PDF document to be loaded\n"; System.err.println(message); System.exit(1); } /** * Loads the local configuration file, if any. */ private void loadConfiguration() { File file = new File("config.properties"); if (file.exists()) { try { InputStream is = new FileInputStream(file); configuration.load(is); is.close(); } catch(IOException e) { throw new RuntimeException(e); } } } /** * This method is called from within the constructor to initialize the form. */ private void initComponents() { jSplitPane1 = new javax.swing.JSplitPane(); jScrollPane1 = new JScrollPane(); tree = new Tree(this); jScrollPane2 = new JScrollPane(); jTextPane1 = new javax.swing.JTextPane(); tree.setCellRenderer(new PDFTreeCellRenderer()); tree.setModel(null); setTitle("Apache PDFBox Debugger"); addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowOpened(WindowEvent windowEvent) { tree.requestFocusInWindow(); super.windowOpened(windowEvent); } @Override public void windowClosing(WindowEvent evt) { exitForm(evt); } }); jScrollPane1.setBorder(new BevelBorder(BevelBorder.RAISED)); jScrollPane1.setPreferredSize(new Dimension(350, 500)); tree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent evt) { jTree1ValueChanged(evt); } }); jScrollPane1.setViewportView(tree); jSplitPane1.setRightComponent(jScrollPane2); jSplitPane1.setDividerSize(3); jScrollPane2.setPreferredSize(new Dimension(300, 500)); jScrollPane2.setViewportView(jTextPane1); jSplitPane1.setLeftComponent(jScrollPane1); JScrollPane documentScroller = new JScrollPane(); documentScroller.setViewportView(documentPanel); statusPane = new TreeStatusPane(tree); statusPane.getPanel().setBorder(new BevelBorder(BevelBorder.RAISED)); statusPane.getPanel().setPreferredSize(new Dimension(300, 25)); getContentPane().add(statusPane.getPanel(), BorderLayout.PAGE_START); getContentPane().add(jSplitPane1, BorderLayout.CENTER); statusBar = new ReaderBottomPanel(); getContentPane().add(statusBar, BorderLayout.SOUTH); // create menus JMenuBar menuBar = new JMenuBar(); menuBar.add(createFileMenu()); menuBar.add(createEditMenu()); menuBar.add(createViewMenu()); setJMenuBar(menuBar); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int width = 1000; int height = 970; setBounds((screenSize.width - width) / 2, (screenSize.height - height) / 2, width, height); // drag and drop to open files setTransferHandler(new TransferHandler() { @Override public boolean canImport(TransferSupport transferSupport) { return transferSupport.isDataFlavorSupported(DataFlavor.javaFileListFlavor); } @Override @SuppressWarnings("unchecked") public boolean importData(TransferSupport transferSupport) { try { Transferable transferable = transferSupport.getTransferable(); List<File> files = (List<File>) transferable.getTransferData( DataFlavor.javaFileListFlavor); readPDFFile(files.get(0), ""); return true; } catch (IOException e) { new ErrorDialog(e).setVisible(true); return true; } catch (UnsupportedFlavorException e) { throw new RuntimeException(e); } } }); // Mac OS X file open/quit handler if (IS_MAC_OS) { try { Method osxOpenFiles = getClass().getDeclaredMethod("osxOpenFiles", String.class); osxOpenFiles.setAccessible(true); OSXAdapter.setFileHandler(this, osxOpenFiles); Method osxQuit = getClass().getDeclaredMethod("osxQuit"); osxQuit.setAccessible(true); OSXAdapter.setQuitHandler(this, osxQuit); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } } private JMenu createFileMenu() { JMenuItem openMenuItem = new JMenuItem("Open..."); openMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, SHORCUT_KEY_MASK)); openMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { openMenuItemActionPerformed(evt); } }); JMenu fileMenu = new JMenu("File"); fileMenu.add(openMenuItem); fileMenu.setMnemonic('F'); JMenuItem openUrlMenuItem = new JMenuItem("Open URL..."); openUrlMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, SHORCUT_KEY_MASK)); openUrlMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { String urlString = JOptionPane.showInputDialog("Enter an URL"); if (urlString == null || urlString.isEmpty()) { return; } try { readPDFurl(urlString, ""); } catch (IOException e) { throw new RuntimeException(e); } } }); fileMenu.add(openUrlMenuItem); reopenMenuItem = new JMenuItem("Reopen"); reopenMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, SHORCUT_KEY_MASK)); reopenMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { try { if (currentFilePath.startsWith("http")) { readPDFurl(currentFilePath, ""); } else { readPDFFile(currentFilePath, ""); } } catch (IOException e) { new ErrorDialog(e).setVisible(true); } } }); reopenMenuItem.setEnabled(false); fileMenu.add(reopenMenuItem); try { recentFiles = new RecentFiles(this.getClass(), 5); } catch (Exception e) { throw new RuntimeException(e); } recentFilesMenu = new JMenu("Open Recent"); recentFilesMenu.setEnabled(false); addRecentFileItems(); fileMenu.add(recentFilesMenu); printMenuItem = new JMenuItem("Print"); printMenuItem.setEnabled(false); printMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { printMenuItemActionPerformed(evt); } }); if (!IS_MAC_OS) { fileMenu.addSeparator(); fileMenu.add(printMenuItem); } JMenuItem exitMenuItem = new JMenuItem("Exit"); exitMenuItem.setAccelerator(KeyStroke.getKeyStroke("alt F4")); exitMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { exitMenuItemActionPerformed(evt); } }); if (!IS_MAC_OS) { fileMenu.addSeparator(); fileMenu.add(exitMenuItem); } return fileMenu; } private JMenu createEditMenu() { JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic('E'); JMenuItem cutMenuItem = new JMenuItem("Cut"); cutMenuItem.setEnabled(false); editMenu.add(cutMenuItem); JMenuItem copyMenuItem = new JMenuItem("Copy"); copyMenuItem.setEnabled(false); editMenu.add(copyMenuItem); JMenuItem pasteMenuItem = new JMenuItem("Paste"); pasteMenuItem.setEnabled(false); editMenu.add(pasteMenuItem); JMenuItem deleteMenuItem = new JMenuItem("Delete"); deleteMenuItem.setEnabled(false); editMenu.add(deleteMenuItem); editMenu.addSeparator(); editMenu.add(createFindMenu()); return editMenu; } private JMenu createViewMenu() { JMenu viewMenu = new JMenu("View"); viewMenu.setMnemonic('V'); if (isPageMode) { viewModeItem = new JMenuItem("Show Internal Structure"); } else { viewModeItem = new JMenuItem("Show Pages"); } viewModeItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if (isPageMode) { viewModeItem.setText("Show Pages"); isPageMode = false; } else { viewModeItem.setText("Show Internal Structure"); isPageMode = true; } if (document != null) { initTree(); } } }); viewMenu.add(viewModeItem); ZoomMenu zoomMenu = ZoomMenu.getInstance(); zoomMenu.setEnableMenu(false); viewMenu.add(zoomMenu.getMenu()); RotationMenu rotationMenu = RotationMenu.getInstance(); rotationMenu.setEnableMenu(false); viewMenu.add(rotationMenu.getMenu()); viewMenu.addSeparator(); showTextStripper = new JCheckBoxMenuItem("Show TextStripper TextPositions"); showTextStripper.setEnabled(false); viewMenu.add(showTextStripper); showTextStripperBeads = new JCheckBoxMenuItem("Show TextStripper Beads"); showTextStripperBeads.setEnabled(false); viewMenu.add(showTextStripperBeads); showFontBBox = new JCheckBoxMenuItem("Show Approximate Text Bounds"); showFontBBox.setEnabled(false); viewMenu.add(showFontBBox); showGlyphBounds = new JCheckBoxMenuItem("Show Glyph Bounds"); showGlyphBounds.setEnabled(false); viewMenu.add(showGlyphBounds); return viewMenu; } private JMenu createFindMenu() { findMenu = new JMenu("Find"); findMenu.setEnabled(false); findMenuItem = new JMenuItem("Find..."); findMenuItem.setActionCommand("find"); findMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, SHORCUT_KEY_MASK)); findNextMenuItem = new JMenuItem("Find Next"); if (IS_MAC_OS) { findNextMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, SHORCUT_KEY_MASK)); } else { findNextMenuItem.setAccelerator(KeyStroke.getKeyStroke("F3")); } findPreviousMenuItem = new JMenuItem("Find Previous"); if (IS_MAC_OS) { findPreviousMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_G, SHORCUT_KEY_MASK | InputEvent.SHIFT_DOWN_MASK)); } else { findPreviousMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_F3, InputEvent.SHIFT_DOWN_MASK)); } findMenu.add(findMenuItem); findMenu.add(findNextMenuItem); findMenu.add(findPreviousMenuItem); return findMenu; } /** * Returns the File menu. */ public JMenu getFindMenu() { return findMenu; } /** * Returns the Edit &gt; Find &gt; Find menu item. */ public JMenuItem getFindMenuItem() { return findMenuItem; } /** * Returns the Edit &gt; Find &gt; Find Next menu item. */ public JMenuItem getFindNextMenuItem() { return findNextMenuItem; } /** * Returns the Edit &gt; Find &gt; Find Previous menu item. */ public JMenuItem getFindPreviousMenuItem() { return findPreviousMenuItem; } /** * This method is called via reflection on Mac OS X. */ private void osxOpenFiles(String filename) { try { readPDFFile(filename, ""); } catch (IOException e) { throw new RuntimeException(e); } } /** * This method is called via reflection on Mac OS X. */ private void osxQuit() { exitMenuItemActionPerformed(null); } private void openMenuItemActionPerformed(ActionEvent evt) { try { if (IS_MAC_OS) { FileDialog openDialog = new FileDialog(this, "Open"); openDialog.setFilenameFilter(new FilenameFilter() { @Override public boolean accept(File file, String s) { return file.getName().toLowerCase().endsWith(".pdf"); } }); openDialog.setVisible(true); if (openDialog.getFile() != null) { readPDFFile(openDialog.getFile(), ""); } } else { String[] extensions = new String[] {"pdf", "PDF"}; FileFilter pdfFilter = new ExtensionFileFilter(extensions, "PDF Files (*.pdf)"); FileOpenSaveDialog openDialog = new FileOpenSaveDialog(this, pdfFilter); File file = openDialog.openFile(); if (file != null) { readPDFFile(file, ""); } } } catch (IOException e) { throw new RuntimeException(e); } } private void jTree1ValueChanged(TreeSelectionEvent evt) { TreePath path = tree.getSelectionPath(); if (path != null) { try { Object selectedNode = path.getLastPathComponent(); statusBar.getStatusLabel().setText(""); if (isPage(selectedNode)) { showPage(selectedNode); return; } if (isSpecialColorSpace(selectedNode) || isOtherColorSpace(selectedNode)) { showColorPane(selectedNode); return; } if (path.getParentPath() != null && isFlagNode(selectedNode, path.getParentPath().getLastPathComponent())) { Object parentNode = path.getParentPath().getLastPathComponent(); showFlagPane(parentNode, selectedNode); return; } if (isStream(selectedNode)) { showStream((COSStream) getUnderneathObject(selectedNode), path); return; } if (isFont(selectedNode)) { showFont(selectedNode, path); return; } if (isString(selectedNode)) { showString(selectedNode); return; } if (jSplitPane1.getRightComponent() == null || !jSplitPane1.getRightComponent().equals(jScrollPane2)) { replaceRightComponent(jScrollPane2); } jTextPane1.setText(convertToString(selectedNode)); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } } private boolean isSpecialColorSpace(Object selectedNode) { selectedNode = getUnderneathObject(selectedNode); if (selectedNode instanceof COSArray && ((COSArray) selectedNode).size() > 0) { COSBase arrayEntry = ((COSArray)selectedNode).get(0); if (arrayEntry instanceof COSName) { COSName name = (COSName) arrayEntry; return SPECIALCOLORSPACES.contains(name); } } return false; } private boolean isOtherColorSpace(Object selectedNode) { selectedNode = getUnderneathObject(selectedNode); if (selectedNode instanceof COSArray && ((COSArray) selectedNode).size() > 0) { COSBase arrayEntry = ((COSArray)selectedNode).get(0); if (arrayEntry instanceof COSName) { COSName name = (COSName) arrayEntry; return OTHERCOLORSPACES.contains(name); } } return false; } private boolean isPage(Object selectedNode) { selectedNode = getUnderneathObject(selectedNode); if (selectedNode instanceof COSDictionary) { COSDictionary dict = (COSDictionary) selectedNode; COSBase typeItem = dict.getItem(COSName.TYPE); if (COSName.PAGE.equals(typeItem)) { return true; } } else if (selectedNode instanceof PageEntry) { return true; } return false; } private boolean isFlagNode(Object selectedNode, Object parentNode) { if (selectedNode instanceof MapEntry) { Object key = ((MapEntry) selectedNode).getKey(); return (COSName.FLAGS.equals(key) && isFontDescriptor(parentNode)) || (COSName.F.equals(key) && isAnnot(parentNode)) || COSName.FF.equals(key) || COSName.PANOSE.equals(key) || COSName.SIG_FLAGS.equals(key) || (COSName.P.equals(key) && isEncrypt(parentNode)); } return false; } private boolean isEncrypt(Object obj) { if (obj instanceof MapEntry) { MapEntry entry = (MapEntry) obj; return COSName.ENCRYPT.equals(entry.getKey()) && entry.getValue() instanceof COSDictionary; } return false; } private boolean isFontDescriptor(Object obj) { Object underneathObject = getUnderneathObject(obj); return underneathObject instanceof COSDictionary && ((COSDictionary) underneathObject).containsKey(COSName.TYPE) && ((COSDictionary) underneathObject).getCOSName(COSName.TYPE).equals(COSName.FONT_DESC); } private boolean isAnnot(Object obj) { Object underneathObject = getUnderneathObject(obj); return underneathObject instanceof COSDictionary && ((COSDictionary) underneathObject).containsKey(COSName.TYPE) && ((COSDictionary) underneathObject).getCOSName(COSName.TYPE).equals(COSName.ANNOT); } private boolean isStream(Object selectedNode) { return getUnderneathObject(selectedNode) instanceof COSStream; } private boolean isString(Object selectedNode) { return getUnderneathObject(selectedNode) instanceof COSString; } private boolean isFont(Object selectedNode) { selectedNode = getUnderneathObject(selectedNode); if (selectedNode instanceof COSDictionary) { COSDictionary dic = (COSDictionary)selectedNode; return dic.containsKey(COSName.TYPE) && dic.getCOSName(COSName.TYPE).equals(COSName.FONT) && !isCIDFont(dic); } return false; } private boolean isCIDFont(COSDictionary dic) { return dic.containsKey(COSName.SUBTYPE) && (dic.getCOSName(COSName.SUBTYPE).equals(COSName.CID_FONT_TYPE0) || dic.getCOSName(COSName.SUBTYPE).equals(COSName.CID_FONT_TYPE2)); } /** * Show a Panel describing color spaces in more detail and interactive way. * @param csNode the special color space containing node. */ private void showColorPane(Object csNode) { csNode = getUnderneathObject(csNode); if (csNode instanceof COSArray && ((COSArray) csNode).size() > 0) { COSArray array = (COSArray)csNode; COSBase arrayEntry = array.get(0); if (arrayEntry instanceof COSName) { COSName csName = (COSName) arrayEntry; if (csName.equals(COSName.SEPARATION)) { replaceRightComponent(new CSSeparation(array).getPanel()); } else if (csName.equals(COSName.DEVICEN)) { replaceRightComponent(new CSDeviceN(array).getPanel()); } else if (csName.equals(COSName.INDEXED)) { replaceRightComponent(new CSIndexed(array).getPanel()); } else if (OTHERCOLORSPACES.contains(csName)) { replaceRightComponent(new CSArrayBased(array).getPanel()); } } } } private void showPage(Object selectedNode) { selectedNode = getUnderneathObject(selectedNode); COSDictionary page; if (selectedNode instanceof COSDictionary) { page = (COSDictionary) selectedNode; } else { page = ((PageEntry) selectedNode).getDict(); } COSBase typeItem = page.getItem(COSName.TYPE); if (COSName.PAGE.equals(typeItem)) { PagePane pagePane = new PagePane(document, page, statusBar.getStatusLabel()); replaceRightComponent(new JScrollPane(pagePane.getPanel())); } } private void showFlagPane(Object parentNode, Object selectedNode) { parentNode = getUnderneathObject(parentNode); if (parentNode instanceof COSDictionary) { selectedNode = ((MapEntry)selectedNode).getKey(); selectedNode = getUnderneathObject(selectedNode); FlagBitsPane flagBitsPane = new FlagBitsPane((COSDictionary) parentNode, (COSName) selectedNode); replaceRightComponent(flagBitsPane.getPane()); } } private void showStream(COSStream stream, TreePath path) throws IOException { boolean isContentStream = false; boolean isThumb = false; COSName key = getNodeKey(path.getLastPathComponent()); COSName parentKey = getNodeKey(path.getParentPath().getLastPathComponent()); COSDictionary resourcesDic = null; if (COSName.CONTENTS.equals(key)) { Object pageObj = path.getParentPath().getLastPathComponent(); COSDictionary page = (COSDictionary) getUnderneathObject(pageObj); resourcesDic = (COSDictionary) page.getDictionaryObject(COSName.RESOURCES); isContentStream = true; } else if (COSName.CONTENTS.equals(parentKey) || COSName.CHAR_PROCS.equals(parentKey)) { Object pageObj = path.getParentPath().getParentPath().getLastPathComponent(); COSDictionary page = (COSDictionary) getUnderneathObject(pageObj); resourcesDic = (COSDictionary) page.getDictionaryObject(COSName.RESOURCES); isContentStream = true; } else if (COSName.FORM.equals(stream.getCOSName(COSName.SUBTYPE)) || COSName.PATTERN.equals(stream.getCOSName(COSName.TYPE)) || stream.getInt(COSName.PATTERN_TYPE) == 1) { if (stream.containsKey(COSName.RESOURCES)) { resourcesDic = (COSDictionary) stream.getDictionaryObject(COSName.RESOURCES); } isContentStream = true; } else if (COSName.THUMB.equals(key)) { resourcesDic = null; isThumb = true; } else if (COSName.IMAGE.equals((stream).getCOSName(COSName.SUBTYPE))) { // not to be used for /Thumb, even if it contains /Subtype /Image Object resourcesObj = path.getParentPath().getParentPath().getLastPathComponent(); resourcesDic = (COSDictionary) getUnderneathObject(resourcesObj); } StreamPane streamPane = new StreamPane(stream, isContentStream, isThumb, resourcesDic); replaceRightComponent(streamPane.getPanel()); } private void showFont(Object selectedNode, TreePath path) { COSName fontName = getNodeKey(selectedNode); COSDictionary resourceDic = (COSDictionary) getUnderneathObject(path.getParentPath().getParentPath().getLastPathComponent()); FontEncodingPaneController fontEncodingPaneController = new FontEncodingPaneController(fontName, resourceDic); JPanel pane = fontEncodingPaneController.getPane(); if (pane == null) { // unsupported font type replaceRightComponent(jScrollPane2); return; } replaceRightComponent(pane); } // replace the right component while keeping divider position private void replaceRightComponent(Component pane) { int div = jSplitPane1.getDividerLocation(); jSplitPane1.setRightComponent(pane); jSplitPane1.setDividerLocation(div); } private void showString(Object selectedNode) { COSString string = (COSString)getUnderneathObject(selectedNode); replaceRightComponent(new StringPane(string).getPane()); } private COSName getNodeKey(Object selectedNode) { if (selectedNode instanceof MapEntry) { return ((MapEntry) selectedNode).getKey(); } return null; } private Object getUnderneathObject(Object selectedNode) { if (selectedNode instanceof MapEntry) { selectedNode = ((MapEntry) selectedNode).getValue(); } else if (selectedNode instanceof ArrayEntry) { selectedNode = ((ArrayEntry) selectedNode).getValue(); } else if (selectedNode instanceof PageEntry) { selectedNode = ((PageEntry) selectedNode).getDict(); } if (selectedNode instanceof COSObject) { selectedNode = ((COSObject) selectedNode).getObject(); } return selectedNode; } private String convertToString( Object selectedNode ) { String data = null; if(selectedNode instanceof COSBoolean) { data = "" + ((COSBoolean)selectedNode).getValue(); } else if( selectedNode instanceof COSFloat ) { data = "" + ((COSFloat)selectedNode).floatValue(); } else if( selectedNode instanceof COSNull ) { data = "null"; } else if( selectedNode instanceof COSInteger ) { data = "" + ((COSInteger)selectedNode).intValue(); } else if( selectedNode instanceof COSName ) { data = "" + ((COSName)selectedNode).getName(); } else if( selectedNode instanceof COSString ) { String text = ((COSString) selectedNode).getString(); // display unprintable strings as hex for (char c : text.toCharArray()) { if (Character.isISOControl(c)) { text = "<" + ((COSString) selectedNode).toHexString() + ">"; break; } } data = "" + text; } else if( selectedNode instanceof COSStream ) { try { COSStream stream = (COSStream)selectedNode; InputStream ioStream = stream.createInputStream(); ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int amountRead; while( (amountRead = ioStream.read( buffer, 0, buffer.length ) ) != -1 ) { byteArray.write( buffer, 0, amountRead ); } data = byteArray.toString(); } catch( IOException e ) { throw new RuntimeException(e); } } else if( selectedNode instanceof MapEntry ) { data = convertToString( ((MapEntry)selectedNode).getValue() ); } else if( selectedNode instanceof ArrayEntry ) { data = convertToString( ((ArrayEntry)selectedNode).getValue() ); } return data; } private void exitMenuItemActionPerformed(ActionEvent evt) { if( document != null ) { try { document.close(); if (!currentFilePath.startsWith("http")) { recentFiles.addFile(currentFilePath); } recentFiles.close(); } catch( IOException e ) { throw new RuntimeException(e); } } System.exit(0); } private void printMenuItemActionPerformed(ActionEvent evt) { if( document != null ) { try { PrinterJob job = PrinterJob.getPrinterJob(); job.setPageable(new PDFPageable(document)); if (job.printDialog()) { job.print(); } } catch (PrinterException e) { throw new RuntimeException(e); } } } /** * Exit the Application. */ private void exitForm(WindowEvent evt) { if( document != null ) { try { document.close(); if (!currentFilePath.startsWith("http")) { recentFiles.addFile(currentFilePath); } recentFiles.close(); } catch( IOException e ) { throw new RuntimeException(e); } } System.exit(0); } private void readPDFFile(String filePath, String password) throws IOException { File file = new File(filePath); readPDFFile(file, password); } private void readPDFFile(File file, String password) throws IOException { if( document != null ) { document.close(); if (!currentFilePath.startsWith("http")) { recentFiles.addFile(currentFilePath); } } currentFilePath = file.getPath(); recentFiles.removeFile(file.getPath()); LogDialog.instance().clear(); parseDocument( file, password ); initTree(); if (IS_MAC_OS) { setTitle(file.getName()); getRootPane().putClientProperty("Window.documentFile", file); } else { setTitle("PDF Debugger - " + file.getAbsolutePath()); } addRecentFileItems(); } private void readPDFurl(String urlString, String password) throws IOException { if (document != null) { document.close(); if (!currentFilePath.startsWith("http")) { recentFiles.addFile(currentFilePath); } } currentFilePath = urlString; URL url = new URL(urlString); LogDialog.instance().clear(); document = PDDocument.load(url.openStream(), password); printMenuItem.setEnabled(true); reopenMenuItem.setEnabled(true); initTree(); if (IS_MAC_OS) { setTitle(urlString); } else { setTitle("PDF Debugger - " + urlString); } addRecentFileItems(); } private void initTree() { TreeStatus treeStatus = new TreeStatus(document.getDocument().getTrailer()); statusPane.updateTreeStatus(treeStatus); if (isPageMode) { File file = new File(currentFilePath); DocumentEntry documentEntry = new DocumentEntry(document, file.getName()); ZoomMenu.getInstance().resetZoom(); tree.setModel(new PDFTreeModel(documentEntry)); // Root/Pages/Kids/[0] is not always the first page, so use the first row instead: tree.setSelectionPath(tree.getPathForRow(1)); } else { tree.setModel(new PDFTreeModel(document)); tree.setSelectionPath(treeStatus.getPathForString("Root")); } } /** * This will parse a document. * * @param file The file addressing the document. * * @throws IOException If there is an error parsing the document. */ private void parseDocument( File file, String password )throws IOException { while (true) { try { document = PDDocument.load(file, password); } catch (InvalidPasswordException ipe) { // https://stackoverflow.com/questions/8881213/joptionpane-to-get-password JPanel panel = new JPanel(); JLabel label = new JLabel("Password:"); JPasswordField pass = new JPasswordField(10); panel.add(label); panel.add(pass); String[] options = new String[] {"OK", "Cancel"}; int option = JOptionPane.showOptionDialog(null, panel, "Enter password", JOptionPane.NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, ""); if (option == 0) { password = new String(pass.getPassword()); continue; } throw ipe; } break; } printMenuItem.setEnabled(true); reopenMenuItem.setEnabled(true); } private void addRecentFileItems() { Action recentMenuAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent actionEvent) { String filePath = (String) ((JComponent) actionEvent.getSource()).getClientProperty("path"); try { readPDFFile(filePath, ""); } catch (Exception e) { throw new RuntimeException(e); } } }; if (!recentFiles.isEmpty()) { recentFilesMenu.removeAll(); List<String> files = recentFiles.getFiles(); for (int i = files.size() - 1; i >= 0; i--) { String path = files.get(i); String name = new File(path).getName(); JMenuItem recentFileMenuItem = new JMenuItem(name); recentFileMenuItem.putClientProperty("path", path); recentFileMenuItem.addActionListener(recentMenuAction); recentFilesMenu.add(recentFileMenuItem); } recentFilesMenu.setEnabled(true); } } /** * Convenience method to get the page label if available. * * @param document * @param pageIndex 0-based page number. * @return a page label or null if not available. */ public static String getPageLabel(PDDocument document, int pageIndex) { PDPageLabels pageLabels; try { pageLabels = document.getDocumentCatalog().getPageLabels(); } catch (IOException ex) { return ex.getMessage(); } if (pageLabels != null) { String[] labels = pageLabels.getLabelsByPageIndices(); if (labels[pageIndex] != null) { return labels[pageIndex]; } } return null; } }
debugger/src/main/java/org/apache/pdfbox/debugger/PDFDebugger.java
/* * 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 org.apache.pdfbox.debugger; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.FileDialog; import java.awt.Toolkit; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowEvent; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.URL; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JScrollPane; import javax.swing.KeyStroke; import javax.swing.TransferHandler; import javax.swing.UIManager; import javax.swing.border.BevelBorder; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.filechooser.FileFilter; import javax.swing.tree.TreePath; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSBoolean; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSFloat; import org.apache.pdfbox.cos.COSInteger; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSNull; import org.apache.pdfbox.cos.COSObject; import org.apache.pdfbox.cos.COSStream; import org.apache.pdfbox.cos.COSString; import org.apache.pdfbox.debugger.colorpane.CSArrayBased; import org.apache.pdfbox.debugger.colorpane.CSDeviceN; import org.apache.pdfbox.debugger.colorpane.CSIndexed; import org.apache.pdfbox.debugger.colorpane.CSSeparation; import org.apache.pdfbox.debugger.flagbitspane.FlagBitsPane; import org.apache.pdfbox.debugger.fontencodingpane.FontEncodingPaneController; import org.apache.pdfbox.debugger.pagepane.PagePane; import org.apache.pdfbox.debugger.streampane.StreamPane; import org.apache.pdfbox.debugger.stringpane.StringPane; import org.apache.pdfbox.debugger.treestatus.TreeStatus; import org.apache.pdfbox.debugger.treestatus.TreeStatusPane; import org.apache.pdfbox.debugger.ui.ArrayEntry; import org.apache.pdfbox.debugger.ui.DocumentEntry; import org.apache.pdfbox.debugger.ui.ErrorDialog; import org.apache.pdfbox.debugger.ui.ExtensionFileFilter; import org.apache.pdfbox.debugger.ui.FileOpenSaveDialog; import org.apache.pdfbox.debugger.ui.LogDialog; import org.apache.pdfbox.debugger.ui.MapEntry; import org.apache.pdfbox.debugger.ui.OSXAdapter; import org.apache.pdfbox.debugger.ui.PDFTreeCellRenderer; import org.apache.pdfbox.debugger.ui.PDFTreeModel; import org.apache.pdfbox.debugger.ui.PageEntry; import org.apache.pdfbox.debugger.ui.ReaderBottomPanel; import org.apache.pdfbox.debugger.ui.RecentFiles; import org.apache.pdfbox.debugger.ui.RotationMenu; import org.apache.pdfbox.debugger.ui.Tree; import org.apache.pdfbox.debugger.ui.ZoomMenu; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.common.PDPageLabels; import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException; import org.apache.pdfbox.printing.PDFPageable; /** * PDF Debugger. * * @author wurtz * @author Ben Litchfield * @author Khyrul Bashar */ public class PDFDebugger extends JFrame { private static final Set<COSName> SPECIALCOLORSPACES = new HashSet<COSName>(Arrays.asList(COSName.INDEXED, COSName.SEPARATION, COSName.DEVICEN)); private static final Set<COSName> OTHERCOLORSPACES = new HashSet<COSName>(Arrays.asList(COSName.ICCBASED, COSName.PATTERN, COSName.CALGRAY, COSName.CALRGB, COSName.LAB)); private static final String PASSWORD = "-password"; private static final String VIEW_STRUCTURE = "-viewstructure"; private static final int SHORCUT_KEY_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); private static final String OS_NAME = System.getProperty("os.name").toLowerCase(); private static final boolean IS_MAC_OS = OS_NAME.startsWith("mac os x"); private final JPanel documentPanel = new JPanel(); private TreeStatusPane statusPane; private RecentFiles recentFiles; private boolean isPageMode; private PDDocument document; private String currentFilePath; private JScrollPane jScrollPane1; private JScrollPane jScrollPane2; private javax.swing.JSplitPane jSplitPane1; private javax.swing.JTextPane jTextPane1; private ReaderBottomPanel statusBar; private Tree tree; // file menu private JMenuItem saveAsMenuItem; private JMenuItem saveMenuItem; private JMenu recentFilesMenu; private JMenuItem printMenuItem; private JMenuItem reopenMenuItem; // edit > find menu private JMenu findMenu; private JMenuItem findMenuItem; private JMenuItem findNextMenuItem; private JMenuItem findPreviousMenuItem; // view menu private JMenuItem viewModeItem; public static JCheckBoxMenuItem showTextStripper; public static JCheckBoxMenuItem showTextStripperBeads; public static JCheckBoxMenuItem showFontBBox; public static JCheckBoxMenuItem showGlyphBounds; // configuration public static Properties configuration = new Properties(); /** * Constructor. */ public PDFDebugger() { this(false); } /** * Constructor. */ public PDFDebugger(boolean viewPages) { isPageMode = viewPages; loadConfiguration(); initComponents(); // use our custom logger LogDialog.init(this, statusBar.getLogLabel()); System.setProperty("org.apache.commons.logging.Log", "org.apache.pdfbox.debugger.ui.DebugLog"); } /** * Entry point. * * @param args the command line arguments * @throws Exception If anything goes wrong. */ public static void main(String[] args) throws Exception { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); if (System.getProperty("apple.laf.useScreenMenuBar") == null) { System.setProperty("apple.laf.useScreenMenuBar", "true"); } // handle uncaught exceptions Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable throwable) { new ErrorDialog(throwable).setVisible(true); } }); // open file, if any String filename = null; String password = ""; boolean viewPages = true; for( int i = 0; i < args.length; i++ ) { if( args[i].equals( PASSWORD ) ) { i++; if( i >= args.length ) { usage(); } password = args[i]; } else if( args[i].equals(VIEW_STRUCTURE) ) { viewPages = false; } else { filename = args[i]; } } final PDFDebugger viewer = new PDFDebugger(viewPages); if (filename != null) { File file = new File(filename); if (file.exists()) { viewer.readPDFFile(filename, password); } } viewer.setVisible(true); } /** * This will print out a message telling how to use this utility. */ private static void usage() { String message = "Usage: java -jar pdfbox-app-x.y.z.jar PDFDebugger [options] <inputfile>\n" + "\nOptions:\n" + " -password <password> : Password to decrypt the document\n" + " -viewstructure : activate structure mode on startup\n" + " <inputfile> : The PDF document to be loaded\n"; System.err.println(message); System.exit(1); } /** * Loads the local configuration file, if any. */ private void loadConfiguration() { File file = new File("config.properties"); if (file.exists()) { try { InputStream is = new FileInputStream(file); configuration.load(is); is.close(); } catch(IOException e) { throw new RuntimeException(e); } } } /** * This method is called from within the constructor to initialize the form. */ private void initComponents() { jSplitPane1 = new javax.swing.JSplitPane(); jScrollPane1 = new JScrollPane(); tree = new Tree(this); jScrollPane2 = new JScrollPane(); jTextPane1 = new javax.swing.JTextPane(); tree.setCellRenderer(new PDFTreeCellRenderer()); tree.setModel(null); setTitle("Apache PDFBox Debugger"); addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowOpened(WindowEvent windowEvent) { tree.requestFocusInWindow(); super.windowOpened(windowEvent); } @Override public void windowClosing(WindowEvent evt) { exitForm(evt); } }); jScrollPane1.setBorder(new BevelBorder(BevelBorder.RAISED)); jScrollPane1.setPreferredSize(new Dimension(350, 500)); tree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent evt) { jTree1ValueChanged(evt); } }); jScrollPane1.setViewportView(tree); jSplitPane1.setRightComponent(jScrollPane2); jSplitPane1.setDividerSize(3); jScrollPane2.setPreferredSize(new Dimension(300, 500)); jScrollPane2.setViewportView(jTextPane1); jSplitPane1.setLeftComponent(jScrollPane1); JScrollPane documentScroller = new JScrollPane(); documentScroller.setViewportView(documentPanel); statusPane = new TreeStatusPane(tree); statusPane.getPanel().setBorder(new BevelBorder(BevelBorder.RAISED)); statusPane.getPanel().setPreferredSize(new Dimension(300, 25)); getContentPane().add(statusPane.getPanel(), BorderLayout.PAGE_START); getContentPane().add(jSplitPane1, BorderLayout.CENTER); statusBar = new ReaderBottomPanel(); getContentPane().add(statusBar, BorderLayout.SOUTH); // create menus JMenuBar menuBar = new JMenuBar(); menuBar.add(createFileMenu()); menuBar.add(createEditMenu()); menuBar.add(createViewMenu()); setJMenuBar(menuBar); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int width = 1000; int height = 970; setBounds((screenSize.width - width) / 2, (screenSize.height - height) / 2, width, height); // drag and drop to open files setTransferHandler(new TransferHandler() { @Override public boolean canImport(TransferSupport transferSupport) { return transferSupport.isDataFlavorSupported(DataFlavor.javaFileListFlavor); } @Override @SuppressWarnings("unchecked") public boolean importData(TransferSupport transferSupport) { try { Transferable transferable = transferSupport.getTransferable(); List<File> files = (List<File>) transferable.getTransferData( DataFlavor.javaFileListFlavor); readPDFFile(files.get(0), ""); return true; } catch (IOException e) { new ErrorDialog(e).setVisible(true); return true; } catch (UnsupportedFlavorException e) { throw new RuntimeException(e); } } }); // Mac OS X file open/quit handler if (IS_MAC_OS) { try { Method osxOpenFiles = getClass().getDeclaredMethod("osxOpenFiles", String.class); osxOpenFiles.setAccessible(true); OSXAdapter.setFileHandler(this, osxOpenFiles); Method osxQuit = getClass().getDeclaredMethod("osxQuit"); osxQuit.setAccessible(true); OSXAdapter.setQuitHandler(this, osxQuit); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } } private JMenu createFileMenu() { JMenuItem openMenuItem = new JMenuItem("Open..."); openMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, SHORCUT_KEY_MASK)); openMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { openMenuItemActionPerformed(evt); } }); JMenu fileMenu = new JMenu("File"); fileMenu.add(openMenuItem); fileMenu.setMnemonic('F'); JMenuItem openUrlMenuItem = new JMenuItem("Open URL..."); openUrlMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, SHORCUT_KEY_MASK)); openUrlMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { String urlString = JOptionPane.showInputDialog("Enter an URL"); if (urlString == null || urlString.isEmpty()) { return; } try { readPDFurl(urlString, ""); } catch (IOException e) { throw new RuntimeException(e); } } }); fileMenu.add(openUrlMenuItem); reopenMenuItem = new JMenuItem("Reopen"); reopenMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, SHORCUT_KEY_MASK)); reopenMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { try { if (currentFilePath.startsWith("http")) { readPDFurl(currentFilePath, ""); } else { readPDFFile(currentFilePath, ""); } } catch (IOException e) { new ErrorDialog(e).setVisible(true); } } }); reopenMenuItem.setEnabled(false); fileMenu.add(reopenMenuItem); try { recentFiles = new RecentFiles(this.getClass(), 5); } catch (Exception e) { throw new RuntimeException(e); } recentFilesMenu = new JMenu("Open Recent"); recentFilesMenu.setEnabled(false); addRecentFileItems(); fileMenu.add(recentFilesMenu); printMenuItem = new JMenuItem("Print"); printMenuItem.setEnabled(false); printMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { printMenuItemActionPerformed(evt); } }); if (!IS_MAC_OS) { fileMenu.addSeparator(); fileMenu.add(printMenuItem); } JMenuItem exitMenuItem = new JMenuItem("Exit"); exitMenuItem.setAccelerator(KeyStroke.getKeyStroke("alt F4")); exitMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { exitMenuItemActionPerformed(evt); } }); if (!IS_MAC_OS) { fileMenu.addSeparator(); fileMenu.add(exitMenuItem); } return fileMenu; } private JMenu createEditMenu() { JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic('E'); JMenuItem cutMenuItem = new JMenuItem("Cut"); cutMenuItem.setEnabled(false); editMenu.add(cutMenuItem); JMenuItem copyMenuItem = new JMenuItem("Copy"); copyMenuItem.setEnabled(false); editMenu.add(copyMenuItem); JMenuItem pasteMenuItem = new JMenuItem("Paste"); pasteMenuItem.setEnabled(false); editMenu.add(pasteMenuItem); JMenuItem deleteMenuItem = new JMenuItem("Delete"); deleteMenuItem.setEnabled(false); editMenu.add(deleteMenuItem); editMenu.addSeparator(); editMenu.add(createFindMenu()); return editMenu; } private JMenu createViewMenu() { JMenu viewMenu = new JMenu("View"); viewMenu.setMnemonic('V'); if (isPageMode) { viewModeItem = new JMenuItem("Show Internal Structure"); } else { viewModeItem = new JMenuItem("Show Pages"); } viewModeItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if (isPageMode) { viewModeItem.setText("Show Pages"); isPageMode = false; } else { viewModeItem.setText("Show Internal Structure"); isPageMode = true; } if (document != null) { initTree(); } } }); viewMenu.add(viewModeItem); ZoomMenu zoomMenu = ZoomMenu.getInstance(); zoomMenu.setEnableMenu(false); viewMenu.add(zoomMenu.getMenu()); RotationMenu rotationMenu = RotationMenu.getInstance(); rotationMenu.setEnableMenu(false); viewMenu.add(rotationMenu.getMenu()); viewMenu.addSeparator(); showTextStripper = new JCheckBoxMenuItem("Show TextStripper TextPositions"); showTextStripper.setEnabled(false); viewMenu.add(showTextStripper); showTextStripperBeads = new JCheckBoxMenuItem("Show TextStripper Beads"); showTextStripperBeads.setEnabled(false); viewMenu.add(showTextStripperBeads); showFontBBox = new JCheckBoxMenuItem("Show Approximate Text Bounds"); showFontBBox.setEnabled(false); viewMenu.add(showFontBBox); showGlyphBounds = new JCheckBoxMenuItem("Show Glyph Bounds"); showGlyphBounds.setEnabled(false); viewMenu.add(showGlyphBounds); return viewMenu; } private JMenu createFindMenu() { findMenu = new JMenu("Find"); findMenu.setEnabled(false); findMenuItem = new JMenuItem("Find..."); findMenuItem.setActionCommand("find"); findMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, SHORCUT_KEY_MASK)); findNextMenuItem = new JMenuItem("Find Next"); if (IS_MAC_OS) { findNextMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, SHORCUT_KEY_MASK)); } else { findNextMenuItem.setAccelerator(KeyStroke.getKeyStroke("F3")); } findPreviousMenuItem = new JMenuItem("Find Previous"); if (IS_MAC_OS) { findPreviousMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_G, SHORCUT_KEY_MASK | InputEvent.SHIFT_DOWN_MASK)); } else { findPreviousMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_F3, InputEvent.SHIFT_DOWN_MASK)); } findMenu.add(findMenuItem); findMenu.add(findNextMenuItem); findMenu.add(findPreviousMenuItem); return findMenu; } /** * Returns the File menu. */ public JMenu getFindMenu() { return findMenu; } /** * Returns the Edit &gt; Find &gt; Find menu item. */ public JMenuItem getFindMenuItem() { return findMenuItem; } /** * Returns the Edit &gt; Find &gt; Find Next menu item. */ public JMenuItem getFindNextMenuItem() { return findNextMenuItem; } /** * Returns the Edit &gt; Find &gt; Find Previous menu item. */ public JMenuItem getFindPreviousMenuItem() { return findPreviousMenuItem; } /** * This method is called via reflection on Mac OS X. */ private void osxOpenFiles(String filename) { try { readPDFFile(filename, ""); } catch (IOException e) { throw new RuntimeException(e); } } /** * This method is called via reflection on Mac OS X. */ private void osxQuit() { exitMenuItemActionPerformed(null); } private void openMenuItemActionPerformed(ActionEvent evt) { try { if (IS_MAC_OS) { FileDialog openDialog = new FileDialog(this, "Open"); openDialog.setFilenameFilter(new FilenameFilter() { @Override public boolean accept(File file, String s) { return file.getName().toLowerCase().endsWith(".pdf"); } }); openDialog.setVisible(true); if (openDialog.getFile() != null) { readPDFFile(openDialog.getFile(), ""); } } else { String[] extensions = new String[] {"pdf", "PDF"}; FileFilter pdfFilter = new ExtensionFileFilter(extensions, "PDF Files (*.pdf)"); FileOpenSaveDialog openDialog = new FileOpenSaveDialog(this, pdfFilter); File file = openDialog.openFile(); if (file != null) { readPDFFile(file, ""); } } } catch (IOException e) { throw new RuntimeException(e); } } private void jTree1ValueChanged(TreeSelectionEvent evt) { TreePath path = tree.getSelectionPath(); if (path != null) { try { Object selectedNode = path.getLastPathComponent(); statusBar.getStatusLabel().setText(""); if (isPage(selectedNode)) { showPage(selectedNode); return; } if (isSpecialColorSpace(selectedNode) || isOtherColorSpace(selectedNode)) { showColorPane(selectedNode); return; } if (path.getParentPath() != null && isFlagNode(selectedNode, path.getParentPath().getLastPathComponent())) { Object parentNode = path.getParentPath().getLastPathComponent(); showFlagPane(parentNode, selectedNode); return; } if (isStream(selectedNode)) { showStream((COSStream) getUnderneathObject(selectedNode), path); return; } if (isFont(selectedNode)) { showFont(selectedNode, path); return; } if (isString(selectedNode)) { showString(selectedNode); return; } if (jSplitPane1.getRightComponent() == null || !jSplitPane1.getRightComponent().equals(jScrollPane2)) { replaceRightComponent(jScrollPane2); } jTextPane1.setText(convertToString(selectedNode)); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } } private boolean isSpecialColorSpace(Object selectedNode) { selectedNode = getUnderneathObject(selectedNode); if (selectedNode instanceof COSArray && ((COSArray) selectedNode).size() > 0) { COSBase arrayEntry = ((COSArray)selectedNode).get(0); if (arrayEntry instanceof COSName) { COSName name = (COSName) arrayEntry; return SPECIALCOLORSPACES.contains(name); } } return false; } private boolean isOtherColorSpace(Object selectedNode) { selectedNode = getUnderneathObject(selectedNode); if (selectedNode instanceof COSArray && ((COSArray) selectedNode).size() > 0) { COSBase arrayEntry = ((COSArray)selectedNode).get(0); if (arrayEntry instanceof COSName) { COSName name = (COSName) arrayEntry; return OTHERCOLORSPACES.contains(name); } } return false; } private boolean isPage(Object selectedNode) { selectedNode = getUnderneathObject(selectedNode); if (selectedNode instanceof COSDictionary) { COSDictionary dict = (COSDictionary) selectedNode; COSBase typeItem = dict.getItem(COSName.TYPE); if (COSName.PAGE.equals(typeItem)) { return true; } } else if (selectedNode instanceof PageEntry) { return true; } return false; } private boolean isFlagNode(Object selectedNode, Object parentNode) { if (selectedNode instanceof MapEntry) { Object key = ((MapEntry) selectedNode).getKey(); return (COSName.FLAGS.equals(key) && isFontDescriptor(parentNode)) || (COSName.F.equals(key) && isAnnot(parentNode)) || COSName.FF.equals(key) || COSName.PANOSE.equals(key) || COSName.SIG_FLAGS.equals(key) || (COSName.P.equals(key) && isEncrypt(parentNode)); } return false; } private boolean isEncrypt(Object obj) { if (obj instanceof MapEntry) { MapEntry entry = (MapEntry) obj; return COSName.ENCRYPT.equals(entry.getKey()) && entry.getValue() instanceof COSDictionary; } return false; } private boolean isFontDescriptor(Object obj) { Object underneathObject = getUnderneathObject(obj); return underneathObject instanceof COSDictionary && ((COSDictionary) underneathObject).containsKey(COSName.TYPE) && ((COSDictionary) underneathObject).getCOSName(COSName.TYPE).equals(COSName.FONT_DESC); } private boolean isAnnot(Object obj) { Object underneathObject = getUnderneathObject(obj); return underneathObject instanceof COSDictionary && ((COSDictionary) underneathObject).containsKey(COSName.TYPE) && ((COSDictionary) underneathObject).getCOSName(COSName.TYPE).equals(COSName.ANNOT); } private boolean isStream(Object selectedNode) { return getUnderneathObject(selectedNode) instanceof COSStream; } private boolean isString(Object selectedNode) { return getUnderneathObject(selectedNode) instanceof COSString; } private boolean isFont(Object selectedNode) { selectedNode = getUnderneathObject(selectedNode); if (selectedNode instanceof COSDictionary) { COSDictionary dic = (COSDictionary)selectedNode; return dic.containsKey(COSName.TYPE) && dic.getCOSName(COSName.TYPE).equals(COSName.FONT) && !isCIDFont(dic); } return false; } private boolean isCIDFont(COSDictionary dic) { return dic.containsKey(COSName.SUBTYPE) && (dic.getCOSName(COSName.SUBTYPE).equals(COSName.CID_FONT_TYPE0) || dic.getCOSName(COSName.SUBTYPE).equals(COSName.CID_FONT_TYPE2)); } /** * Show a Panel describing color spaces in more detail and interactive way. * @param csNode the special color space containing node. */ private void showColorPane(Object csNode) { csNode = getUnderneathObject(csNode); if (csNode instanceof COSArray && ((COSArray) csNode).size() > 0) { COSArray array = (COSArray)csNode; COSBase arrayEntry = array.get(0); if (arrayEntry instanceof COSName) { COSName csName = (COSName) arrayEntry; if (csName.equals(COSName.SEPARATION)) { replaceRightComponent(new CSSeparation(array).getPanel()); } else if (csName.equals(COSName.DEVICEN)) { replaceRightComponent(new CSDeviceN(array).getPanel()); } else if (csName.equals(COSName.INDEXED)) { replaceRightComponent(new CSIndexed(array).getPanel()); } else if (OTHERCOLORSPACES.contains(csName)) { replaceRightComponent(new CSArrayBased(array).getPanel()); } } } } private void showPage(Object selectedNode) { selectedNode = getUnderneathObject(selectedNode); COSDictionary page; if (selectedNode instanceof COSDictionary) { page = (COSDictionary) selectedNode; } else { page = ((PageEntry) selectedNode).getDict(); } COSBase typeItem = page.getItem(COSName.TYPE); if (COSName.PAGE.equals(typeItem)) { PagePane pagePane = new PagePane(document, page, statusBar.getStatusLabel()); replaceRightComponent(new JScrollPane(pagePane.getPanel())); } } private void showFlagPane(Object parentNode, Object selectedNode) { parentNode = getUnderneathObject(parentNode); if (parentNode instanceof COSDictionary) { selectedNode = ((MapEntry)selectedNode).getKey(); selectedNode = getUnderneathObject(selectedNode); FlagBitsPane flagBitsPane = new FlagBitsPane((COSDictionary) parentNode, (COSName) selectedNode); replaceRightComponent(flagBitsPane.getPane()); } } private void showStream(COSStream stream, TreePath path) throws IOException { boolean isContentStream = false; boolean isThumb = false; COSName key = getNodeKey(path.getLastPathComponent()); COSName parentKey = getNodeKey(path.getParentPath().getLastPathComponent()); COSDictionary resourcesDic = null; if (COSName.CONTENTS.equals(key)) { Object pageObj = path.getParentPath().getLastPathComponent(); COSDictionary page = (COSDictionary) getUnderneathObject(pageObj); resourcesDic = (COSDictionary) page.getDictionaryObject(COSName.RESOURCES); isContentStream = true; } else if (COSName.CONTENTS.equals(parentKey) || COSName.CHAR_PROCS.equals(parentKey)) { Object pageObj = path.getParentPath().getParentPath().getLastPathComponent(); COSDictionary page = (COSDictionary) getUnderneathObject(pageObj); resourcesDic = (COSDictionary) page.getDictionaryObject(COSName.RESOURCES); isContentStream = true; } else if (COSName.FORM.equals(stream.getCOSName(COSName.SUBTYPE)) || COSName.PATTERN.equals(stream.getCOSName(COSName.TYPE)) || stream.getInt(COSName.PATTERN_TYPE) == 1) { if (stream.containsKey(COSName.RESOURCES)) { resourcesDic = (COSDictionary) stream.getDictionaryObject(COSName.RESOURCES); } isContentStream = true; } else if (COSName.THUMB.equals(key)) { resourcesDic = null; isThumb = true; } else if (COSName.IMAGE.equals((stream).getCOSName(COSName.SUBTYPE))) { // not to be used for /Thumb, even if it contains /Subtype /Image Object resourcesObj = path.getParentPath().getParentPath().getLastPathComponent(); resourcesDic = (COSDictionary) getUnderneathObject(resourcesObj); } StreamPane streamPane = new StreamPane(stream, isContentStream, isThumb, resourcesDic); replaceRightComponent(streamPane.getPanel()); } private void showFont(Object selectedNode, TreePath path) { COSName fontName = getNodeKey(selectedNode); COSDictionary resourceDic = (COSDictionary) getUnderneathObject(path.getParentPath().getParentPath().getLastPathComponent()); FontEncodingPaneController fontEncodingPaneController = new FontEncodingPaneController(fontName, resourceDic); JPanel pane = fontEncodingPaneController.getPane(); if (pane == null) { // unsupported font type replaceRightComponent(jScrollPane2); return; } replaceRightComponent(pane); } // replace the right component while keeping divider position private void replaceRightComponent(Component pane) { int div = jSplitPane1.getDividerLocation(); jSplitPane1.setRightComponent(pane); jSplitPane1.setDividerLocation(div); } private void showString(Object selectedNode) { COSString string = (COSString)getUnderneathObject(selectedNode); replaceRightComponent(new StringPane(string).getPane()); } private COSName getNodeKey(Object selectedNode) { if (selectedNode instanceof MapEntry) { return ((MapEntry) selectedNode).getKey(); } return null; } private Object getUnderneathObject(Object selectedNode) { if (selectedNode instanceof MapEntry) { selectedNode = ((MapEntry) selectedNode).getValue(); } else if (selectedNode instanceof ArrayEntry) { selectedNode = ((ArrayEntry) selectedNode).getValue(); } else if (selectedNode instanceof PageEntry) { selectedNode = ((PageEntry) selectedNode).getDict(); } if (selectedNode instanceof COSObject) { selectedNode = ((COSObject) selectedNode).getObject(); } return selectedNode; } private String convertToString( Object selectedNode ) { String data = null; if(selectedNode instanceof COSBoolean) { data = "" + ((COSBoolean)selectedNode).getValue(); } else if( selectedNode instanceof COSFloat ) { data = "" + ((COSFloat)selectedNode).floatValue(); } else if( selectedNode instanceof COSNull ) { data = "null"; } else if( selectedNode instanceof COSInteger ) { data = "" + ((COSInteger)selectedNode).intValue(); } else if( selectedNode instanceof COSName ) { data = "" + ((COSName)selectedNode).getName(); } else if( selectedNode instanceof COSString ) { String text = ((COSString) selectedNode).getString(); // display unprintable strings as hex for (char c : text.toCharArray()) { if (Character.isISOControl(c)) { text = "<" + ((COSString) selectedNode).toHexString() + ">"; break; } } data = "" + text; } else if( selectedNode instanceof COSStream ) { try { COSStream stream = (COSStream)selectedNode; InputStream ioStream = stream.createInputStream(); ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int amountRead; while( (amountRead = ioStream.read( buffer, 0, buffer.length ) ) != -1 ) { byteArray.write( buffer, 0, amountRead ); } data = byteArray.toString(); } catch( IOException e ) { throw new RuntimeException(e); } } else if( selectedNode instanceof MapEntry ) { data = convertToString( ((MapEntry)selectedNode).getValue() ); } else if( selectedNode instanceof ArrayEntry ) { data = convertToString( ((ArrayEntry)selectedNode).getValue() ); } return data; } private void exitMenuItemActionPerformed(ActionEvent evt) { if( document != null ) { try { document.close(); if (!currentFilePath.startsWith("http")) { recentFiles.addFile(currentFilePath); } recentFiles.close(); } catch( IOException e ) { throw new RuntimeException(e); } } System.exit(0); } private void printMenuItemActionPerformed(ActionEvent evt) { if( document != null ) { try { PrinterJob job = PrinterJob.getPrinterJob(); job.setPageable(new PDFPageable(document)); if (job.printDialog()) { job.print(); } } catch (PrinterException e) { throw new RuntimeException(e); } } } /** * Exit the Application. */ private void exitForm(WindowEvent evt) { if( document != null ) { try { document.close(); if (!currentFilePath.startsWith("http")) { recentFiles.addFile(currentFilePath); } recentFiles.close(); } catch( IOException e ) { throw new RuntimeException(e); } } System.exit(0); } private void readPDFFile(String filePath, String password) throws IOException { File file = new File(filePath); readPDFFile(file, password); } private void readPDFFile(File file, String password) throws IOException { if( document != null ) { document.close(); if (!currentFilePath.startsWith("http")) { recentFiles.addFile(currentFilePath); } } currentFilePath = file.getPath(); recentFiles.removeFile(file.getPath()); LogDialog.instance().clear(); parseDocument( file, password ); initTree(); if (IS_MAC_OS) { setTitle(file.getName()); getRootPane().putClientProperty("Window.documentFile", file); } else { setTitle("PDF Debugger - " + file.getAbsolutePath()); } addRecentFileItems(); } private void readPDFurl(String urlString, String password) throws IOException { if (document != null) { document.close(); if (!currentFilePath.startsWith("http")) { recentFiles.addFile(currentFilePath); } } currentFilePath = urlString; URL url = new URL(urlString); document = PDDocument.load(url.openStream(), password); printMenuItem.setEnabled(true); reopenMenuItem.setEnabled(true); initTree(); if (IS_MAC_OS) { setTitle(urlString); } else { setTitle("PDF Debugger - " + urlString); } addRecentFileItems(); } private void initTree() { TreeStatus treeStatus = new TreeStatus(document.getDocument().getTrailer()); statusPane.updateTreeStatus(treeStatus); if (isPageMode) { File file = new File(currentFilePath); DocumentEntry documentEntry = new DocumentEntry(document, file.getName()); ZoomMenu.getInstance().resetZoom(); tree.setModel(new PDFTreeModel(documentEntry)); // Root/Pages/Kids/[0] is not always the first page, so use the first row instead: tree.setSelectionPath(tree.getPathForRow(1)); } else { tree.setModel(new PDFTreeModel(document)); tree.setSelectionPath(treeStatus.getPathForString("Root")); } } /** * This will parse a document. * * @param file The file addressing the document. * * @throws IOException If there is an error parsing the document. */ private void parseDocument( File file, String password )throws IOException { while (true) { try { document = PDDocument.load(file, password); } catch (InvalidPasswordException ipe) { // https://stackoverflow.com/questions/8881213/joptionpane-to-get-password JPanel panel = new JPanel(); JLabel label = new JLabel("Password:"); JPasswordField pass = new JPasswordField(10); panel.add(label); panel.add(pass); String[] options = new String[] {"OK", "Cancel"}; int option = JOptionPane.showOptionDialog(null, panel, "Enter password", JOptionPane.NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, ""); if (option == 0) { password = new String(pass.getPassword()); continue; } throw ipe; } break; } printMenuItem.setEnabled(true); reopenMenuItem.setEnabled(true); } private void addRecentFileItems() { Action recentMenuAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent actionEvent) { String filePath = (String) ((JComponent) actionEvent.getSource()).getClientProperty("path"); try { readPDFFile(filePath, ""); } catch (Exception e) { throw new RuntimeException(e); } } }; if (!recentFiles.isEmpty()) { recentFilesMenu.removeAll(); List<String> files = recentFiles.getFiles(); for (int i = files.size() - 1; i >= 0; i--) { String path = files.get(i); String name = new File(path).getName(); JMenuItem recentFileMenuItem = new JMenuItem(name); recentFileMenuItem.putClientProperty("path", path); recentFileMenuItem.addActionListener(recentMenuAction); recentFilesMenu.add(recentFileMenuItem); } recentFilesMenu.setEnabled(true); } } /** * Convenience method to get the page label if available. * * @param document * @param pageIndex 0-based page number. * @return a page label or null if not available. */ public static String getPageLabel(PDDocument document, int pageIndex) { PDPageLabels pageLabels; try { pageLabels = document.getDocumentCatalog().getPageLabels(); } catch (IOException ex) { return ex.getMessage(); } if (pageLabels != null) { String[] labels = pageLabels.getLabelsByPageIndices(); if (labels[pageIndex] != null) { return labels[pageIndex]; } } return null; } }
PDFBOX-2941: clear log also before loading URL git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1781176 13f79535-47bb-0310-9956-ffa450edef68
debugger/src/main/java/org/apache/pdfbox/debugger/PDFDebugger.java
PDFBOX-2941: clear log also before loading URL
<ide><path>ebugger/src/main/java/org/apache/pdfbox/debugger/PDFDebugger.java <ide> } <ide> currentFilePath = urlString; <ide> URL url = new URL(urlString); <add> LogDialog.instance().clear(); <ide> document = PDDocument.load(url.openStream(), password); <ide> printMenuItem.setEnabled(true); <ide> reopenMenuItem.setEnabled(true);
Java
mit
120e17bcaedb8f9f4af71031f1dd595c668bf19e
0
saybur/fractala
package com.tarvon.fractala.util; import java.awt.EventQueue; import java.awt.Graphics; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.image.BufferedImage; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.SpinnerNumberModel; import com.tarvon.fractala.Fractals; /** * Graphical utility to help select {@link ColorChooser} values. * * @author saybur * */ public class ColorHelper { @SuppressWarnings("serial") private final class ColorPanel extends JPanel { private ColorChooser chooser; public ColorPanel() { setOpaque(true); setPreferredSize(new Dimension(1024, 512)); } @Override public void paint(Graphics g) { // get draw size final Dimension size = this.getSize(); if(size == null) return; final int width = size.width; final int height = size.height; if(width == 0 || height == 0) return; // alias chooser final ColorChooser chooser = this.chooser; if(chooser == null) { g.setColor(Color.BLACK); g.fillRect(0, 0, width, height); return; } // get seed final int seed = ((Integer) seedSpinner.getValue()) .intValue(); // draw final BufferedImage image = Fractals .createSimplexFractal(seed, 10) .call() .normalize(0, MAX) .toImage(chooser); g.drawImage(image, 0, 0, null); } } private static final int ROWS = 16; private static final double MAX = 100.0; private static final Color ERROR_COLOR = new Color(255, 200, 200); private static final Color GOOD_COLOR = new Color(255, 255, 255); public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ColorHelper window = new ColorHelper(); window.frame.setVisible(true); } catch(Exception e) { e.printStackTrace(); } } }); } private final JFrame frame; private final JSpinner seedSpinner; private final List<JSpinner> spinners; private final List<JTextField> fields; private final ColorPanel colorPanel; public ColorHelper() { frame = new JFrame("Color Helper"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); // make the color panel colorPanel = new ColorPanel(); frame.getContentPane().add(colorPanel, BorderLayout.EAST); // create GUI elements spinners = IntStream.range(0, ROWS).boxed() .map(i -> { final JSpinner spinner = new JSpinner(new SpinnerNumberModel( 0.0, 0.0, MAX, 0.01)); spinner.setBackground(ERROR_COLOR); spinner.setPreferredSize(new Dimension( 100, spinner.getPreferredSize().height)); return spinner; }) .collect(Collectors.toList()); fields = IntStream.range(0, ROWS).boxed() .map(i -> { final JTextField field = new JTextField(); field.setBackground(ERROR_COLOR); field.addActionListener(e -> update()); field.setPreferredSize(new Dimension( 100, field.getPreferredSize().height)); return field; }) .collect(Collectors.toList()); // put a few defaults in spinners.get(0).setValue(0.0); fields.get(0).setText("#000000"); spinners.get(1).setValue(MAX); fields.get(1).setText("#FFFFFF"); // create table of entry objects final JPanel entryPanel = new JPanel(); entryPanel.setLayout(new GridLayout(ROWS, 2, 2, 2)); for(int i = 0; i < ROWS; i++) { entryPanel.add(spinners.get(i)); entryPanel.add(fields.get(i)); } frame.getContentPane().add(entryPanel); // the maximum spinner seedSpinner = new JSpinner(new SpinnerNumberModel( 1000, 1, Integer.MAX_VALUE, 1)); seedSpinner.addChangeListener(e -> update()); frame.getContentPane().add(seedSpinner, BorderLayout.NORTH); // redrawing button final JButton redrawButton = new JButton("Redraw"); redrawButton.addActionListener(e -> update()); frame.getContentPane().add(redrawButton, BorderLayout.SOUTH); update(); frame.pack(); } private void update() { final ColorChooser.Builder b = ColorChooser.builder(); for(int i = 0; i < ROWS; i++) { final JSpinner spinner = spinners.get(i); final JTextField field = fields.get(i); // fetch color or error final Color color; try { color = Color.decode(field.getText()); field.setBackground(GOOD_COLOR); } catch(Exception e) { field.setBackground(ERROR_COLOR); continue; } // fetch value or error final double value; try { value = ((Double) spinner.getValue()).doubleValue(); spinner.setBackground(GOOD_COLOR); } catch(Exception e) { spinner.setBackground(ERROR_COLOR); continue; } // insert into chooser b.add(value, color); } // assign try { ColorChooser chooser = b.create(); colorPanel.chooser = chooser; } catch(Exception e) { colorPanel.chooser = null; } colorPanel.repaint(); } }
fractala/src/com/tarvon/fractala/util/ColorHelper.java
package com.tarvon.fractala.util; import java.awt.EventQueue; import java.awt.Graphics; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.image.BufferedImage; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.SpinnerNumberModel; /** * Graphical utility to help select {@link ColorChooser} values. * * @author saybur * */ public class ColorHelper { @SuppressWarnings("serial") private final class ColorPanel extends JPanel { private ColorChooser chooser; public ColorPanel() { setOpaque(true); setPreferredSize(new Dimension(100, 600)); } @Override public void paint(Graphics g) { // get draw size final Dimension size = this.getSize(); if(size == null) return; final int width = size.width; final int height = size.height; if(width == 0 || height == 0) return; // alias chooser final ColorChooser chooser = this.chooser; if(chooser == null) { g.setColor(Color.BLACK); g.fillRect(0, 0, width, height); return; } // get maximum draw final double maxValue = ((Double) maxSpinner.getValue()) .doubleValue(); // create drawing image final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for(int y = 0; y < height; y++) { double n = y / (double) height; n *= maxValue; int color = chooser.applyAsInt(n); for(int x = 0; x < width; x++) image.setRGB(x, y, color); } // then draw g.drawImage(image, 0, 0, null); } } private static final int ROWS = 16; private static final double MAX_RANGE = 10.0; private static final Color ERROR_COLOR = new Color(255, 200, 200); private static final Color GOOD_COLOR = new Color(255, 255, 255); public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ColorHelper window = new ColorHelper(); window.frame.setVisible(true); } catch(Exception e) { e.printStackTrace(); } } }); } private final JFrame frame; private final JSpinner maxSpinner; private final List<JSpinner> spinners; private final List<JTextField> fields; private final ColorPanel colorPanel; public ColorHelper() { frame = new JFrame("Color Helper"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); // make the color panel colorPanel = new ColorPanel(); frame.getContentPane().add(colorPanel, BorderLayout.EAST); // create GUI elements spinners = IntStream.range(0, ROWS).boxed() .map(i -> { final JSpinner spinner = new JSpinner(new SpinnerNumberModel( 0.0, 0.0, MAX_RANGE, 0.001)); spinner.setBackground(ERROR_COLOR); spinner.addChangeListener(e -> update()); spinner.setPreferredSize(new Dimension( 100, spinner.getPreferredSize().height)); return spinner; }) .collect(Collectors.toList()); fields = IntStream.range(0, ROWS).boxed() .map(i -> { final JTextField field = new JTextField(); field.setBackground(ERROR_COLOR); field.addActionListener(e -> update()); field.setPreferredSize(new Dimension( 100, field.getPreferredSize().height)); return field; }) .collect(Collectors.toList()); // put a few defaults in spinners.get(0).setValue(0.0); fields.get(0).setText("#000000"); spinners.get(1).setValue(1.0); fields.get(1).setText("#FFFFFF"); // create table of entry objects final JPanel entryPanel = new JPanel(); entryPanel.setLayout(new GridLayout(ROWS, 2, 2, 2)); for(int i = 0; i < ROWS; i++) { entryPanel.add(spinners.get(i)); entryPanel.add(fields.get(i)); } frame.getContentPane().add(entryPanel); // the maximum spinner maxSpinner = new JSpinner(new SpinnerNumberModel( 1.0, 1.0, MAX_RANGE, 0.1)); maxSpinner.addChangeListener(e -> update()); frame.getContentPane().add(maxSpinner, BorderLayout.NORTH); // redrawing button final JButton redrawButton = new JButton("Redraw"); redrawButton.addActionListener(e -> update()); frame.getContentPane().add(redrawButton, BorderLayout.SOUTH); update(); frame.pack(); } private void update() { final ColorChooser.Builder b = ColorChooser.builder(); for(int i = 0; i < ROWS; i++) { final JSpinner spinner = spinners.get(i); final JTextField field = fields.get(i); // fetch color or error final Color color; try { color = Color.decode(field.getText()); field.setBackground(GOOD_COLOR); } catch(Exception e) { field.setBackground(ERROR_COLOR); continue; } // fetch value or error final double value; try { value = ((Double) spinner.getValue()).doubleValue(); spinner.setBackground(GOOD_COLOR); } catch(Exception e) { spinner.setBackground(ERROR_COLOR); continue; } // insert into chooser b.add(value, color); } // assign try { ColorChooser chooser = b.create(); colorPanel.chooser = chooser; } catch(Exception e) { colorPanel.chooser = null; } colorPanel.repaint(); } }
Might as well use the fancy fractals for this
fractala/src/com/tarvon/fractala/util/ColorHelper.java
Might as well use the fancy fractals for this
<ide><path>ractala/src/com/tarvon/fractala/util/ColorHelper.java <ide> import javax.swing.JTextField; <ide> import javax.swing.SpinnerNumberModel; <ide> <add>import com.tarvon.fractala.Fractals; <add> <ide> /** <ide> * Graphical utility to help select {@link ColorChooser} values. <ide> * <ide> public ColorPanel() <ide> { <ide> setOpaque(true); <del> setPreferredSize(new Dimension(100, 600)); <add> setPreferredSize(new Dimension(1024, 512)); <ide> } <ide> <ide> @Override <ide> return; <ide> } <ide> <del> // get maximum draw <del> final double maxValue = ((Double) maxSpinner.getValue()) <del> .doubleValue(); <del> <del> // create drawing image <del> final BufferedImage image = new BufferedImage(width, height, <del> BufferedImage.TYPE_INT_RGB); <del> for(int y = 0; y < height; y++) <del> { <del> double n = y / (double) height; <del> n *= maxValue; <del> <del> int color = chooser.applyAsInt(n); <del> for(int x = 0; x < width; x++) <del> image.setRGB(x, y, color); <del> } <del> <del> // then draw <add> // get seed <add> final int seed = ((Integer) seedSpinner.getValue()) <add> .intValue(); <add> <add> // draw <add> final BufferedImage image = Fractals <add> .createSimplexFractal(seed, 10) <add> .call() <add> .normalize(0, MAX) <add> .toImage(chooser); <ide> g.drawImage(image, 0, 0, null); <ide> } <ide> } <ide> <ide> private static final int ROWS = 16; <del> private static final double MAX_RANGE = 10.0; <add> private static final double MAX = 100.0; <ide> private static final Color ERROR_COLOR = new Color(255, 200, 200); <ide> private static final Color GOOD_COLOR = new Color(255, 255, 255); <ide> <ide> } <ide> <ide> private final JFrame frame; <del> private final JSpinner maxSpinner; <add> private final JSpinner seedSpinner; <ide> private final List<JSpinner> spinners; <ide> private final List<JTextField> fields; <ide> private final ColorPanel colorPanel; <ide> .map(i -> <ide> { <ide> final JSpinner spinner = new JSpinner(new SpinnerNumberModel( <del> 0.0, 0.0, MAX_RANGE, 0.001)); <add> 0.0, 0.0, MAX, 0.01)); <ide> spinner.setBackground(ERROR_COLOR); <del> spinner.addChangeListener(e -> update()); <ide> spinner.setPreferredSize(new Dimension( <ide> 100, <ide> spinner.getPreferredSize().height)); <ide> // put a few defaults in <ide> spinners.get(0).setValue(0.0); <ide> fields.get(0).setText("#000000"); <del> spinners.get(1).setValue(1.0); <add> spinners.get(1).setValue(MAX); <ide> fields.get(1).setText("#FFFFFF"); <ide> <ide> // create table of entry objects <ide> frame.getContentPane().add(entryPanel); <ide> <ide> // the maximum spinner <del> maxSpinner = new JSpinner(new SpinnerNumberModel( <del> 1.0, 1.0, MAX_RANGE, 0.1)); <del> maxSpinner.addChangeListener(e -> update()); <del> frame.getContentPane().add(maxSpinner, BorderLayout.NORTH); <add> seedSpinner = new JSpinner(new SpinnerNumberModel( <add> 1000, 1, Integer.MAX_VALUE, 1)); <add> seedSpinner.addChangeListener(e -> update()); <add> frame.getContentPane().add(seedSpinner, BorderLayout.NORTH); <ide> <ide> // redrawing button <ide> final JButton redrawButton = new JButton("Redraw");
JavaScript
mit
950b1edb3b65e80254422b3ae9c43020c4650bad
0
zooyalove/dailynote,zooyalove/dailynote,zooyalove/dailynote
import express from 'express'; import mongoose from 'mongoose'; import moment from 'moment'; import OrderNote from './../models/OrderNote'; import util from './../helper'; mongoose.Promise = global.Promise; const router = express.Router(); /* POST /api/note 일일장부 등록 ERROR CODES 1 : EMPTY REQUIRED FIELD 2 : PERMISSION DENIED */ router.post('/', (req, res) => { // let phoneRegex = /^\d{2,3}-\d{3,4}-\d{4}$/; if (typeof req.session.loginInfo === 'undefined') { return res.status(401).json({ error: 'PERMISSION DENIED', code: 2 }); } if (util.empty(req.body.orderer_name)) { return res.status(400).json({ error: 'EMPTY REQUIRED FIELD', code: 1 }); } if (util.empty(req.body.receiver_name)) { return res.status(400).json({ error: 'EMPTY REQUIRED FIELD', code: 1 }); } const { orderer_name, // 주문자 이름 또는 회사명 orderer_phone, // 주문자 연락처 orderer_id="no", // 주문자 고유식별자(등록된 거래처면 ID값으로, 등록되지 않았다면 "no"로 등록) receiver_name, // 받는 분 이름 receiver_phone, // 받는 분 연락처 delivery_category, // 배달품 종류 (ex. 꽃바구니, 꽃다발, 관엽 등등...) delivery_price, // 가격 delivery_date, // 배달일자 delivery_address, // 배달주소 delivery_text, // 글씨(경조사어 및 주문자 이름) memo // delivery_image, // 배송된 물품의 사진...(차후 설계하자...) // is_payment // 결제관련 여부 파악 (이것도 차후로...) } = req.body; let note = new OrderNote({ 'orderer.name': orderer_name.trim(), 'orderer.phone': orderer_phone, 'orderer.id': orderer_id, 'receiver.name': receiver_name.trim(), 'receiver.phone': receiver_phone, 'delivery.category': delivery_category, 'delivery.price': delivery_price, 'delivery.date': new Date(delivery_date), 'delivery.address': delivery_address, 'delivery.text': delivery_text, // 'delivery.image': delivery_image, 'memo': memo // 'is_payment': is_payment }); note.save( (err) => { if (err) throw err; return res.json({ success: true, id: note._id }); }); }); /* GET /api/note 모든 장부들 조회 ERROR CODES 1 : PERMISSION DENIED */ router.get('/', (req, res) => { if (typeof req.session.loginInfo === 'undefined') { return res.status(401).json({ error: 'PERMISSION DENIED', code: 1 }); } // 보여주고 싶은 field를 설정 const projection = { '_id': 1, 'orderer.name': 1, 'receiver.name': 1, 'delivery.category': 1, 'delivery.price': 1, 'delivery.address': 1, 'delivery.date': 1, // 'delivery.image': 1, 'is_payment': 1 // 'memo': 1 }; OrderNote.find({}, projection) .sort({'delivery.date': -1}) .exec( (err, notes) => { if (err) throw err; return res.json({ success: true, data: notes }); }); }); /* GET /api/note/today 특정 장부를 조회 ERROR CODES 2 : PERMISSION DENIED 3 : NO RESOURCE */ router.get('/today', (req, res) => { if (typeof req.session.loginInfo === 'undefined') { return res.status(401).json({ error: 'PERMISSION DENIED', code: 2 }); } const today = moment(); today.hour(1).minute(0); const tomorrow = moment(today).add(1, 'day'); tomorrow.hour(0).minute(0); OrderNote .find({ 'delivery.date': { $gte: today.toDate(), $lt: tomorrow.toDate() } }) .sort({ 'delivery.date': -1 }) .exec((err, notes) => { if (err) throw err; if (notes.length === 0) { return res.status(400).json({ error: 'NO RESOURCE', code: 3 }); } return res.json({ data: notes }); }); }); /* GET /api/note/search/:searchTxt 특정 장부를 조회 ERROR CODES 2 : PERMISSION DENIED */ router.get('/search/:searchTxt', (req, res) => { if (typeof req.session.loginInfo === 'undefined') { return res.status(401).json({ error: 'PERMISSION DENIED', code: 2 }); } const searchTxt = decodeURIComponent(req.params.searchTxt); let condition = null; // 찾고자 하는 날짜로 검색 if (searchTxt.indexOf('-') !== -1) { const dateArray = []; searchTxt.split('-').forEach( (d) => { dateArray.push(parseInt(d, 10)); }); condition = { 'delivery.date': { $gte: new Date(searchTxt), $lt: new Date(dateArray[0], dateArray[1]-1, dateArray[2], 23, 0, 0) } }; } else { // 찾고자 하는 검색어로 검색 condition = { $or: [ {'orderer.name': new RegExp(searchTxt, 'i')}, {'orderer.phone': new RegExp(searchTxt, 'i')}, {'receiver.name': new RegExp(searchTxt, 'i')}, {'receiver.phone': new RegExp(searchTxt, 'i')}, {'delivery.address': new RegExp(searchTxt, 'i')}, {'delivery.text': new RegExp(searchTxt, 'i')}, {'memo': new RegExp(searchTxt, 'i')} ] }; } OrderNote .find(condition) .sort({'delivery.date': -1}) .exec( (err, notes) => { if (err) throw err; return res.json({ data: notes }); }); }); /* GET /api/note/:id 특정 장부를 조회 ERROR CODES 1 : INVALID ID 2 : PERMISSION DENIED 3 : NO RESOURCE */ router.get('/:id', (req, res) => { if (typeof req.session.loginInfo === 'undefined') { return res.status(401).json({ error: 'PERMISSION DENIED', code: 2 }); } if (!mongoose.Types.ObjectId.isValid(req.params.id)) { return res.status(400).json({ error: 'INVALID ID', code: 1 }); } OrderNote.findById(req.params.id, (err, note) => { if (err) throw err; if (!note) { return res.status(400).json({ error: 'NO RESOURCE', code: 3 }); } }); }); export default router;
daily-frontend/server/src/routes/note.js
import express from 'express'; import mongoose from 'mongoose'; import moment from 'moment'; import OrderNote from './../models/OrderNote'; import util from './../helper'; mongoose.Promise = global.Promise; const router = express.Router(); /* POST /api/note 일일장부 등록 ERROR CODES 1 : EMPTY REQUIRED FIELD 2 : PERMISSION DENIED */ router.post('/', (req, res) => { // let phoneRegex = /^\d{2,3}-\d{3,4}-\d{4}$/; if (typeof req.session.loginInfo === 'undefined') { return res.status(401).json({ error: 'PERMISSION DENIED', code: 2 }); } if (util.empty(req.body.orderer_name)) { return res.status(400).json({ error: 'EMPTY REQUIRED FIELD', code: 1 }); } if (util.empty(req.body.receiver_name)) { return res.status(400).json({ error: 'EMPTY REQUIRED FIELD', code: 1 }); } const { orderer_name, // 주문자 이름 또는 회사명 orderer_phone, // 주문자 연락처 orderer_id="no", // 주문자 고유식별자(등록된 거래처면 ID값으로, 등록되지 않았다면 "no"로 등록) receiver_name, // 받는 분 이름 receiver_phone, // 받는 분 연락처 delivery_category, // 배달품 종류 (ex. 꽃바구니, 꽃다발, 관엽 등등...) delivery_price, // 가격 delivery_date, // 배달일자 delivery_address, // 배달주소 delivery_text, // 글씨(경조사어 및 주문자 이름) memo // delivery_image, // 배송된 물품의 사진...(차후 설계하자...) // is_payment // 결제관련 여부 파악 (이것도 차후로...) } = req.body; let note = new OrderNote({ 'orderer.name': orderer_name.trim(), 'orderer.phone': orderer_phone, 'orderer.id': orderer_id, 'receiver.name': receiver_name.trim(), 'receiver.phone': receiver_phone, 'delivery.category': delivery_category, 'delivery.price': delivery_price, 'delivery.date': new Date(delivery_date), 'delivery.address': delivery_address, 'delivery.text': delivery_text, // 'delivery.image': delivery_image, 'memo': memo // 'is_payment': is_payment }); note.save( (err) => { if (err) throw err; return res.json({ success: true, id: note._id }); }); }); /* GET /api/note 모든 장부들 조회 ERROR CODES 1 : PERMISSION DENIED */ router.get('/', (req, res) => { if (typeof req.session.loginInfo === 'undefined') { return res.status(401).json({ error: 'PERMISSION DENIED', code: 1 }); } // 보여주고 싶은 field를 설정 const projection = { '_id': 1, 'orderer.name': 1, 'receiver.name': 1, 'delivery.category': 1, 'delivery.price': 1, 'delivery.address': 1, 'delivery.date': 1, // 'delivery.image': 1, 'is_payment': 1 // 'memo': 1 }; OrderNote.find({}, projection) .sort({'delivery.date': -1}) .exec( (err, notes) => { if (err) throw err; return res.json({ success: true, data: notes }); }); }); /* GET /api/note/today 특정 장부를 조회 ERROR CODES 2 : PERMISSION DENIED 3 : NO RESOURCE */ router.get('/today', (req, res) => { if (typeof req.session.loginInfo === 'undefined') { return res.status(401).json({ error: 'PERMISSION DENIED', code: 2 }); } const today = moment(); today.hour(1).minute(0); const tomorrow = moment(today).add(1, 'day'); tomorrow.hour(0).minute(0); OrderNote .find({ 'delivery.date': { $gte: today.toDate(), $lt: tomorrow.toDate() } }) .sort({ 'delivery.date': -1 }) .exec((err, notes) => { if (err) throw err; if (notes.length === 0) { return res.status(400).json({ error: 'NO RESOURCE', code: 3 }); } return res.json({ data: notes }); }); }); /* GET /api/note/search/:searchTxt 특정 장부를 조회 ERROR CODES 2 : PERMISSION DENIED */ router.get('/search/:searchTxt', (req, res) => { if (typeof req.session.loginInfo === 'undefined') { return res.status(401).json({ error: 'PERMISSION DENIED', code: 2 }); } const searchTxt = decodeURIComponent(req.params.searchTxt); OrderNote .find({ $or: [ {'orderer.name': new RegExp(searchTxt, 'i')}, {'orderer.phone': new RegExp(searchTxt, 'i')}, {'receiver.name': new RegExp(searchTxt, 'i')}, {'receiver.phone': new RegExp(searchTxt, 'i')}, {'delivery.address': new RegExp(searchTxt, 'i')}, {'delivery.text': new RegExp(searchTxt, 'i')}, {'memo': new RegExp(searchTxt, 'i')} ] }) .sort({'delivery.date': -1}) .exec( (err, notes) => { if (err) throw err; return res.json({ data: notes }); }); }); /* GET /api/note/:id 특정 장부를 조회 ERROR CODES 1 : INVALID ID 2 : PERMISSION DENIED 3 : NO RESOURCE */ router.get('/:id', (req, res) => { if (typeof req.session.loginInfo === 'undefined') { return res.status(401).json({ error: 'PERMISSION DENIED', code: 2 }); } if (!mongoose.Types.ObjectId.isValid(req.params.id)) { return res.status(400).json({ error: 'INVALID ID', code: 1 }); } OrderNote.findById(req.params.id, (err, note) => { if (err) throw err; if (!note) { return res.status(400).json({ error: 'NO RESOURCE', code: 3 }); } }); }); export default router;
날짜검색에 의한 API 변경
daily-frontend/server/src/routes/note.js
날짜검색에 의한 API 변경
<ide><path>aily-frontend/server/src/routes/note.js <ide> <ide> const searchTxt = decodeURIComponent(req.params.searchTxt); <ide> <del> OrderNote <del> .find({ <add> let condition = null; <add> <add> // 찾고자 하는 날짜로 검색 <add> if (searchTxt.indexOf('-') !== -1) { <add> const dateArray = []; <add> searchTxt.split('-').forEach( (d) => { <add> dateArray.push(parseInt(d, 10)); <add> }); <add> <add> condition = { <add> 'delivery.date': { <add> $gte: new Date(searchTxt), <add> $lt: new Date(dateArray[0], dateArray[1]-1, dateArray[2], 23, 0, 0) <add> } <add> }; <add> } else { // 찾고자 하는 검색어로 검색 <add> condition = { <ide> $or: [ <ide> {'orderer.name': new RegExp(searchTxt, 'i')}, <ide> {'orderer.phone': new RegExp(searchTxt, 'i')}, <ide> {'delivery.text': new RegExp(searchTxt, 'i')}, <ide> {'memo': new RegExp(searchTxt, 'i')} <ide> ] <del> }) <add> }; <add> } <add> <add> OrderNote <add> .find(condition) <ide> .sort({'delivery.date': -1}) <ide> .exec( (err, notes) => { <ide> if (err) throw err;
Java
bsd-3-clause
error: pathspec 'SourceCode/ILIT/AndroidApp/IndicKeyboard/app/src/main/java/org/buildmlearn/indickeyboard/ImeUtilities.java' did not match any file(s) known to git
00738598ced004c79c042dd05d2e0ef0ce736dfe
1
BuildmLearn/Indic-Language-Input-Tool-ILIT
package org.buildmlearn.indickeyboard; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Will have all the Utility methods for IME & Subtypes */ public class ImeUtilities { private static Map<String,String> languageMap=createLanguageMap(); private static Map<String,String> createLanguageMap() { HashMap<String, String> map = new HashMap<String, String>(); map.put("hi_IN","hindi"); map.put("gu_IN","gujarati"); //Similarly will add all the languages return Collections.unmodifiableMap(map); } public static String getLanguage(String code) { String lang=languageMap.get(code); if(lang==null) { //Value not found lang="hindi"; //default } return lang; } }
SourceCode/ILIT/AndroidApp/IndicKeyboard/app/src/main/java/org/buildmlearn/indickeyboard/ImeUtilities.java
Added a utility class for IME&Subtype related functions
SourceCode/ILIT/AndroidApp/IndicKeyboard/app/src/main/java/org/buildmlearn/indickeyboard/ImeUtilities.java
Added a utility class for IME&Subtype related functions
<ide><path>ourceCode/ILIT/AndroidApp/IndicKeyboard/app/src/main/java/org/buildmlearn/indickeyboard/ImeUtilities.java <add>package org.buildmlearn.indickeyboard; <add> <add>import java.util.Collections; <add>import java.util.HashMap; <add>import java.util.Map; <add> <add>/** <add> * Will have all the Utility methods for IME & Subtypes <add> */ <add>public class ImeUtilities { <add> <add> private static Map<String,String> languageMap=createLanguageMap(); <add> <add> private static Map<String,String> createLanguageMap() <add> { <add> HashMap<String, String> map = new HashMap<String, String>(); <add> map.put("hi_IN","hindi"); <add> map.put("gu_IN","gujarati"); <add> <add> //Similarly will add all the languages <add> return Collections.unmodifiableMap(map); <add> } <add> <add> public static String getLanguage(String code) <add> { <add> String lang=languageMap.get(code); <add> if(lang==null) <add> { <add> //Value not found <add> lang="hindi"; //default <add> } <add> return lang; <add> } <add> <add> <add>}
JavaScript
mit
a7339094097c73729298c00bf46e968b7c313f40
0
mark-rushakoff/influxdb,li-ang/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdata/influxdb,influxdb/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,nooproblem/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,influxdb/influxdb
import React from 'react' import PropTypes from 'prop-types' import _ from 'lodash' import classnames from 'classnames' import RoleEditingRow from 'src/admin/components/RoleEditingRow' import MultiSelectDropdown from 'shared/components/MultiSelectDropdown' import ConfirmOrCancel from 'shared/components/ConfirmOrCancel' import ConfirmButton from 'shared/components/ConfirmButton' import {ROLES_TABLE} from 'src/admin/constants/tableSizing' const RoleRow = ({ role: {name: roleName, permissions, users = []}, role, allUsers, allPermissions, isNew, isEditing, onEdit, onSave, onCancel, onDelete, onUpdateRoleUsers, onUpdateRolePermissions, }) => { function handleUpdateUsers(usrs) { onUpdateRoleUsers(role, usrs) } function handleUpdatePermissions(allowed) { onUpdateRolePermissions(role, [ {scope: 'all', allowed: allowed.map(({name}) => name)}, ]) } const perms = _.get(permissions, ['0', 'allowed'], []) if (isEditing) { return ( <tr className="admin-table--edit-row"> <RoleEditingRow role={role} onEdit={onEdit} onSave={onSave} isNew={isNew} /> <td className="admin-table--left-offset">--</td> <td className="admin-table--left-offset">--</td> <td className="text-right" style={{width: `${ROLES_TABLE.colDelete}px`}} > <ConfirmOrCancel item={role} onConfirm={onSave} onCancel={onCancel} buttonSize="btn-xs" /> </td> </tr> ) } const wrappedDelete = () => { onDelete(role) } return ( <tr> <td style={{width: `${ROLES_TABLE.colName}px`}}>{roleName}</td> <td> {allPermissions && allPermissions.length ? ( <MultiSelectDropdown items={allPermissions.map(name => ({name}))} selectedItems={perms.map(name => ({name}))} label={perms.length ? '' : 'Select Permissions'} onApply={handleUpdatePermissions} buttonSize="btn-xs" buttonColor="btn-primary" customClass={classnames(`dropdown-${ROLES_TABLE.colPermissions}`, { 'admin-table--multi-select-empty': !permissions.length, })} resetStateOnReceiveProps={false} /> ) : null} </td> <td> {allUsers && allUsers.length ? ( <MultiSelectDropdown items={allUsers} selectedItems={users} label={users.length ? '' : 'Select Users'} onApply={handleUpdateUsers} buttonSize="btn-xs" buttonColor="btn-primary" customClass={classnames(`dropdown-${ROLES_TABLE.colUsers}`, { 'admin-table--multi-select-empty': !users.length, })} resetStateOnReceiveProps={false} /> ) : null} </td> <td className="text-right"> <ConfirmButton customClass="table--show-on-row-hover" size="btn-xs" type="btn-danger" text="Delete Role" confirmAction={wrappedDelete} /> </td> </tr> ) } const {arrayOf, bool, func, shape, string} = PropTypes RoleRow.propTypes = { role: shape({ name: string, permissions: arrayOf( shape({ name: string, }) ), users: arrayOf( shape({ name: string, }) ), }).isRequired, isNew: bool, isEditing: bool, onCancel: func, onEdit: func, onSave: func, onDelete: func.isRequired, allUsers: arrayOf(shape()), allPermissions: arrayOf(string), onUpdateRoleUsers: func.isRequired, onUpdateRolePermissions: func.isRequired, } export default RoleRow
ui/src/admin/components/RoleRow.js
import React from 'react' import PropTypes from 'prop-types' import _ from 'lodash' import classnames from 'classnames' import RoleEditingRow from 'src/admin/components/RoleEditingRow' import MultiSelectDropdown from 'shared/components/MultiSelectDropdown' import ConfirmOrCancel from 'shared/components/ConfirmOrCancel' import DeleteConfirmTableCell from 'shared/components/DeleteConfirmTableCell' import {ROLES_TABLE} from 'src/admin/constants/tableSizing' const RoleRow = ({ role: {name: roleName, permissions, users = []}, role, allUsers, allPermissions, isNew, isEditing, onEdit, onSave, onCancel, onDelete, onUpdateRoleUsers, onUpdateRolePermissions, }) => { function handleUpdateUsers(usrs) { onUpdateRoleUsers(role, usrs) } function handleUpdatePermissions(allowed) { onUpdateRolePermissions(role, [ {scope: 'all', allowed: allowed.map(({name}) => name)}, ]) } const perms = _.get(permissions, ['0', 'allowed'], []) if (isEditing) { return ( <tr className="admin-table--edit-row"> <RoleEditingRow role={role} onEdit={onEdit} onSave={onSave} isNew={isNew} /> <td className="admin-table--left-offset">--</td> <td className="admin-table--left-offset">--</td> <td className="text-right" style={{width: `${ROLES_TABLE.colDelete}px`}} > <ConfirmOrCancel item={role} onConfirm={onSave} onCancel={onCancel} buttonSize="btn-xs" /> </td> </tr> ) } return ( <tr> <td style={{width: `${ROLES_TABLE.colName}px`}}>{roleName}</td> <td> {allPermissions && allPermissions.length ? ( <MultiSelectDropdown items={allPermissions.map(name => ({name}))} selectedItems={perms.map(name => ({name}))} label={perms.length ? '' : 'Select Permissions'} onApply={handleUpdatePermissions} buttonSize="btn-xs" buttonColor="btn-primary" customClass={classnames(`dropdown-${ROLES_TABLE.colPermissions}`, { 'admin-table--multi-select-empty': !permissions.length, })} resetStateOnReceiveProps={false} /> ) : null} </td> <td> {allUsers && allUsers.length ? ( <MultiSelectDropdown items={allUsers} selectedItems={users} label={users.length ? '' : 'Select Users'} onApply={handleUpdateUsers} buttonSize="btn-xs" buttonColor="btn-primary" customClass={classnames(`dropdown-${ROLES_TABLE.colUsers}`, { 'admin-table--multi-select-empty': !users.length, })} resetStateOnReceiveProps={false} /> ) : null} </td> <DeleteConfirmTableCell onDelete={onDelete} item={role} buttonSize="btn-xs" /> </tr> ) } const {arrayOf, bool, func, shape, string} = PropTypes RoleRow.propTypes = { role: shape({ name: string, permissions: arrayOf( shape({ name: string, }) ), users: arrayOf( shape({ name: string, }) ), }).isRequired, isNew: bool, isEditing: bool, onCancel: func, onEdit: func, onSave: func, onDelete: func.isRequired, allUsers: arrayOf(shape()), allPermissions: arrayOf(string), onUpdateRoleUsers: func.isRequired, onUpdateRolePermissions: func.isRequired, } export default RoleRow
Refactor influxdb roles admin tables to use Confirm Button
ui/src/admin/components/RoleRow.js
Refactor influxdb roles admin tables to use Confirm Button
<ide><path>i/src/admin/components/RoleRow.js <ide> import RoleEditingRow from 'src/admin/components/RoleEditingRow' <ide> import MultiSelectDropdown from 'shared/components/MultiSelectDropdown' <ide> import ConfirmOrCancel from 'shared/components/ConfirmOrCancel' <del>import DeleteConfirmTableCell from 'shared/components/DeleteConfirmTableCell' <add>import ConfirmButton from 'shared/components/ConfirmButton' <ide> import {ROLES_TABLE} from 'src/admin/constants/tableSizing' <ide> <ide> const RoleRow = ({ <ide> ) <ide> } <ide> <add> const wrappedDelete = () => { <add> onDelete(role) <add> } <add> <ide> return ( <ide> <tr> <ide> <td style={{width: `${ROLES_TABLE.colName}px`}}>{roleName}</td> <ide> /> <ide> ) : null} <ide> </td> <del> <DeleteConfirmTableCell <del> onDelete={onDelete} <del> item={role} <del> buttonSize="btn-xs" <del> /> <add> <td className="text-right"> <add> <ConfirmButton <add> customClass="table--show-on-row-hover" <add> size="btn-xs" <add> type="btn-danger" <add> text="Delete Role" <add> confirmAction={wrappedDelete} <add> /> <add> </td> <ide> </tr> <ide> ) <ide> }
JavaScript
bsd-2-clause
e7f8a858364259d61a8a1722e5c01e5aca673051
0
hyperknot/Leaflet,elfalem/Leaflet,DrillingInfo/Leaflet,rlugojr/Leaflet,gabrielpconceicao/frontend-asset-leaflet,pzdz/Leaflet,ismyrnow/Leaflet,northerneyes/Leaflet,iamjonbradley/Leaflet,AndBicScadMedia/Leaflet,tormi/Leaflet,iZucken/Leaflet,geoloep/Leaflet,waeltken/Leaflet,nathancahill/Leaflet,webmechanicx/Leaflet,akrzyzanowskino/TeamSE,msiadak/Leaflet,billybonz1/Leaflet,frogcat/Leaflet,prashen/Leaflet,olafurr/Leaflet,alex2wong/Leaflet,Andrey-Pavlov/Leaflet,2gis/Leaflet,psicomante/Leaflet,beni55/Leaflet,kumy/Leaflet,msokk/Leaflet,dhootha/Leaflet,tormi/Leaflet,grahamthompson/Leaflet,pakro/Leaflet,RLRR/Leaflet,CorainChicago/Leaflet,juliensoret/Leaflet,snkashis/Leaflet,sellonen/Leaflet,lee101/Leaflet,DrillingInfo/Leaflet,taraszerebecki/Leaflet,jblarsen/Leaflet,Mark-Wood/Leaflet,bolshoibooze/Leaflet,beni55/Leaflet,tbassett44/Leaflet,davidlukerice/Leaflet,pzdz/Leaflet,tormi/Leaflet,andrewmartini/Leaflet,AP-whitehat/Leaflet,Trufi/Leaflet,CapeSepias/Leaflet,akrzyzanowskino/TeamSE,kjell/Leaflet,klaftertief/Leaflet,geoloep/Leaflet,mstahv/Leaflet,snkashis/Leaflet,dhootha/Leaflet,jmutua2015/Leaflet,Neorth/Leaflet,patrickarlt/Leaflet,Ossehoht/Leaflet,nkovacs/Leaflet,alex2wong/Leaflet,akauppi/Leaflet,billybonz1/Leaflet,nycitt/Leaflet,w8r/Leaflet,nycitt/Leaflet,Neorth/Leaflet,cartant/Leaflet,brunocasanova/frontend-asset-leaflet,frafra/ProntoSoccorsoLiguria,nycitt/Leaflet,andrewmartini/Leaflet,Andrey-Pavlov/Leaflet,fab1an/Leaflet,msokk/Leaflet,brunocasanova/frontend-asset-leaflet,sisou/Leaflet,lee101/Leaflet,olafurr/Leaflet,codeator/Leaflet,sellonen/Leaflet,fab1an/Leaflet,wrrnwng/Leaflet,yohanboniface/Leaflet,MuellerMatthew/Leaflet,northerneyes/Leaflet,psicomante/Leaflet,psicomante/Leaflet,msokk/Leaflet,mourner/Leaflet,nikhildhamsaniya/Leaflet,RyanHickman/Leaflet,grahamthompson/Leaflet,Andrey-Pavlov/Leaflet,fredericksilva/Leaflet,tbassett44/Leaflet,2gis/Leaflet,AndBicScadMedia/Leaflet,javimolla/Leaflet,olafurr/Leaflet,fredericksilva/Leaflet,tsantacruz/RotationalMarker,starsolaris/Leaflet,Leaflet/Leaflet,starsolaris/Leaflet,scaddenp/Leaflet,Mark-Wood/Leaflet,wancharle/Leaflet,stefanocudini/Leaflet,elkingtonmcb/Leaflet,elfalem/Leaflet,wancharle/Leaflet,iZucken/Leaflet,wancharle/Leaflet,tsantacruz/RotationalMarker,snkashis/Leaflet,litnerdy/Leaflet,AP-whitehat/Leaflet,cmulders/Leaflet,huangsong/Leaflet,waeltken/Leaflet,CorainChicago/Leaflet,waeltken/Leaflet,jmutua2015/Leaflet,brah/Leaflet,brah/Leaflet,beni55/Leaflet,Trufi/Leaflet,iOffice/Leaflet,iZucken/Leaflet,iOffice/Leaflet,thalesfsp/Leaflet,RLRR/Leaflet,2gis/Leaflet,thalesfsp/Leaflet,codeator/Leaflet,davidlukerice/Leaflet,sambernet/Leaflet,danzel/Leaflet,twoubt/Leaflet,jmutua2015/Leaflet,bolshoibooze/Leaflet,mstahv/Leaflet,brah/Leaflet,RobertoMalatesta/Leaflet,RyanHickman/Leaflet,prashen/Leaflet,prashen/Leaflet,patrickarlt/Leaflet,AndBicScadMedia/Leaflet,elkingtonmcb/Leaflet,MuellerMatthew/Leaflet,huangsong/Leaflet,tomnod/Leaflet,caiiiycuk/Leaflet,mstahv/Leaflet,eriksjaastad/Leaflet,iamjonbradley/Leaflet,RobertoMalatesta/Leaflet,Fil/Leaflet,sambernet/Leaflet,Fil/Leaflet,tomnod/Leaflet,klaftertief/Leaflet,CorainChicago/Leaflet,nikhildhamsaniya/Leaflet,sellonen/Leaflet,sisou/Leaflet,taraszerebecki/Leaflet,Jakobud/Leaflet,mbrukman/Leaflet,iamjonbradley/Leaflet,akauppi/Leaflet,devjoseluis/Leaflet,davojta/Leaflet,wpf500/Leaflet,tsantacruz/RotationalMarker,CloudMade/Leaflet,grahamthompson/Leaflet,cmulders/Leaflet,bbecquet/Leaflet,mbrukman/Leaflet,perliedman/Leaflet,cartant/Leaflet,Neorth/Leaflet,devjoseluis/Leaflet,wpf500/Leaflet,kumy/Leaflet,taraszerebecki/Leaflet,webmechanicx/Leaflet,jaropolk2/Leaflet,msiadak/Leaflet,gabrielpconceicao/frontend-asset-leaflet,fillerwriter/Leaflet,Ossehoht/Leaflet,MuellerMatthew/Leaflet,mediasuitenz/Leaflet,jasonoverland/Leaflet,nkovacs/Leaflet,huangsong/Leaflet,devjoseluis/Leaflet,Ubisense/Leaflet,scaddenp/Leaflet,Leaflet/Leaflet,starsolaris/Leaflet,stefanocudini/Leaflet,mourner/Leaflet,gabrielpconceicao/frontend-asset-leaflet,yohanboniface/Leaflet,fillerwriter/Leaflet,akrzyzanowskino/TeamSE,RobertoMalatesta/Leaflet,rlugojr/Leaflet,srdavis/leaflet-template,litnerdy/Leaflet,bolshoibooze/Leaflet,sisou/Leaflet,Trufi/Leaflet,juliensoret/Leaflet,tbassett44/Leaflet,caiiiycuk/Leaflet,mediasuitenz/Leaflet,yohanboniface/Leaflet,jblarsen/Leaflet,mourner/Leaflet,klaftertief/Leaflet,kumy/Leaflet,twoubt/Leaflet,billybonz1/Leaflet,tyrasd/Leaflet,frafra/ProntoSoccorsoLiguria,Srikanth4/Leaflet,pzdz/Leaflet,thalesfsp/Leaflet,w8r/Leaflet,hyperknot/Leaflet,caiiiycuk/Leaflet,kjell/Leaflet,moklick/Leaflet,che603000/Leaflet,eriksjaastad/Leaflet,webmechanicx/Leaflet,tomnod/Leaflet,Ubisense/Leaflet,jasonoverland/Leaflet,msiadak/Leaflet,davojta/Leaflet,Leaflet/Leaflet,davidlukerice/Leaflet,fillerwriter/Leaflet,AP-whitehat/Leaflet,frogcat/Leaflet,Jakobud/Leaflet,Srikanth4/Leaflet,pakro/Leaflet,wrrnwng/Leaflet,dhootha/Leaflet,javimolla/Leaflet,elkingtonmcb/Leaflet,CapeSepias/Leaflet,eriksjaastad/Leaflet,lee101/Leaflet,wpf500/Leaflet,cmulders/Leaflet,mediasuitenz/Leaflet,jasonoverland/Leaflet,brunocasanova/frontend-asset-leaflet,bbecquet/Leaflet,nvoron23/Leaflet,fab1an/Leaflet,sambernet/Leaflet,che603000/Leaflet,nikhildhamsaniya/Leaflet,w8r/Leaflet,fredericksilva/Leaflet,scaddenp/Leaflet,litnerdy/Leaflet,lizardtechblog/Leaflet,RyanHickman/Leaflet,rlugojr/Leaflet,mbrukman/Leaflet,wrrnwng/Leaflet,javimolla/Leaflet,cartant/Leaflet,azimux/Leaflet,Fil/Leaflet,nathancahill/Leaflet,frogcat/Leaflet,Srikanth4/Leaflet,iOffice/Leaflet,RLRR/Leaflet,akauppi/Leaflet,bbecquet/Leaflet,codeator/Leaflet,davidjb/Leaflet,stefanocudini/Leaflet,davojta/Leaflet,andrewmartini/Leaflet,nvoron23/Leaflet,Ubisense/Leaflet,Jakobud/Leaflet,Ossehoht/Leaflet,pakro/Leaflet,jblarsen/Leaflet,geoloep/Leaflet,nathancahill/Leaflet,twoubt/Leaflet,alex2wong/Leaflet,hyperknot/Leaflet,CapeSepias/Leaflet,elfalem/Leaflet
L.Map.mergeOptions({ zoomAnimation: L.DomUtil.TRANSITION && !L.Browser.android23 && !L.Browser.mobileOpera }); L.Map.addInitHook(function () { L.DomEvent.on(this._mapPane, L.Transition.END, this._catchTransitionEnd, this); }); L.Map.include(!L.DomUtil.TRANSITION ? {} : { _zoomToIfClose: function (center, zoom) { if (this._animatingZoom) { return true; } if (!this.options.zoomAnimation) { return false; } var scale = this.getZoomScale(zoom), offset = this._getCenterOffset(center).divideBy(1 - 1 / scale); // if offset does not exceed half of the view if (!this._offsetIsWithinView(offset, 1)) { return false; } L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim'); this .fire('movestart') .fire('zoomstart'); this._prepareTileBg(); this.fire('zoomanim', { center: center, zoom: zoom }); var origin = this._getCenterLayerPoint().add(offset); this._runAnimation(center, zoom, scale, origin); return true; }, _catchTransitionEnd: function (e) { if (this._animatingZoom) { this._onZoomTransitionEnd(); } }, _runAnimation: function (center, zoom, scale, origin, backwardsTransform) { this._animatingZoom = true; this._animateToCenter = center; this._animateToZoom = zoom; var transform = L.DomUtil.TRANSFORM, tileBg = this._tileBg; clearTimeout(this._clearTileBgTimer); //dumb FireFox hack, I have no idea why this magic zero translate fixes the scale transition problem if (L.Browser.gecko || window.opera) { tileBg.style[transform] += ' translate(0,0)'; } var scaleStr = L.DomUtil.getScaleString(scale, origin); L.Util.falseFn(tileBg.offsetWidth); //hack to make sure transform is updated before running animation tileBg.style[transform] = backwardsTransform ? tileBg.style[transform] + ' ' + scaleStr : scaleStr + ' ' + tileBg.style[transform]; }, _prepareTileBg: function () { var tilePane = this._tilePane, tileBg = this._tileBg; // If foreground layer doesn't have many tiles but bg layer does, keep the existing bg layer and just zoom it some more if (tileBg && this._getLoadedTilesPercentage(tileBg) > 0.5 && this._getLoadedTilesPercentage(tilePane) < 0.5) { tilePane.style.visibility = 'hidden'; tilePane.empty = true; this._stopLoadingImages(tilePane); return; } if (!tileBg) { tileBg = this._tileBg = this._createPane('leaflet-tile-pane', this._mapPane); tileBg.style.zIndex = 1; } // prepare the background pane to become the main tile pane tileBg.style[L.DomUtil.TRANSFORM] = ''; tileBg.style.visibility = 'hidden'; // tells tile layers to reinitialize their containers tileBg.empty = true; //new FG tilePane.empty = false; //new BG //Switch out the current layer to be the new bg layer (And vice-versa) this._tilePane = this._panes.tilePane = tileBg; var newTileBg = this._tileBg = tilePane; L.DomUtil.addClass(newTileBg, 'leaflet-zoom-animated'); this._stopLoadingImages(newTileBg); }, _getLoadedTilesPercentage: function (container) { var tiles = container.getElementsByTagName('img'), i, len, count = 0; for (i = 0, len = tiles.length; i < len; i++) { if (tiles[i].complete) { count++; } } return count / len; }, // stops loading all tiles in the background layer _stopLoadingImages: function (container) { var tiles = Array.prototype.slice.call(container.getElementsByTagName('img')), i, len, tile; for (i = 0, len = tiles.length; i < len; i++) { tile = tiles[i]; if (!tile.complete) { tile.onload = L.Util.falseFn; tile.onerror = L.Util.falseFn; tile.src = L.Util.emptyImageUrl; tile.parentNode.removeChild(tile); } } }, _onZoomTransitionEnd: function () { this._restoreTileFront(); L.Util.falseFn(this._tileBg.offsetWidth); // force reflow this._resetView(this._animateToCenter, this._animateToZoom, true, true); L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim'); this._animatingZoom = false; }, _restoreTileFront: function () { this._tilePane.innerHTML = ''; this._tilePane.style.visibility = ''; this._tilePane.style.zIndex = 2; this._tileBg.style.zIndex = 1; }, _clearTileBg: function () { if (!this._animatingZoom && !this.touchZoom._zooming) { this._tileBg.innerHTML = ''; } } });
src/map/anim/Map.ZoomAnimation.js
L.Map.mergeOptions({ zoomAnimation: L.DomUtil.TRANSITION && !L.Browser.android23 && !L.Browser.mobileOpera }); L.Map.include(!L.DomUtil.TRANSITION ? {} : { _zoomToIfClose: function (center, zoom) { if (this._animatingZoom) { return true; } if (!this.options.zoomAnimation) { return false; } var scale = this.getZoomScale(zoom), offset = this._getCenterOffset(center).divideBy(1 - 1 / scale); // if offset does not exceed half of the view if (!this._offsetIsWithinView(offset, 1)) { return false; } L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim'); this .fire('movestart') .fire('zoomstart'); this._prepareTileBg(); this.fire('zoomanim', { center: center, zoom: zoom }); var origin = this._getCenterLayerPoint().add(offset); this._runAnimation(center, zoom, scale, origin); return true; }, _runAnimation: function (center, zoom, scale, origin, backwardsTransform) { this._animatingZoom = true; this._animateToCenter = center; this._animateToZoom = zoom; var transform = L.DomUtil.TRANSFORM, tileBg = this._tileBg; clearTimeout(this._clearTileBgTimer); //dumb FireFox hack, I have no idea why this magic zero translate fixes the scale transition problem if (L.Browser.gecko || window.opera) { tileBg.style[transform] += ' translate(0,0)'; } var scaleStr = L.DomUtil.getScaleString(scale, origin); L.Util.falseFn(tileBg.offsetWidth); //hack to make sure transform is updated before running animation var options = {}; if (backwardsTransform) { options[transform] = tileBg.style[transform] + ' ' + scaleStr; } else { options[transform] = scaleStr + ' ' + tileBg.style[transform]; } tileBg.transition.run(options); }, _prepareTileBg: function () { var tilePane = this._tilePane, tileBg = this._tileBg; // If foreground layer doesn't have many tiles but bg layer does, keep the existing bg layer and just zoom it some more if (tileBg && this._getLoadedTilesPercentage(tileBg) > 0.5 && this._getLoadedTilesPercentage(tilePane) < 0.5) { tilePane.style.visibility = 'hidden'; tilePane.empty = true; this._stopLoadingImages(tilePane); return; } if (!tileBg) { tileBg = this._tileBg = this._createPane('leaflet-tile-pane', this._mapPane); tileBg.style.zIndex = 1; } // prepare the background pane to become the main tile pane tileBg.style[L.DomUtil.TRANSFORM] = ''; tileBg.style.visibility = 'hidden'; // tells tile layers to reinitialize their containers tileBg.empty = true; //new FG tilePane.empty = false; //new BG //Switch out the current layer to be the new bg layer (And vice-versa) this._tilePane = this._panes.tilePane = tileBg; var newTileBg = this._tileBg = tilePane; if (!newTileBg.transition) { // TODO move to Map options newTileBg.transition = new L.Transition(newTileBg, { duration: 0.25, easing: 'cubic-bezier(0.25,0.1,0.25,0.75)' }); newTileBg.transition.on('end', this._onZoomTransitionEnd, this); } this._stopLoadingImages(newTileBg); }, _getLoadedTilesPercentage: function (container) { var tiles = container.getElementsByTagName('img'), i, len, count = 0; for (i = 0, len = tiles.length; i < len; i++) { if (tiles[i].complete) { count++; } } return count / len; }, // stops loading all tiles in the background layer _stopLoadingImages: function (container) { var tiles = Array.prototype.slice.call(container.getElementsByTagName('img')), i, len, tile; for (i = 0, len = tiles.length; i < len; i++) { tile = tiles[i]; if (!tile.complete) { tile.onload = L.Util.falseFn; tile.onerror = L.Util.falseFn; tile.src = L.Util.emptyImageUrl; tile.parentNode.removeChild(tile); } } }, _onZoomTransitionEnd: function () { this._restoreTileFront(); L.Util.falseFn(this._tileBg.offsetWidth); // force reflow this._resetView(this._animateToCenter, this._animateToZoom, true, true); L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim'); this._animatingZoom = false; }, _restoreTileFront: function () { this._tilePane.innerHTML = ''; this._tilePane.style.visibility = ''; this._tilePane.style.zIndex = 2; this._tileBg.style.zIndex = 1; }, _clearTileBg: function () { if (!this._animatingZoom && !this.touchZoom._zooming) { this._tileBg.innerHTML = ''; } } });
Move tile layer transition to CSS, detect zoom transion end globally
src/map/anim/Map.ZoomAnimation.js
Move tile layer transition to CSS, detect zoom transion end globally
<ide><path>rc/map/anim/Map.ZoomAnimation.js <ide> L.Map.mergeOptions({ <ide> zoomAnimation: L.DomUtil.TRANSITION && !L.Browser.android23 && !L.Browser.mobileOpera <add>}); <add> <add>L.Map.addInitHook(function () { <add> L.DomEvent.on(this._mapPane, L.Transition.END, this._catchTransitionEnd, this); <ide> }); <ide> <ide> L.Map.include(!L.DomUtil.TRANSITION ? {} : { <ide> return true; <ide> }, <ide> <add> _catchTransitionEnd: function (e) { <add> if (this._animatingZoom) { <add> this._onZoomTransitionEnd(); <add> } <add> }, <ide> <ide> _runAnimation: function (center, zoom, scale, origin, backwardsTransform) { <ide> this._animatingZoom = true; <ide> <ide> L.Util.falseFn(tileBg.offsetWidth); //hack to make sure transform is updated before running animation <ide> <del> var options = {}; <del> if (backwardsTransform) { <del> options[transform] = tileBg.style[transform] + ' ' + scaleStr; <del> } else { <del> options[transform] = scaleStr + ' ' + tileBg.style[transform]; <del> } <del> <del> tileBg.transition.run(options); <add> tileBg.style[transform] = backwardsTransform ? <add> tileBg.style[transform] + ' ' + scaleStr : <add> scaleStr + ' ' + tileBg.style[transform]; <ide> }, <ide> <ide> _prepareTileBg: function () { <ide> this._tilePane = this._panes.tilePane = tileBg; <ide> var newTileBg = this._tileBg = tilePane; <ide> <del> if (!newTileBg.transition) { <del> // TODO move to Map options <del> newTileBg.transition = new L.Transition(newTileBg, { <del> duration: 0.25, <del> easing: 'cubic-bezier(0.25,0.1,0.25,0.75)' <del> }); <del> newTileBg.transition.on('end', this._onZoomTransitionEnd, this); <del> } <add> L.DomUtil.addClass(newTileBg, 'leaflet-zoom-animated'); <ide> <ide> this._stopLoadingImages(newTileBg); <ide> }, <ide> <ide> _onZoomTransitionEnd: function () { <ide> this._restoreTileFront(); <del> <ide> L.Util.falseFn(this._tileBg.offsetWidth); // force reflow <ide> this._resetView(this._animateToCenter, this._animateToZoom, true, true); <ide>
JavaScript
mit
766ffb64a582cb5fca7d3733f69fcf9f50af7bb7
0
jdh11235/JSchunks,jdh11235/JSchunks
function fib( n ) { return F(n)[n]; } function generateF( n ){ var F = [0, 1]; for( i = 2; i <= n; i++ ){ F[i] = F[i - 2] + F[i - 1] } return F; }
fibonacci.js
function fib( n ) { return F(n)[n]; } function F( n ){ var F = [0, 1]; for( i = 2; i <= n; i++ ){ F[i] = F[i - 2] + F[i - 1] } return F; }
F generation clarity
fibonacci.js
F generation clarity
<ide><path>ibonacci.js <ide> return F(n)[n]; <ide> } <ide> <del>function F( n ){ <add>function generateF( n ){ <ide> var F = [0, 1]; <ide> <ide> for( i = 2; i <= n; i++ ){
Java
apache-2.0
9e5944d0a7a12cc49b655bb059c80d792da2860f
0
michpetrov/hal.next,hpehl/hal.next,michpetrov/hal.next,hal/hal.next,hal/hal.next,hal/hal.next,hpehl/hal.next,hpehl/hal.next,hpehl/hal.next,michpetrov/hal.next,michpetrov/hal.next,hal/hal.next
/* * Copyright 2015-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.hal.client.runtime.server; import javax.inject.Inject; import elemental2.dom.HTMLButtonElement; import elemental2.dom.HTMLElement; import org.jboss.gwt.elemento.core.Elements; import org.jboss.hal.ballroom.Button; import org.jboss.hal.ballroom.VerticalNavigation; import org.jboss.hal.ballroom.form.Form; import org.jboss.hal.core.mbui.form.ModelNodeForm; import org.jboss.hal.core.mvp.HalViewImpl; import org.jboss.hal.dmr.ModelNode; import org.jboss.hal.meta.Metadata; import org.jboss.hal.meta.MetadataRegistry; import org.jboss.hal.resources.Ids; import org.jboss.hal.resources.Resources; import static org.jboss.gwt.elemento.core.Elements.*; import static org.jboss.gwt.elemento.core.EventType.bind; import static org.jboss.gwt.elemento.core.EventType.click; import static org.jboss.hal.ballroom.LayoutBuilder.column; import static org.jboss.hal.ballroom.LayoutBuilder.row; import static org.jboss.hal.client.runtime.server.StandaloneServerPresenter.HTTP_INTERFACE_TEMPLATE; import static org.jboss.hal.client.runtime.server.StandaloneServerPresenter.ROOT_TEMPLATE; import static org.jboss.hal.dmr.ModelDescriptionConstants.*; import static org.jboss.hal.resources.CSS.pfIcon; import static org.jboss.hal.resources.CSS.pullRight; import static org.jboss.hal.resources.Ids.*; public class StandaloneServerView extends HalViewImpl implements StandaloneServerPresenter.MyView { private Form<ModelNode> attributesForm; private Form<ModelNode> httpInterfaceForm; private HTMLButtonElement enableSslButton; private HTMLButtonElement disableSslButton; private StandaloneServerPresenter presenter; @Inject StandaloneServerView(MetadataRegistry metadataRegistry, Resources resources) { VerticalNavigation navigation = new VerticalNavigation(); registerAttachable(navigation); Metadata metadata = metadataRegistry.lookup(ROOT_TEMPLATE); String attributesFormId = Ids.build(Ids.STANDALONE_SERVER_COLUMN, Ids.ATTRIBUTES, FORM); attributesForm = new ModelNodeForm.Builder<>(attributesFormId, metadata) .includeRuntime() .onSave((form, changedValues) -> presenter.save(resources.constants().standaloneServer(), ROOT_TEMPLATE, changedValues)) .prepareReset(form -> presenter.reset(resources.constants().standaloneServer(), ROOT_TEMPLATE, form, metadata)) .unsorted() .build(); // makes no sense to mask name attribute attributesForm.getFormItem(NAME).unmask(); // the following attributes are read-only, set as non required to let user save the form attributesForm.getFormItem(NAMESPACES).setRequired(false); attributesForm.getFormItem(SCHEMA_LOCATIONS).setRequired(false); registerAttachable(attributesForm); HTMLElement attributesElement = section() .add(h(1).textContent(resources.constants().attributes()).get()) .add(p().textContent(metadata.getDescription().getDescription()).get()) .add(attributesForm) .get(); String attributesItemId = Ids.build(Ids.ATTRIBUTES, ITEM); navigation.addPrimary(attributesItemId, resources.constants().configuration(), pfIcon("settings"), attributesElement); String httpTitle = resources.constants().httpManagementInterface(); Metadata httpMetadata = metadataRegistry.lookup(HTTP_INTERFACE_TEMPLATE); String httpId = Ids.build(HTTP_INTERFACE, FORM); httpInterfaceForm = new ModelNodeForm.Builder<>(httpId, httpMetadata) .onSave((form, changedValues) -> presenter.save(httpTitle, HTTP_INTERFACE_TEMPLATE, changedValues)) .prepareReset(form -> presenter.reset(httpTitle, HTTP_INTERFACE_TEMPLATE, form, httpMetadata)) .unsorted() .build(); enableSslButton = button().id(ENABLE_SSL) .textContent(resources.constants().enableSSL()) .css(Button.DEFAULT_CSS, pullRight) .get(); bind(enableSslButton, click, ev -> presenter.launchEnableSSLWizard()); disableSslButton = button().id(DISABLE_SSL) .textContent(resources.constants().disableSSL()) .css(Button.DEFAULT_CSS, pullRight) .get(); bind(disableSslButton, click, ev -> presenter.disableSSLWizard()); HTMLElement httpMgmtItemElement = section() .add(div() .add(h(1).textContent(httpTitle).get()) .add(p().textContent(httpMetadata.getDescription().getDescription()).get()) .add(enableSslButton) .add(disableSslButton)) .add(httpInterfaceForm) .get(); registerAttachable(httpInterfaceForm); navigation.addPrimary(HTTP_INTERFACE_ITEM, resources.constants().httpManagementInterface(), pfIcon("virtual-machine"), httpMgmtItemElement); initElement(row() .add(column() .addAll(navigation.panes()))); } @Override public void updateAttributes(ModelNode attributes) { attributesForm.view(attributes); } @Override public void updateHttpInterface(ModelNode model) { httpInterfaceForm.view(model); boolean isSslEnabled = model.hasDefined(SSL_CONTEXT) && model.get(SSL_CONTEXT).asString() != null; toggleSslButton(isSslEnabled); } private void toggleSslButton(boolean enable) { Elements.setVisible(enableSslButton, !enable); Elements.setVisible(disableSslButton, enable); } @Override public void setPresenter(StandaloneServerPresenter presenter) { this.presenter = presenter; } }
app/src/main/java/org/jboss/hal/client/runtime/server/StandaloneServerView.java
/* * Copyright 2015-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.hal.client.runtime.server; import javax.inject.Inject; import elemental2.dom.HTMLButtonElement; import elemental2.dom.HTMLElement; import org.jboss.gwt.elemento.core.Elements; import org.jboss.hal.ballroom.Button; import org.jboss.hal.ballroom.VerticalNavigation; import org.jboss.hal.ballroom.form.Form; import org.jboss.hal.core.mbui.form.ModelNodeForm; import org.jboss.hal.core.mvp.HalViewImpl; import org.jboss.hal.dmr.ModelNode; import org.jboss.hal.meta.Metadata; import org.jboss.hal.meta.MetadataRegistry; import org.jboss.hal.resources.Ids; import org.jboss.hal.resources.Resources; import static org.jboss.gwt.elemento.core.Elements.*; import static org.jboss.gwt.elemento.core.EventType.bind; import static org.jboss.gwt.elemento.core.EventType.click; import static org.jboss.hal.ballroom.LayoutBuilder.column; import static org.jboss.hal.ballroom.LayoutBuilder.row; import static org.jboss.hal.client.runtime.server.StandaloneServerPresenter.HTTP_INTERFACE_TEMPLATE; import static org.jboss.hal.client.runtime.server.StandaloneServerPresenter.ROOT_TEMPLATE; import static org.jboss.hal.dmr.ModelDescriptionConstants.*; import static org.jboss.hal.resources.CSS.pfIcon; import static org.jboss.hal.resources.CSS.pullRight; import static org.jboss.hal.resources.Ids.*; public class StandaloneServerView extends HalViewImpl implements StandaloneServerPresenter.MyView { private Form<ModelNode> attributesForm; private Form<ModelNode> httpInterfaceForm; private HTMLButtonElement enableSslButton; private HTMLButtonElement disableSslButton; private StandaloneServerPresenter presenter; @Inject StandaloneServerView(MetadataRegistry metadataRegistry, Resources resources) { VerticalNavigation navigation = new VerticalNavigation(); registerAttachable(navigation); Metadata metadata = metadataRegistry.lookup(ROOT_TEMPLATE); String attributesFormId = Ids.build(Ids.STANDALONE_SERVER_COLUMN, ATTRIBUTES, FORM); attributesForm = new ModelNodeForm.Builder<>(attributesFormId, metadata) .includeRuntime() .onSave((form, changedValues) -> presenter.save(resources.constants().standaloneServer(), ROOT_TEMPLATE, changedValues)) .prepareReset(form -> presenter.reset(resources.constants().standaloneServer(), ROOT_TEMPLATE, form, metadata)) .unsorted() .build(); // makes no sense to mask name attribute attributesForm.getFormItem(NAME).unmask(); // the following attributes are read-only, set as non required to let user save the form attributesForm.getFormItem(NAMESPACES).setRequired(false); attributesForm.getFormItem(SCHEMA_LOCATIONS).setRequired(false); registerAttachable(attributesForm); HTMLElement attributesElement = section() .add(h(1).textContent(resources.constants().attributes()).get()) .add(p().textContent(metadata.getDescription().getDescription()).get()) .add(attributesForm) .get(); String attributesItemId = Ids.build(ATTRIBUTES, ITEM); navigation.addPrimary(attributesItemId, resources.constants().configuration(), pfIcon("settings"), attributesElement); String httpTitle = resources.constants().httpManagementInterface(); Metadata httpMetadata = metadataRegistry.lookup(HTTP_INTERFACE_TEMPLATE); String httpId = Ids.build(HTTP_INTERFACE, FORM); httpInterfaceForm = new ModelNodeForm.Builder<>(httpId, httpMetadata) .onSave((form, changedValues) -> presenter.save(httpTitle, HTTP_INTERFACE_TEMPLATE, changedValues)) .prepareReset(form -> presenter.reset(httpTitle, HTTP_INTERFACE_TEMPLATE, form, httpMetadata)) .unsorted() .build(); enableSslButton = button().id(ENABLE_SSL) .textContent(resources.constants().enableSSL()) .css(Button.DEFAULT_CSS, pullRight) .get(); bind(enableSslButton, click, ev -> presenter.launchEnableSSLWizard()); disableSslButton = button().id(DISABLE_SSL) .textContent(resources.constants().disableSSL()) .css(Button.DEFAULT_CSS, pullRight) .get(); bind(disableSslButton, click, ev -> presenter.disableSSLWizard()); HTMLElement httpMgmtItemElement = section() .add(div() .add(h(1).textContent(httpTitle).get()) .add(p().textContent(httpMetadata.getDescription().getDescription()).get()) .add(enableSslButton) .add(disableSslButton)) .add(httpInterfaceForm) .get(); registerAttachable(httpInterfaceForm); navigation.addPrimary(HTTP_INTERFACE_ITEM, resources.constants().httpManagementInterface(), pfIcon("virtual-machine"), httpMgmtItemElement); initElement(row() .add(column() .addAll(navigation.panes()))); } @Override public void updateAttributes(ModelNode attributes) { attributesForm.view(attributes); } @Override public void updateHttpInterface(ModelNode model) { httpInterfaceForm.view(model); boolean isSslEnabled = model.hasDefined(SSL_CONTEXT) && model.get(SSL_CONTEXT).asString() != null; toggleSslButton(isSslEnabled); } private void toggleSslButton(boolean enable) { Elements.setVisible(enableSslButton, !enable); Elements.setVisible(disableSslButton, enable); } @Override public void setPresenter(StandaloneServerPresenter presenter) { this.presenter = presenter; } }
Fix checkstyle errors
app/src/main/java/org/jboss/hal/client/runtime/server/StandaloneServerView.java
Fix checkstyle errors
<ide><path>pp/src/main/java/org/jboss/hal/client/runtime/server/StandaloneServerView.java <ide> registerAttachable(navigation); <ide> <ide> Metadata metadata = metadataRegistry.lookup(ROOT_TEMPLATE); <del> String attributesFormId = Ids.build(Ids.STANDALONE_SERVER_COLUMN, ATTRIBUTES, FORM); <add> String attributesFormId = Ids.build(Ids.STANDALONE_SERVER_COLUMN, Ids.ATTRIBUTES, FORM); <ide> attributesForm = new ModelNodeForm.Builder<>(attributesFormId, metadata) <ide> .includeRuntime() <ide> .onSave((form, changedValues) -> presenter.save(resources.constants().standaloneServer(), ROOT_TEMPLATE, <ide> .add(p().textContent(metadata.getDescription().getDescription()).get()) <ide> .add(attributesForm) <ide> .get(); <del> String attributesItemId = Ids.build(ATTRIBUTES, ITEM); <add> String attributesItemId = Ids.build(Ids.ATTRIBUTES, ITEM); <ide> navigation.addPrimary(attributesItemId, resources.constants().configuration(), pfIcon("settings"), <ide> attributesElement); <ide>
Java
lgpl-2.1
33857fec843f0008bb4e086606f73637b5ae42ed
0
n8han/Databinder-for-Wicket,n8han/Databinder-for-Wicket,n8han/Databinder-for-Wicket,n8han/Databinder-for-Wicket
package net.databinder.models.ao; import java.sql.SQLException; import java.util.Arrays; import java.util.Iterator; import net.databinder.ao.Databinder; import net.java.ao.Query; import net.java.ao.RawEntity; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.markup.repeater.data.IDataProvider; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.IModel; @SuppressWarnings("unchecked") public class EntityProvider implements IDataProvider { private Class entityType; private Query query; /** Controls wrapping with a compound property model. */ private boolean wrapWithPropertyModel = true; public EntityProvider(Class entityType) { this (entityType, Query.select()); } public EntityProvider(Class entityType, Query query) { this.entityType = entityType; this.query = query; } public Iterator iterator(int first, int count) { try { return Arrays.asList(Databinder.getEntityManager().find(entityType, query)).iterator(); } catch (SQLException e) { throw new WicketRuntimeException(e); } } public int size() { try { return Databinder.getEntityManager().count(entityType, query); } catch (SQLException e) { throw new WicketRuntimeException(e); } } public IModel model(Object object) { IModel model = new EntityModel((RawEntity)object); if (wrapWithPropertyModel) model = new CompoundPropertyModel(model); return model; } public EntityProvider setWrapWithPropertyModel(boolean wrapWithPropertyModel) { this.wrapWithPropertyModel = wrapWithPropertyModel; return this; } public void detach() { } }
databinder-models-ao/src/main/java/net/databinder/models/ao/EntityProvider.java
package net.databinder.models.ao; import java.sql.SQLException; import java.util.Arrays; import java.util.Iterator; import net.databinder.ao.Databinder; import net.java.ao.Query; import net.java.ao.RawEntity; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.markup.repeater.data.IDataProvider; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.IModel; @SuppressWarnings("unchecked") public class EntityProvider implements IDataProvider { private Class entityType; private Query query; /** Controls wrapping with a compound property model. */ private boolean wrapWithPropertyModel = true; public EntityProvider(Class entityType) { this (entityType, Query.select()); } public EntityProvider(Class entityType, Query query) { this.entityType = entityType; this.query = query; } public Iterator iterator(int first, int count) { try { return Arrays.asList(Databinder.getEntityManager().find(entityType, query)).iterator(); } catch (SQLException e) { throw new WicketRuntimeException(e); } } public int size() { try { return Databinder.getEntityManager().count(entityType, query); } catch (SQLException e) { throw new WicketRuntimeException(e); } } public IModel model(Object object) { IModel model = new EntityModel((RawEntity)object); if (wrapWithPropertyModel) model = new CompoundPropertyModel(model); return model; } public void detach() { } public EntityProvider setWrapWithPropertyModel(boolean wrapWithPropertyModel) { this.wrapWithPropertyModel = wrapWithPropertyModel; return this; } }
data provider updates git-svn-id: a029deac1672d4faad1f67456e5ca11caf16dc5a@2113 c322e9cc-cc08-0410-988e-c197163ad9eb
databinder-models-ao/src/main/java/net/databinder/models/ao/EntityProvider.java
data provider updates
<ide><path>atabinder-models-ao/src/main/java/net/databinder/models/ao/EntityProvider.java <ide> throw new WicketRuntimeException(e); <ide> } <ide> } <add> <ide> public IModel model(Object object) { <ide> IModel model = new EntityModel((RawEntity)object); <ide> if (wrapWithPropertyModel) <ide> model = new CompoundPropertyModel(model); <ide> return model; <ide> } <del> public void detach() { } <ide> <ide> public EntityProvider setWrapWithPropertyModel(boolean wrapWithPropertyModel) { <ide> this.wrapWithPropertyModel = wrapWithPropertyModel; <ide> return this; <ide> } <add> <add> public void detach() { } <ide> }
Java
mit
af9289a4e35dc2ce0f3fab035ad4d8c26ad4ade4
0
domisum/ExZiff
package de.domisum.exziff; import de.domisum.exziff.map.BooleanMap; import de.domisum.exziff.map.exporter.bool.BooleanMapImageExporter; import de.domisum.exziff.shape.BooleanMapContinentsGenerator; import de.domisum.lib.auxilium.data.container.math.Polygon2D; import de.domisum.lib.auxilium.data.container.math.Vector2D; import de.domisum.lib.auxilium.util.FileUtil; import de.domisum.lib.auxilium.util.ImageUtil; import java.awt.image.BufferedImage; import java.io.File; import java.util.Random; public class TestLauncher { public static void main(String[] args) { //test(); Random random = new Random(32); FileUtil.deleteDirectoryContents(new File("C:\\Users\\domisum\\testChamber/continents/")); for(int i = 0; i < 30; i++) generate(random.nextLong()); } private static void generate(long seed) { BooleanMapContinentsGenerator generator = new BooleanMapContinentsGenerator((int) Math.pow(2, 14), seed); generator.setDownscalingFactor(4*4); BooleanMap booleanMap = generator.generate(); System.out.println("generator done: "+seed); BooleanMapImageExporter exporter = new BooleanMapImageExporter(); BufferedImage image = exporter.export(booleanMap); ImageUtil.writeImage(new File("C:\\Users\\domisum\\testChamber/continents/"+seed+".png"), image); } private static void test() { Polygon2D polygon2D = new Polygon2D(new Vector2D(0, 0), new Vector2D(1, 0), new Vector2D(1, 1)); System.out.println(polygon2D.contains(new Vector2D(0.25, 0.25))); System.exit(0); } }
src/main/java/de/domisum/exziff/TestLauncher.java
package de.domisum.exziff; import de.domisum.exziff.map.BooleanMap; import de.domisum.exziff.map.exporter.bool.BooleanMapImageExporter; import de.domisum.exziff.shape.BooleanMapContinentsGenerator; import de.domisum.lib.auxilium.data.container.math.Polygon2D; import de.domisum.lib.auxilium.data.container.math.Vector2D; import de.domisum.lib.auxilium.util.ImageUtil; import java.awt.image.BufferedImage; import java.io.File; import java.util.Random; public class TestLauncher { public static void main(String[] args) { //test(); Random random = new Random(3812); for(int i = 0; i < 30; i++) generate(random.nextLong()); } private static void generate(long seed) { BooleanMapContinentsGenerator generator = new BooleanMapContinentsGenerator((int) Math.pow(2, 14), seed); generator.setDownscalingFactor(16); BooleanMap booleanMap = generator.generate(); System.out.println("generator done: "+seed); BooleanMapImageExporter exporter = new BooleanMapImageExporter(); BufferedImage image = exporter.export(booleanMap); ImageUtil.writeImage(new File("C:\\Users\\domisum\\testChamber/continents/"+seed+".png"), image); } private static void test() { Polygon2D polygon2D = new Polygon2D(new Vector2D(0, 0), new Vector2D(1, 0), new Vector2D(1, 1)); System.out.println(polygon2D.contains(new Vector2D(0.25, 0.25))); System.exit(0); } }
Changes to TestLauncher
src/main/java/de/domisum/exziff/TestLauncher.java
Changes to TestLauncher
<ide><path>rc/main/java/de/domisum/exziff/TestLauncher.java <ide> import de.domisum.exziff.shape.BooleanMapContinentsGenerator; <ide> import de.domisum.lib.auxilium.data.container.math.Polygon2D; <ide> import de.domisum.lib.auxilium.data.container.math.Vector2D; <add>import de.domisum.lib.auxilium.util.FileUtil; <ide> import de.domisum.lib.auxilium.util.ImageUtil; <ide> <ide> import java.awt.image.BufferedImage; <ide> { <ide> //test(); <ide> <del> Random random = new Random(3812); <add> Random random = new Random(32); <ide> <add> FileUtil.deleteDirectoryContents(new File("C:\\Users\\domisum\\testChamber/continents/")); <ide> for(int i = 0; i < 30; i++) <ide> generate(random.nextLong()); <ide> } <ide> private static void generate(long seed) <ide> { <ide> BooleanMapContinentsGenerator generator = new BooleanMapContinentsGenerator((int) Math.pow(2, 14), seed); <del> generator.setDownscalingFactor(16); <add> generator.setDownscalingFactor(4*4); <ide> BooleanMap booleanMap = generator.generate(); <ide> System.out.println("generator done: "+seed); <ide>
Java
apache-2.0
f5cda70fba0f29af17450e0e4023e78be64086a9
0
lukhnos/j2objc,google/j2objc,groschovskiy/j2objc,lukhnos/j2objc,mirego/j2objc,google/j2objc,mirego/j2objc,mirego/j2objc,lukhnos/j2objc,google/j2objc,lukhnos/j2objc,groschovskiy/j2objc,mirego/j2objc,groschovskiy/j2objc,google/j2objc,lukhnos/j2objc,groschovskiy/j2objc,google/j2objc,groschovskiy/j2objc,google/j2objc,lukhnos/j2objc,mirego/j2objc,mirego/j2objc,groschovskiy/j2objc
/* * 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.google.devtools.j2objc.translate; import com.google.devtools.j2objc.GenerationTest; import java.io.IOException; /** * Tests Java 8 type annotations. * * @author Keith Stanger */ public class TypeUseAnnotationTest extends GenerationTest { // Regression for Issue #730. public void testAnnotatedStringType() throws IOException { addSourceFile( "import java.lang.annotation.*;\n" + "@Target(ElementType.TYPE_USE) public @interface A {}", "A.java"); String translation = translateSourceFile( "class Test { @A String str; @A String foo() { return null; } }", "Test", "Test.m"); assertNotInTranslation(translation, "java/lang/String.h"); assertNotInTranslation(translation, "JavaLangString"); } String testWeakOuterSetup = "import java.lang.annotation.*;\n" + "import com.google.j2objc.annotations.WeakOuter;" + "interface Simple { public int run(); }" + "class SimpleClass { public int run() {return 1;}; }" + "abstract class SimpleAbstractClass { public int run(){return 2;}; }" + "class Test { int member = 7; Object o;"; public void testWeakOuterInterface() throws IOException { String translationInterfaceWithWeak = translateSourceFile(testWeakOuterSetup + "void f() { o = new @WeakOuter Simple() { public int run() { return member; } }; } }", "Test", "Test.m"); assertTranslation(translationInterfaceWithWeak, "__unsafe_unretained Test *this$0_;"); String translationInterfaceWithoutWeak = translateSourceFile(testWeakOuterSetup + "void f() { o = new Simple() { public int run() { return member; } }; } }", "Test", "Test.m"); assertNotInTranslation(translationInterfaceWithoutWeak, "__unsafe_unretained Test *this$0_;"); } public void testWeakOuterClass() throws IOException { String translationInterfaceWithWeak = translateSourceFile(testWeakOuterSetup + "void f() { o = new @WeakOuter SimpleClass() {" + "public int run() { return member; } }; } }", "Test", "Test.m"); assertTranslation(translationInterfaceWithWeak, "__unsafe_unretained Test *this$0_;"); String translationInterfaceWithoutWeak = translateSourceFile(testWeakOuterSetup + "void f() { o = new SimpleClass() { public int run() { return member; } }; } }", "Test", "Test.m"); assertNotInTranslation(translationInterfaceWithoutWeak, "__unsafe_unretained Test *this$0_;"); } public void testWeakOuterAbstractClass() throws IOException { String translationInterfaceWithWeak = translateSourceFile(testWeakOuterSetup + "void f() { o = new @WeakOuter SimpleAbstractClass() {" + "public int run() { return member; } }; } }", "Test", "Test.m"); assertTranslation(translationInterfaceWithWeak, "__unsafe_unretained Test *this$0_;"); String translationInterfaceWithoutWeak = translateSourceFile(testWeakOuterSetup + "void f() { o = new SimpleAbstractClass() { public int run() { return member; } }; } }", "Test", "Test.m"); assertNotInTranslation(translationInterfaceWithoutWeak, "__unsafe_unretained Test *this$0_;"); } }
translator/src/test/java/com/google/devtools/j2objc/translate/TypeUseAnnotationTest.java
/* * 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.google.devtools.j2objc.translate; import com.google.devtools.j2objc.GenerationTest; import java.io.IOException; /** * Tests Java 8 type annotations. * * @author Keith Stanger */ public class TypeUseAnnotationTest extends GenerationTest { // Regression for Issue #730. public void testAnnotatedStringType() throws IOException { addSourceFile( "import java.lang.annotation.*;\n" + "@Target(ElementType.TYPE_USE) public @interface A {}", "A.java"); String translation = translateSourceFile( "class Test { @A String str; @A String foo() { return null; } }", "Test", "Test.m"); assertNotInTranslation(translation, "java/lang/String.h"); assertNotInTranslation(translation, "JavaLangString"); } // TODO(nbraswell): Use com.google.j2objc.annotations.WeakOuter when transitioned to Java 8 String testWeakOuterSetup = "import java.lang.annotation.*;\n" + "@Target(ElementType.TYPE_USE) @interface WeakOuter {}" + "interface Simple { public int run(); }" + "class SimpleClass { public int run() {return 1;}; }" + "abstract class SimpleAbstractClass { public int run(){return 2;}; }" + "class Test { int member = 7; Object o;"; public void testWeakOuterInterface() throws IOException { String translationInterfaceWithWeak = translateSourceFile(testWeakOuterSetup + "void f() { o = new @WeakOuter Simple() { public int run() { return member; } }; } }", "Test", "Test.m"); assertTranslation(translationInterfaceWithWeak, "__unsafe_unretained Test *this$0_;"); String translationInterfaceWithoutWeak = translateSourceFile(testWeakOuterSetup + "void f() { o = new Simple() { public int run() { return member; } }; } }", "Test", "Test.m"); assertNotInTranslation(translationInterfaceWithoutWeak, "__unsafe_unretained Test *this$0_;"); } public void testWeakOuterClass() throws IOException { String translationInterfaceWithWeak = translateSourceFile(testWeakOuterSetup + "void f() { o = new @WeakOuter SimpleClass() {" + "public int run() { return member; } }; } }", "Test", "Test.m"); assertTranslation(translationInterfaceWithWeak, "__unsafe_unretained Test *this$0_;"); String translationInterfaceWithoutWeak = translateSourceFile(testWeakOuterSetup + "void f() { o = new SimpleClass() { public int run() { return member; } }; } }", "Test", "Test.m"); assertNotInTranslation(translationInterfaceWithoutWeak, "__unsafe_unretained Test *this$0_;"); } public void testWeakOuterAbstractClass() throws IOException { String translationInterfaceWithWeak = translateSourceFile(testWeakOuterSetup + "void f() { o = new @WeakOuter SimpleAbstractClass() {" + "public int run() { return member; } }; } }", "Test", "Test.m"); assertTranslation(translationInterfaceWithWeak, "__unsafe_unretained Test *this$0_;"); String translationInterfaceWithoutWeak = translateSourceFile(testWeakOuterSetup + "void f() { o = new SimpleAbstractClass() { public int run() { return member; } }; } }", "Test", "Test.m"); assertNotInTranslation(translationInterfaceWithoutWeak, "__unsafe_unretained Test *this$0_;"); } }
Project health: use com.google.j2objc.annotations.WeakOuter in TypeUseAnnotationTest. Change on 2019/03/15 by antoniocortes <[email protected]> ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=238645354
translator/src/test/java/com/google/devtools/j2objc/translate/TypeUseAnnotationTest.java
Project health: use com.google.j2objc.annotations.WeakOuter in TypeUseAnnotationTest.
<ide><path>ranslator/src/test/java/com/google/devtools/j2objc/translate/TypeUseAnnotationTest.java <ide> assertNotInTranslation(translation, "JavaLangString"); <ide> } <ide> <del> // TODO(nbraswell): Use com.google.j2objc.annotations.WeakOuter when transitioned to Java 8 <ide> String testWeakOuterSetup = "import java.lang.annotation.*;\n" <del> + "@Target(ElementType.TYPE_USE) @interface WeakOuter {}" <add> + "import com.google.j2objc.annotations.WeakOuter;" <ide> + "interface Simple { public int run(); }" <ide> + "class SimpleClass { public int run() {return 1;}; }" <ide> + "abstract class SimpleAbstractClass { public int run(){return 2;}; }"
Java
apache-2.0
4d5e03049eb7067551580bbc4ef872b51a7ba5e1
0
stianst/keycloak,reneploetz/keycloak,ssilvert/keycloak,brat000012001/keycloak,brat000012001/keycloak,mhajas/keycloak,vmuzikar/keycloak,ahus1/keycloak,agolPL/keycloak,mbaluch/keycloak,mhajas/keycloak,hmlnarik/keycloak,abstractj/keycloak,brat000012001/keycloak,jpkrohling/keycloak,jpkrohling/keycloak,keycloak/keycloak,mhajas/keycloak,srose/keycloak,stianst/keycloak,ahus1/keycloak,mposolda/keycloak,thomasdarimont/keycloak,mposolda/keycloak,stianst/keycloak,vmuzikar/keycloak,ssilvert/keycloak,ahus1/keycloak,thomasdarimont/keycloak,brat000012001/keycloak,ssilvert/keycloak,jpkrohling/keycloak,thomasdarimont/keycloak,ssilvert/keycloak,hmlnarik/keycloak,raehalme/keycloak,ahus1/keycloak,agolPL/keycloak,reneploetz/keycloak,darranl/keycloak,vmuzikar/keycloak,srose/keycloak,brat000012001/keycloak,srose/keycloak,darranl/keycloak,keycloak/keycloak,pedroigor/keycloak,keycloak/keycloak,hmlnarik/keycloak,ssilvert/keycloak,raehalme/keycloak,pedroigor/keycloak,mposolda/keycloak,raehalme/keycloak,pedroigor/keycloak,abstractj/keycloak,mhajas/keycloak,mposolda/keycloak,darranl/keycloak,srose/keycloak,raehalme/keycloak,reneploetz/keycloak,jpkrohling/keycloak,pedroigor/keycloak,reneploetz/keycloak,darranl/keycloak,hmlnarik/keycloak,srose/keycloak,pedroigor/keycloak,hmlnarik/keycloak,thomasdarimont/keycloak,mbaluch/keycloak,agolPL/keycloak,abstractj/keycloak,ahus1/keycloak,thomasdarimont/keycloak,keycloak/keycloak,raehalme/keycloak,hmlnarik/keycloak,keycloak/keycloak,raehalme/keycloak,abstractj/keycloak,mhajas/keycloak,mposolda/keycloak,vmuzikar/keycloak,agolPL/keycloak,ahus1/keycloak,mbaluch/keycloak,jpkrohling/keycloak,vmuzikar/keycloak,vmuzikar/keycloak,abstractj/keycloak,stianst/keycloak,reneploetz/keycloak,stianst/keycloak,pedroigor/keycloak,mbaluch/keycloak,thomasdarimont/keycloak,mposolda/keycloak
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.keycloak.adapters.servlet; import org.keycloak.adapters.AdapterDeploymentContext; import org.keycloak.adapters.AuthenticatedActionsHandler; import org.keycloak.adapters.KeycloakConfigResolver; import org.keycloak.adapters.KeycloakDeployment; import org.keycloak.adapters.KeycloakDeploymentBuilder; import org.keycloak.adapters.NodesRegistrationManagement; import org.keycloak.adapters.PreAuthActionsHandler; import org.keycloak.adapters.spi.AuthChallenge; import org.keycloak.adapters.spi.AuthOutcome; import org.keycloak.adapters.spi.InMemorySessionIdMapper; import org.keycloak.adapters.spi.SessionIdMapper; import org.keycloak.adapters.spi.UserSessionManagement; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; /** * @author <a href="mailto:[email protected]">Bill Burke</a> * @version $Revision: 1 $ */ public class KeycloakOIDCFilter implements Filter { private final static Logger log = Logger.getLogger("" + KeycloakOIDCFilter.class); public static final String SKIP_PATTERN_PARAM = "keycloak.config.skipPattern"; public static final String CONFIG_RESOLVER_PARAM = "keycloak.config.resolver"; public static final String CONFIG_FILE_PARAM = "keycloak.config.file"; public static final String CONFIG_PATH_PARAM = "keycloak.config.path"; protected AdapterDeploymentContext deploymentContext; protected SessionIdMapper idMapper = new InMemorySessionIdMapper(); protected NodesRegistrationManagement nodesRegistrationManagement; protected Pattern skipPattern; private final KeycloakConfigResolver definedconfigResolver; /** * Constructor that can be used to define a {@code KeycloakConfigResolver} that will be used at initialization to * provide the {@code KeycloakDeployment}. * @param definedconfigResolver the resolver */ public KeycloakOIDCFilter(KeycloakConfigResolver definedconfigResolver) { this.definedconfigResolver = definedconfigResolver; } public KeycloakOIDCFilter() { this(null); } @Override public void init(final FilterConfig filterConfig) throws ServletException { String skipPatternDefinition = filterConfig.getInitParameter(SKIP_PATTERN_PARAM); if (skipPatternDefinition != null) { skipPattern = Pattern.compile(skipPatternDefinition, Pattern.DOTALL); } if (definedconfigResolver != null) { deploymentContext = new AdapterDeploymentContext(definedconfigResolver); log.log(Level.INFO, "Using {0} to resolve Keycloak configuration on a per-request basis.", definedconfigResolver.getClass()); } else { String configResolverClass = filterConfig.getInitParameter(CONFIG_RESOLVER_PARAM); if (configResolverClass != null) { try { KeycloakConfigResolver configResolver = (KeycloakConfigResolver) getClass().getClassLoader().loadClass(configResolverClass).newInstance(); deploymentContext = new AdapterDeploymentContext(configResolver); log.log(Level.INFO, "Using {0} to resolve Keycloak configuration on a per-request basis.", configResolverClass); } catch (Exception ex) { log.log(Level.FINE, "The specified resolver {0} could NOT be loaded. Keycloak is unconfigured and will deny all requests. Reason: {1}", new Object[]{configResolverClass, ex.getMessage()}); deploymentContext = new AdapterDeploymentContext(new KeycloakDeployment()); } } else { String fp = filterConfig.getInitParameter(CONFIG_FILE_PARAM); InputStream is = null; if (fp != null) { try { is = new FileInputStream(fp); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } else { String path = "/WEB-INF/keycloak.json"; String pathParam = filterConfig.getInitParameter(CONFIG_PATH_PARAM); if (pathParam != null) path = pathParam; is = filterConfig.getServletContext().getResourceAsStream(path); } KeycloakDeployment kd = createKeycloakDeploymentFrom(is); deploymentContext = new AdapterDeploymentContext(kd); log.fine("Keycloak is using a per-deployment configuration."); } } filterConfig.getServletContext().setAttribute(AdapterDeploymentContext.class.getName(), deploymentContext); nodesRegistrationManagement = new NodesRegistrationManagement(); } private KeycloakDeployment createKeycloakDeploymentFrom(InputStream is) { if (is == null) { log.fine("No adapter configuration. Keycloak is unconfigured and will deny all requests."); return new KeycloakDeployment(); } return KeycloakDeploymentBuilder.build(is); } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { log.fine("Keycloak OIDC Filter"); HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; if (shouldSkip(request)) { chain.doFilter(req, res); return; } OIDCServletHttpFacade facade = new OIDCServletHttpFacade(request, response); KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade); if (deployment == null || !deployment.isConfigured()) { response.sendError(403); log.fine("deployment not configured"); return; } PreAuthActionsHandler preActions = new PreAuthActionsHandler(new UserSessionManagement() { @Override public void logoutAll() { if (idMapper != null) { idMapper.clear(); } } @Override public void logoutHttpSessions(List<String> ids) { log.fine("**************** logoutHttpSessions"); //System.err.println("**************** logoutHttpSessions"); for (String id : ids) { log.finest("removed idMapper: " + id); idMapper.removeSession(id); } } }, deploymentContext, facade); if (preActions.handleRequest()) { //System.err.println("**************** preActions.handleRequest happened!"); return; } nodesRegistrationManagement.tryRegister(deployment); OIDCFilterSessionStore tokenStore = new OIDCFilterSessionStore(request, facade, 100000, deployment, idMapper); tokenStore.checkCurrentToken(); FilterRequestAuthenticator authenticator = new FilterRequestAuthenticator(deployment, tokenStore, facade, request, 8443); AuthOutcome outcome = authenticator.authenticate(); if (outcome == AuthOutcome.AUTHENTICATED) { log.fine("AUTHENTICATED"); if (facade.isEnded()) { return; } AuthenticatedActionsHandler actions = new AuthenticatedActionsHandler(deployment, facade); if (actions.handledRequest()) { return; } else { HttpServletRequestWrapper wrapper = tokenStore.buildWrapper(); chain.doFilter(wrapper, res); return; } } AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { log.fine("challenge"); challenge.challenge(facade); return; } response.sendError(403); } /** * Decides whether this {@link Filter} should skip the given {@link HttpServletRequest} based on the configured {@link KeycloakOIDCFilter#skipPattern}. * Patterns are matched against the {@link HttpServletRequest#getRequestURI() requestURI} of a request without the context-path. * A request for {@code /myapp/index.html} would be tested with {@code /index.html} against the skip pattern. * Skipped requests will not be processed further by {@link KeycloakOIDCFilter} and immediately delegated to the {@link FilterChain}. * * @param request the request to check * @return {@code true} if the request should not be handled, * {@code false} otherwise. */ private boolean shouldSkip(HttpServletRequest request) { if (skipPattern == null) { return false; } String requestPath = request.getRequestURI().substring(request.getContextPath().length()); return skipPattern.matcher(requestPath).matches(); } @Override public void destroy() { } }
adapters/oidc/servlet-filter/src/main/java/org/keycloak/adapters/servlet/KeycloakOIDCFilter.java
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.keycloak.adapters.servlet; import org.keycloak.adapters.AdapterDeploymentContext; import org.keycloak.adapters.AuthenticatedActionsHandler; import org.keycloak.adapters.KeycloakConfigResolver; import org.keycloak.adapters.KeycloakDeployment; import org.keycloak.adapters.KeycloakDeploymentBuilder; import org.keycloak.adapters.NodesRegistrationManagement; import org.keycloak.adapters.PreAuthActionsHandler; import org.keycloak.adapters.spi.AuthChallenge; import org.keycloak.adapters.spi.AuthOutcome; import org.keycloak.adapters.spi.InMemorySessionIdMapper; import org.keycloak.adapters.spi.SessionIdMapper; import org.keycloak.adapters.spi.UserSessionManagement; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; /** * @author <a href="mailto:[email protected]">Bill Burke</a> * @version $Revision: 1 $ */ public class KeycloakOIDCFilter implements Filter { public static final String SKIP_PATTERN_PARAM = "keycloak.config.skipPattern"; protected AdapterDeploymentContext deploymentContext; protected SessionIdMapper idMapper = new InMemorySessionIdMapper(); protected NodesRegistrationManagement nodesRegistrationManagement; protected Pattern skipPattern; private final static Logger log = Logger.getLogger(""+KeycloakOIDCFilter.class); @Override public void init(final FilterConfig filterConfig) throws ServletException { String skipPatternDefinition = filterConfig.getInitParameter(SKIP_PATTERN_PARAM); if (skipPatternDefinition != null) { skipPattern = Pattern.compile(skipPatternDefinition, Pattern.DOTALL); } String configResolverClass = filterConfig.getInitParameter("keycloak.config.resolver"); if (configResolverClass != null) { try { KeycloakConfigResolver configResolver = (KeycloakConfigResolver) getClass().getClassLoader().loadClass(configResolverClass).newInstance(); deploymentContext = new AdapterDeploymentContext(configResolver); log.log(Level.INFO, "Using {0} to resolve Keycloak configuration on a per-request basis.", configResolverClass); } catch (Exception ex) { log.log(Level.FINE, "The specified resolver {0} could NOT be loaded. Keycloak is unconfigured and will deny all requests. Reason: {1}", new Object[]{configResolverClass, ex.getMessage()}); deploymentContext = new AdapterDeploymentContext(new KeycloakDeployment()); } } else { String fp = filterConfig.getInitParameter("keycloak.config.file"); InputStream is = null; if (fp != null) { try { is = new FileInputStream(fp); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } else { String path = "/WEB-INF/keycloak.json"; String pathParam = filterConfig.getInitParameter("keycloak.config.path"); if (pathParam != null) path = pathParam; is = filterConfig.getServletContext().getResourceAsStream(path); } KeycloakDeployment kd = createKeycloakDeploymentFrom(is); deploymentContext = new AdapterDeploymentContext(kd); log.fine("Keycloak is using a per-deployment configuration."); } filterConfig.getServletContext().setAttribute(AdapterDeploymentContext.class.getName(), deploymentContext); nodesRegistrationManagement = new NodesRegistrationManagement(); } private KeycloakDeployment createKeycloakDeploymentFrom(InputStream is) { if (is == null) { log.fine("No adapter configuration. Keycloak is unconfigured and will deny all requests."); return new KeycloakDeployment(); } return KeycloakDeploymentBuilder.build(is); } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { log.fine("Keycloak OIDC Filter"); //System.err.println("Keycloak OIDC Filter: " + ((HttpServletRequest)req).getRequestURL().toString()); HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; if (shouldSkip(request)) { chain.doFilter(req, res); return; } OIDCServletHttpFacade facade = new OIDCServletHttpFacade(request, response); KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade); if (deployment == null || !deployment.isConfigured()) { response.sendError(403); log.fine("deployment not configured"); return; } PreAuthActionsHandler preActions = new PreAuthActionsHandler(new UserSessionManagement() { @Override public void logoutAll() { if (idMapper != null) { idMapper.clear(); } } @Override public void logoutHttpSessions(List<String> ids) { log.fine("**************** logoutHttpSessions"); //System.err.println("**************** logoutHttpSessions"); for (String id : ids) { log.finest("removed idMapper: " + id); idMapper.removeSession(id); } } }, deploymentContext, facade); if (preActions.handleRequest()) { //System.err.println("**************** preActions.handleRequest happened!"); return; } nodesRegistrationManagement.tryRegister(deployment); OIDCFilterSessionStore tokenStore = new OIDCFilterSessionStore(request, facade, 100000, deployment, idMapper); tokenStore.checkCurrentToken(); FilterRequestAuthenticator authenticator = new FilterRequestAuthenticator(deployment, tokenStore, facade, request, 8443); AuthOutcome outcome = authenticator.authenticate(); if (outcome == AuthOutcome.AUTHENTICATED) { log.fine("AUTHENTICATED"); if (facade.isEnded()) { return; } AuthenticatedActionsHandler actions = new AuthenticatedActionsHandler(deployment, facade); if (actions.handledRequest()) { return; } else { HttpServletRequestWrapper wrapper = tokenStore.buildWrapper(); chain.doFilter(wrapper, res); return; } } AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { log.fine("challenge"); challenge.challenge(facade); return; } response.sendError(403); } /** * Decides whether this {@link Filter} should skip the given {@link HttpServletRequest} based on the configured {@link KeycloakOIDCFilter#skipPattern}. * Patterns are matched against the {@link HttpServletRequest#getRequestURI() requestURI} of a request without the context-path. * A request for {@code /myapp/index.html} would be tested with {@code /index.html} against the skip pattern. * Skipped requests will not be processed further by {@link KeycloakOIDCFilter} and immediately delegated to the {@link FilterChain}. * * @param request the request to check * @return {@code true} if the request should not be handled, * {@code false} otherwise. */ private boolean shouldSkip(HttpServletRequest request) { if (skipPattern == null) { return false; } String requestPath = request.getRequestURI().substring(request.getContextPath().length()); return skipPattern.matcher(requestPath).matches(); } @Override public void destroy() { } }
provide a custom KeycloakConfigResolver instance for servlet filter.
adapters/oidc/servlet-filter/src/main/java/org/keycloak/adapters/servlet/KeycloakOIDCFilter.java
provide a custom KeycloakConfigResolver instance for servlet filter.
<ide><path>dapters/oidc/servlet-filter/src/main/java/org/keycloak/adapters/servlet/KeycloakOIDCFilter.java <ide> */ <ide> public class KeycloakOIDCFilter implements Filter { <ide> <add> private final static Logger log = Logger.getLogger("" + KeycloakOIDCFilter.class); <add> <ide> public static final String SKIP_PATTERN_PARAM = "keycloak.config.skipPattern"; <ide> <add> public static final String CONFIG_RESOLVER_PARAM = "keycloak.config.resolver"; <add> <add> public static final String CONFIG_FILE_PARAM = "keycloak.config.file"; <add> <add> public static final String CONFIG_PATH_PARAM = "keycloak.config.path"; <add> <ide> protected AdapterDeploymentContext deploymentContext; <add> <ide> protected SessionIdMapper idMapper = new InMemorySessionIdMapper(); <add> <ide> protected NodesRegistrationManagement nodesRegistrationManagement; <add> <ide> protected Pattern skipPattern; <ide> <del> private final static Logger log = Logger.getLogger(""+KeycloakOIDCFilter.class); <add> private final KeycloakConfigResolver definedconfigResolver; <add> <add> /** <add> * Constructor that can be used to define a {@code KeycloakConfigResolver} that will be used at initialization to <add> * provide the {@code KeycloakDeployment}. <add> * @param definedconfigResolver the resolver <add> */ <add> public KeycloakOIDCFilter(KeycloakConfigResolver definedconfigResolver) { <add> this.definedconfigResolver = definedconfigResolver; <add> } <add> <add> public KeycloakOIDCFilter() { <add> this(null); <add> } <ide> <ide> @Override <ide> public void init(final FilterConfig filterConfig) throws ServletException { <del> <ide> String skipPatternDefinition = filterConfig.getInitParameter(SKIP_PATTERN_PARAM); <ide> if (skipPatternDefinition != null) { <ide> skipPattern = Pattern.compile(skipPatternDefinition, Pattern.DOTALL); <ide> } <ide> <del> String configResolverClass = filterConfig.getInitParameter("keycloak.config.resolver"); <del> if (configResolverClass != null) { <del> try { <del> KeycloakConfigResolver configResolver = (KeycloakConfigResolver) getClass().getClassLoader().loadClass(configResolverClass).newInstance(); <del> deploymentContext = new AdapterDeploymentContext(configResolver); <del> log.log(Level.INFO, "Using {0} to resolve Keycloak configuration on a per-request basis.", configResolverClass); <del> } catch (Exception ex) { <del> log.log(Level.FINE, "The specified resolver {0} could NOT be loaded. Keycloak is unconfigured and will deny all requests. Reason: {1}", new Object[]{configResolverClass, ex.getMessage()}); <del> deploymentContext = new AdapterDeploymentContext(new KeycloakDeployment()); <del> } <add> if (definedconfigResolver != null) { <add> deploymentContext = new AdapterDeploymentContext(definedconfigResolver); <add> log.log(Level.INFO, "Using {0} to resolve Keycloak configuration on a per-request basis.", definedconfigResolver.getClass()); <ide> } else { <del> String fp = filterConfig.getInitParameter("keycloak.config.file"); <del> InputStream is = null; <del> if (fp != null) { <add> String configResolverClass = filterConfig.getInitParameter(CONFIG_RESOLVER_PARAM); <add> if (configResolverClass != null) { <ide> try { <del> is = new FileInputStream(fp); <del> } catch (FileNotFoundException e) { <del> throw new RuntimeException(e); <add> KeycloakConfigResolver configResolver = (KeycloakConfigResolver) getClass().getClassLoader().loadClass(configResolverClass).newInstance(); <add> deploymentContext = new AdapterDeploymentContext(configResolver); <add> log.log(Level.INFO, "Using {0} to resolve Keycloak configuration on a per-request basis.", configResolverClass); <add> } catch (Exception ex) { <add> log.log(Level.FINE, "The specified resolver {0} could NOT be loaded. Keycloak is unconfigured and will deny all requests. Reason: {1}", new Object[]{configResolverClass, ex.getMessage()}); <add> deploymentContext = new AdapterDeploymentContext(new KeycloakDeployment()); <ide> } <ide> } else { <del> String path = "/WEB-INF/keycloak.json"; <del> String pathParam = filterConfig.getInitParameter("keycloak.config.path"); <del> if (pathParam != null) path = pathParam; <del> is = filterConfig.getServletContext().getResourceAsStream(path); <del> } <del> KeycloakDeployment kd = createKeycloakDeploymentFrom(is); <del> deploymentContext = new AdapterDeploymentContext(kd); <del> log.fine("Keycloak is using a per-deployment configuration."); <add> String fp = filterConfig.getInitParameter(CONFIG_FILE_PARAM); <add> InputStream is = null; <add> if (fp != null) { <add> try { <add> is = new FileInputStream(fp); <add> } catch (FileNotFoundException e) { <add> throw new RuntimeException(e); <add> } <add> } else { <add> String path = "/WEB-INF/keycloak.json"; <add> String pathParam = filterConfig.getInitParameter(CONFIG_PATH_PARAM); <add> if (pathParam != null) path = pathParam; <add> is = filterConfig.getServletContext().getResourceAsStream(path); <add> } <add> KeycloakDeployment kd = createKeycloakDeploymentFrom(is); <add> deploymentContext = new AdapterDeploymentContext(kd); <add> log.fine("Keycloak is using a per-deployment configuration."); <add> } <ide> } <ide> filterConfig.getServletContext().setAttribute(AdapterDeploymentContext.class.getName(), deploymentContext); <ide> nodesRegistrationManagement = new NodesRegistrationManagement(); <ide> } <ide> <ide> private KeycloakDeployment createKeycloakDeploymentFrom(InputStream is) { <del> <ide> if (is == null) { <ide> log.fine("No adapter configuration. Keycloak is unconfigured and will deny all requests."); <ide> return new KeycloakDeployment(); <ide> } <del> <ide> return KeycloakDeploymentBuilder.build(is); <ide> } <ide> <ide> <ide> @Override <ide> public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { <del> <ide> log.fine("Keycloak OIDC Filter"); <del> //System.err.println("Keycloak OIDC Filter: " + ((HttpServletRequest)req).getRequestURL().toString()); <ide> HttpServletRequest request = (HttpServletRequest) req; <ide> HttpServletResponse response = (HttpServletResponse) res; <ide> <ide> * <ide> * @param request the request to check <ide> * @return {@code true} if the request should not be handled, <del> * {@code false} otherwise. <add> * {@code false} otherwise. <ide> */ <ide> private boolean shouldSkip(HttpServletRequest request) { <ide>
JavaScript
apache-2.0
cfd0b18d968cddd96b9e2429a00b7abfc3084558
0
ManageIQ/manageiq-ui-classic,ManageIQ/manageiq-ui-classic,ManageIQ/manageiq-ui-classic,ManageIQ/manageiq-ui-classic
/* global dialogFieldRefresh miqCheckForChanges miqCheckMaxLength miqJqueryRequest miqMenuChangeRow miqObserveRequest miqSendDateRequest miqSendOneTrans miqSerializeForm miqSparkle miqSparkleOn */ // MIQ unobtrusive javascript bindings run when document is fully loaded $(document).ready(function () { // Bind call to prompt if leaving an active edit $(document).on('ajax:beforeSend', 'a[data-miq_check_for_changes]', function () { return miqCheckForChanges(); }); $(document).on('click', 'button[data-click_url]', function () { var el = $(this); var parms = $.parseJSON(el.attr('data-click_url')); var url = parms.url; var options = {}; if (el.attr('data-miq_sparkle_on')) { options.beforeSend = true; } if (el.attr('data-miq_sparkle_off')) { options.complete = true; } var submit = el.attr('data-submit'); if (typeof submit != "undefined") miqJqueryRequest(url, {data: miqSerializeForm(submit)}); else miqJqueryRequest(url, options); return false; }); // bind button click to call JS function to send up grid data $(document).on('click', 'button[data-grid_submit]', function () { return miqMenuChangeRow($(this).attr('data-grid_submit'), $(this)); }); // Bind call to check/display text area max length on keyup $(document).on('keyup', 'textarea[data-miq_check_max_length]', function () { miqCheckMaxLength(this); }); // Bind the MIQ spinning Q to configured links $(document).on('ajax:beforeSend', 'a[data-miq_sparkle_on]', function () { // Return only if data-miq_sparkle_on is set to false if ($(this).data('miq_sparkle_on') === false) { return; } // Call to miqSparkleOn since miqSparkle(true) checks XHR count, which is 0 before send miqSparkleOn(); }); $(document).on('ajax:complete', 'a[data-miq_sparkle_off]', function () { // Return only if data-miq_sparkle_off is set to false if ($(this).data('miq_sparkle_off') === false) { return; } miqSparkle(false); }); // Handle data-submit - triggered by handleRemote from jquery-ujs $(document).on('ajax:before', 'a[data-submit]', function () { var form_id = $(this).data('submit'); // because handleRemote will send the element's data-params as the POST body $(this).data('params', miqSerializeForm(form_id)); }); // Bind in the observe support. If interval is configured, use the observe_field function var attemptAutoRefreshTrigger = function(parms) { return function() { if (parms.auto_refresh === true) { dialogFieldRefresh.triggerAutoRefresh(parms); } }; }; var observeWithInterval = function(el, parms) { if (el.data('isObserved')) { return; } el.data('isObserved', true); var interval = parms.interval; var url = parms.url; var submit = parms.submit; el.observe_field(interval, function () { var oneTrans = this.getAttribute('data-miq_send_one_trans'); // Grab one trans URL, if present if (typeof submit != "undefined") { // If submit element passed in miqObserveRequest(url, { data: miqSerializeForm(submit), done: attemptAutoRefreshTrigger(parms), }); } else if (oneTrans) { miqSendOneTrans(url, { observe: true, done: attemptAutoRefreshTrigger(parms), }); } else { // tack on the id and value to the URL var data = {}; data[el.attr('id')] = el.prop('value'); miqObserveRequest(url, { done: attemptAutoRefreshTrigger(parms), data: data, }); } }); }; var observeOnChange = function(el, parms) { // No interval passed, use event observer el.off('change'); el.on('change', _.debounce(function() { var id = el.attr('id'); var value = el.prop('multiple') ? el.val() : encodeURIComponent(el.prop('value')); miqObserveRequest(parms.url, { no_encoding: true, data: id + '=' + value, beforeSend: !! el.attr('data-miq_sparkle_on'), complete: !! el.attr('data-miq_sparkle_off'), done: attemptAutoRefreshTrigger(parms), }); }, 700, {leading: true, trailing: true})); }; $(document).on('focus', '[data-miq_observe]', function () { var el = $(this); var parms = $.parseJSON(el.attr('data-miq_observe')); if (typeof parms.interval == "undefined") { observeOnChange(el, parms); } else { observeWithInterval(el, parms); } }); $(document).on('change', '[data-miq_observe_checkbox]', function (event) { var el = $(this); var parms = $.parseJSON(el.attr('data-miq_observe_checkbox')); var url = parms.url; var id = el.attr('id'); var value = encodeURIComponent(el.prop('checked') ? el.val() : 'null'); miqObserveRequest(url, { no_encoding: true, data: id + '=' + value, beforeSend: !! el.attr('data-miq_sparkle_on'), complete: !! el.attr('data-miq_sparkle_off'), done: attemptAutoRefreshTrigger(parms), }); event.stopPropagation(); }); ManageIQ.observeDate = function(el) { miqSendDateRequest(el); }; $(document).on('changeDate clearDate', '[data-miq_observe_date]', function() { ManageIQ.observeDate($(this)); }); // Run this last to be sure all other UJS bindings have been run in case the focus field is observed $('[data-miq_focus]').each(function(_index) { this.focus(); }); });
app/assets/javascripts/miq_ujs_bindings.js
/* global dialogFieldRefresh miqCheckForChanges miqCheckMaxLength miqJqueryRequest miqMenuChangeRow miqObserveRequest miqSendDateRequest miqSendOneTrans miqSerializeForm miqSparkle miqSparkleOn */ // MIQ unobtrusive javascript bindings run when document is fully loaded $(document).ready(function () { // Bind call to prompt if leaving an active edit $(document).on('ajax:beforeSend', 'a[data-miq_check_for_changes]', function () { return miqCheckForChanges(); }); $(document).on('click', 'button[data-click_url]', function () { var el = $(this); var parms = $.parseJSON(el.attr('data-click_url')); var url = parms.url; var options = {}; if (el.attr('data-miq_sparkle_on')) { options.beforeSend = true; } if (el.attr('data-miq_sparkle_off')) { options.complete = true; } var submit = el.attr('data-submit'); if (typeof submit != "undefined") miqJqueryRequest(url, {data: miqSerializeForm(submit)}); else miqJqueryRequest(url, options); return false; }); // bind button click to call JS function to send up grid data $(document).on('click', 'button[data-grid_submit]', function () { return miqMenuChangeRow($(this).attr('data-grid_submit'), $(this)); }); // Bind call to check/display text area max length on keyup $(document).on('keyup', 'textarea[data-miq_check_max_length]', function () { miqCheckMaxLength(this); }); // Bind the MIQ spinning Q to configured links $(document).on('ajax:beforeSend', 'a[data-miq_sparkle_on]', function () { // Call to miqSparkleOn since miqSparkle(true) checks XHR count, which is 0 before send miqSparkleOn(); }); $(document).on('ajax:complete', 'a[data-miq_sparkle_off]', function () { miqSparkle(false); }); // Handle data-submit - triggered by handleRemote from jquery-ujs $(document).on('ajax:before', 'a[data-submit]', function () { var form_id = $(this).data('submit'); // because handleRemote will send the element's data-params as the POST body $(this).data('params', miqSerializeForm(form_id)); }); // Bind in the observe support. If interval is configured, use the observe_field function var attemptAutoRefreshTrigger = function(parms) { return function() { if (parms.auto_refresh === true) { dialogFieldRefresh.triggerAutoRefresh(parms); } }; }; var observeWithInterval = function(el, parms) { if (el.data('isObserved')) { return; } el.data('isObserved', true); var interval = parms.interval; var url = parms.url; var submit = parms.submit; el.observe_field(interval, function () { var oneTrans = this.getAttribute('data-miq_send_one_trans'); // Grab one trans URL, if present if (typeof submit != "undefined") { // If submit element passed in miqObserveRequest(url, { data: miqSerializeForm(submit), done: attemptAutoRefreshTrigger(parms), }); } else if (oneTrans) { miqSendOneTrans(url, { observe: true, done: attemptAutoRefreshTrigger(parms), }); } else { // tack on the id and value to the URL var data = {}; data[el.attr('id')] = el.prop('value'); miqObserveRequest(url, { done: attemptAutoRefreshTrigger(parms), data: data, }); } }); }; var observeOnChange = function(el, parms) { // No interval passed, use event observer el.off('change'); el.on('change', _.debounce(function() { var id = el.attr('id'); var value = el.prop('multiple') ? el.val() : encodeURIComponent(el.prop('value')); miqObserveRequest(parms.url, { no_encoding: true, data: id + '=' + value, beforeSend: !! el.attr('data-miq_sparkle_on'), complete: !! el.attr('data-miq_sparkle_off'), done: attemptAutoRefreshTrigger(parms), }); }, 700, {leading: true, trailing: true})); }; $(document).on('focus', '[data-miq_observe]', function () { var el = $(this); var parms = $.parseJSON(el.attr('data-miq_observe')); if (typeof parms.interval == "undefined") { observeOnChange(el, parms); } else { observeWithInterval(el, parms); } }); $(document).on('change', '[data-miq_observe_checkbox]', function (event) { var el = $(this); var parms = $.parseJSON(el.attr('data-miq_observe_checkbox')); var url = parms.url; var id = el.attr('id'); var value = encodeURIComponent(el.prop('checked') ? el.val() : 'null'); miqObserveRequest(url, { no_encoding: true, data: id + '=' + value, beforeSend: !! el.attr('data-miq_sparkle_on'), complete: !! el.attr('data-miq_sparkle_off'), done: attemptAutoRefreshTrigger(parms), }); event.stopPropagation(); }); ManageIQ.observeDate = function(el) { miqSendDateRequest(el); }; $(document).on('changeDate clearDate', '[data-miq_observe_date]', function() { ManageIQ.observeDate($(this)); }); // Run this last to be sure all other UJS bindings have been run in case the focus field is observed $('[data-miq_focus]').each(function(_index) { this.focus(); }); });
Spinner is ont called if data-miq_sparkle_on/off is set to false Spinner is called for every other possible value including empty string, no value, ...
app/assets/javascripts/miq_ujs_bindings.js
Spinner is ont called if data-miq_sparkle_on/off is set to false
<ide><path>pp/assets/javascripts/miq_ujs_bindings.js <ide> <ide> // Bind the MIQ spinning Q to configured links <ide> $(document).on('ajax:beforeSend', 'a[data-miq_sparkle_on]', function () { <add> // Return only if data-miq_sparkle_on is set to false <add> if ($(this).data('miq_sparkle_on') === false) { return; } <ide> // Call to miqSparkleOn since miqSparkle(true) checks XHR count, which is 0 before send <ide> miqSparkleOn(); <ide> }); <ide> $(document).on('ajax:complete', 'a[data-miq_sparkle_off]', function () { <add> // Return only if data-miq_sparkle_off is set to false <add> if ($(this).data('miq_sparkle_off') === false) { return; } <ide> miqSparkle(false); <ide> }); <ide>
JavaScript
mit
b4865e6fd5a57fad0025cf8459ef2e3dde5ab87d
0
amishne/mipui,amishne/mipui
class Tile { constructor(parent, key, x, y) { this.containerElement = createAndAppendDivWithClass(parent, 'tile'); this.mapElement = createAndAppendDivWithClass(this.containerElement, 'tile-map'); this.imageElement = document.createElement('img'); this.imageElement.className = 'tile-image'; this.imageElement.addEventListener('mouseenter', () => this.mouseEntered()); this.containerElement.appendChild(this.imageElement); this.gridLayer = createAndAppendDivWithClass(this.mapElement, 'grid-layer'); this.cells = []; this.key = key; this.x = x; this.y = y; this.dimensionsInitialized = false; this.layerElements = new Map(); this.firstCell = null; this.lastCell = null; this.left = null; this.right = null; this.top = null; this.bottom = null; this.active = false; this.deactivationTimer = null; this.isImageReady = false; this.locked = false; } initializeDimensions(left, top) { if (this.dimensionsInitialized) return; this.dimensionsInitialized = true; this.left = left; this.top = top; this.containerElement.style.left = left; this.containerElement.style.top = top; } finalizeDimensions() { if (!this.lastCell) return; this.right = this.lastCell.offsetRight; this.bottom = this.lastCell.offsetBottom; this.width = 1 + this.lastCell.offsetLeft + this.lastCell.width - this.left; this.height = 1 + this.lastCell.offsetTop + this.lastCell.height - this.top; this.containerElement.style.width = this.width; this.containerElement.style.height = this.height; this.active = true; this.deactivate(); } mouseEntered() { this.activate(); } mouseExited() { this.markForDeactivation(); } invalidateImage() { this.isImageReady = false; } activate() { if (this.active) return; this.active = true; this.containerElement.appendChild(this.mapElement); this.imageElement.style.visibility = 'hidden'; this.containerElement.style.filter = ''; clearTimeout(this.deactivationTimer); debug(`Tile ${this.key} activated.`); this.markForDeactivation(); } markForDeactivation() { if (this.deactivationTimer || this.locked) return; this.deactivationTimer = setTimeout(() => { window.requestAnimationFrame(() => { this.deactivate(); this.deactivationTimer = null; }); }, 4000 + Math.random() * 2000); } deactivate() { if (!this.active || this.locked) return; this.active = false; debug(`Tile ${this.key} deactivated.`); const start = performance.now(); if (this.isImageReady) { this.deactivationComplete(start); return; } const imageFromTheme = this.getImageFromTheme(); if (imageFromTheme) { this.imageElement.src = imageFromTheme; this.deactivationComplete(start); return; } domtoimage.toPng(this.mapElement, { width: this.containerElement.clientWidth, height: this.containerElement.clientHeight, filter: node => node.style.visibility != 'hidden' && !node.classList.contains('grid-layer'), scale: 6, // Maximum zoom level responsive: true, isInterrupted: () => this.active, disableSmoothing: true, }).then(dataUrl => { if (this.active || this.locked) return; this.imageElement.src = dataUrl; this.deactivationComplete(start); }).catch(reason => { debug(`Tile ${this.key} caching failed: ${reason}.`); }); } deactivationComplete(deactivationStartTime) { const duration = Math.ceil(performance.now() - deactivationStartTime); console.log(`Deactivated tile ${this.key} in ${duration}ms.`); this.containerElement.removeChild(this.mapElement); this.isImageReady = true; this.imageElement.style.visibility = 'visible'; this.containerElement.style.filter = 'grayscale(1)'; } lock() { this.locked = true; } unlock() { this.locked = false; this.markForDeactivation(); } getImageFromTheme() { const emptyTile5Src = themes[state.getProperty(pk.theme)].emptyTile5Src; if (emptyTile5Src) { const emptyTile = this.cells.every( cell => ct.children.every( layer => layer == ct.floors || this.layerElements.get(layer).childElementCount == 0)); if (emptyTile) { console.log(`Matched tile ${this.key} with the empty tile image.`); return emptyTile5Src; } } return null; } }
public/app/tile.js
class Tile { constructor(parent, key, x, y) { this.containerElement = createAndAppendDivWithClass(parent, 'tile'); this.mapElement = createAndAppendDivWithClass(this.containerElement, 'tile-map'); this.imageElement = document.createElement('img'); this.imageElement.className = 'tile-image'; this.imageElement.addEventListener('mouseenter', () => this.mouseEntered()); this.containerElement.appendChild(this.imageElement); this.gridLayer = createAndAppendDivWithClass(this.mapElement, 'grid-layer'); this.cells = []; this.key = key; this.x = x; this.y = y; this.dimensionsInitialized = false; this.layerElements = new Map(); this.firstCell = null; this.lastCell = null; this.left = null; this.right = null; this.top = null; this.bottom = null; this.active = false; this.deactivationTimer = null; this.isImageReady = false; this.locked = false; } initializeDimensions(left, top) { if (this.dimensionsInitialized) return; this.dimensionsInitialized = true; this.left = left; this.top = top; this.containerElement.style.left = left; this.containerElement.style.top = top; } finalizeDimensions() { if (!this.lastCell) return; this.right = this.lastCell.offsetRight; this.bottom = this.lastCell.offsetBottom; this.width = 1 + this.lastCell.offsetLeft + this.lastCell.width - this.left; this.height = 1 + this.lastCell.offsetTop + this.lastCell.height - this.top; this.containerElement.style.width = this.width; this.containerElement.style.height = this.height; this.active = true; this.deactivate(); } mouseEntered() { this.activate(); } mouseExited() { this.markForDeactivation(); } invalidateImage() { this.isImageReady = false; } activate() { if (this.active) return; this.active = true; this.containerElement.appendChild(this.mapElement); this.imageElement.style.visibility = 'hidden'; clearTimeout(this.deactivationTimer); debug(`Tile ${this.key} activated.`); this.markForDeactivation(); } markForDeactivation() { if (this.deactivationTimer || this.locked) return; this.deactivationTimer = setTimeout(() => { window.requestAnimationFrame(() => { this.deactivate(); this.deactivationTimer = null; }); }, 4000 + Math.random() * 2000); } deactivate() { if (!this.active || this.locked) return; this.active = false; debug(`Tile ${this.key} deactivated.`); const start = performance.now(); if (this.isImageReady) { this.deactivationComplete(start); return; } const imageFromTheme = this.getImageFromTheme(); if (imageFromTheme) { this.imageElement.src = imageFromTheme; this.deactivationComplete(start); return; } domtoimage.toPng(this.mapElement, { width: this.containerElement.clientWidth, height: this.containerElement.clientHeight, filter: node => node.style.visibility != 'hidden' && !node.classList.contains('grid-layer'), scale: 6, // Maximum zoom level responsive: true, isInterrupted: () => this.active, disableSmoothing: true, }).then(dataUrl => { if (this.active || this.locked) return; this.imageElement.src = dataUrl; this.deactivationComplete(start); }).catch(reason => { debug(`Tile ${this.key} caching failed: ${reason}.`); }); } deactivationComplete(deactivationStartTime) { const duration = Math.ceil(performance.now() - deactivationStartTime); debug(`Deactivated tile ${this.key} in ${duration}ms.`); this.containerElement.removeChild(this.mapElement); this.isImageReady = true; this.imageElement.style.visibility = 'visible'; } lock() { this.locked = true; } unlock() { this.locked = false; this.markForDeactivation(); } getImageFromTheme() { const emptyTile5Src = themes[state.getProperty(pk.theme)].emptyTile5Src; if (emptyTile5Src) { const emptyTile = this.cells.every( cell => ct.children.every( layer => layer == ct.floors || this.layerElements.get(layer).childElementCount == 0)); if (emptyTile) { debug(`Matched tile ${this.key} with the empty tile image.`); return emptyTile5Src; } } return null; } }
Grayscale inactive tiles for debugging purposes.
public/app/tile.js
Grayscale inactive tiles for debugging purposes.
<ide><path>ublic/app/tile.js <ide> this.active = true; <ide> this.containerElement.appendChild(this.mapElement); <ide> this.imageElement.style.visibility = 'hidden'; <add> this.containerElement.style.filter = ''; <ide> clearTimeout(this.deactivationTimer); <ide> debug(`Tile ${this.key} activated.`); <ide> this.markForDeactivation(); <ide> <ide> deactivationComplete(deactivationStartTime) { <ide> const duration = Math.ceil(performance.now() - deactivationStartTime); <del> debug(`Deactivated tile ${this.key} in ${duration}ms.`); <add> console.log(`Deactivated tile ${this.key} in ${duration}ms.`); <ide> this.containerElement.removeChild(this.mapElement); <ide> this.isImageReady = true; <ide> this.imageElement.style.visibility = 'visible'; <add> this.containerElement.style.filter = 'grayscale(1)'; <ide> } <ide> <ide> lock() { <ide> layer => layer == ct.floors || <ide> this.layerElements.get(layer).childElementCount == 0)); <ide> if (emptyTile) { <del> debug(`Matched tile ${this.key} with the empty tile image.`); <add> console.log(`Matched tile ${this.key} with the empty tile image.`); <ide> return emptyTile5Src; <ide> } <ide> }
Java
apache-2.0
eaf87987a839bbe92c2688e3d97e39fb53cd0282
0
raydac/netbeans-mmd-plugin,raydac/netbeans-mmd-plugin,raydac/netbeans-mmd-plugin,raydac/netbeans-mmd-plugin
/* * Copyright 2015-2018 Igor Maznitsa. * * 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.igormaznitsa.mindmap.swing.panel.utils; import com.igormaznitsa.meta.annotation.ImplementationNote; import com.igormaznitsa.meta.annotation.MayContainNull; import com.igormaznitsa.meta.annotation.MustNotContainNull; import com.igormaznitsa.meta.annotation.ReturnsOriginal; import com.igormaznitsa.mindmap.model.Topic; import com.igormaznitsa.mindmap.model.logger.Logger; import com.igormaznitsa.mindmap.model.logger.LoggerFactory; import com.igormaznitsa.mindmap.plugins.MindMapPluginRegistry; import com.igormaznitsa.mindmap.plugins.PopUpSection; import com.igormaznitsa.mindmap.plugins.api.PluginContext; import com.igormaznitsa.mindmap.plugins.api.PopUpMenuItemPlugin; import com.igormaznitsa.mindmap.swing.panel.DialogProvider; import com.igormaznitsa.mindmap.swing.panel.MindMapPanelConfig; import com.igormaznitsa.mindmap.swing.panel.ui.AbstractCollapsableElement; import com.igormaznitsa.mindmap.swing.panel.ui.AbstractElement; import com.igormaznitsa.mindmap.swing.panel.ui.gfx.MMGraphics; import com.igormaznitsa.mindmap.swing.panel.ui.gfx.MMGraphics2DWrapper; import com.igormaznitsa.mindmap.swing.services.*; import net.iharder.Base64; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.SystemUtils; import org.jsoup.Jsoup; import org.jsoup.helper.W3CDom; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.event.*; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.RenderedImage; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public final class Utils { public static final ResourceBundle BUNDLE = java.util.ResourceBundle.getBundle("com/igormaznitsa/mindmap/swing/panel/Bundle"); public static final UIComponentFactory UI_COMPO_FACTORY = UIComponentFactoryProvider.findInstance(); public static final ImageIconService ICON_SERVICE = ImageIconServiceProvider.findInstance(); public static final String PROPERTY_MAX_EMBEDDED_IMAGE_SIDE_SIZE = "mmap.max.image.side.size"; //NOI18N public static final boolean LTR_LANGUAGE = ComponentOrientation.getOrientation(new Locale(System.getProperty("user.language"))).isLeftToRight(); private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class); private static final Pattern URI_PATTERN = Pattern.compile("^(?:([^:\\s]+):)(?://(?:[^?/@\\s]*@)?([^/?\\s]*)/?)?([^?\\s]+)?(?:\\?([^#\\s]*))?(?:#\\S*)?$"); private static final int MAX_IMAGE_SIDE_SIZE_IN_PIXELS = 350; private static final Pattern STRIP_PATTERN = Pattern.compile("^(\\s*)(.*[^\\s])(\\s*)$"); private Utils() { } /** * Get input stream for resource in zip file. * * @param zipFile zip file * @param resourcePath path to resource * @return input stream for resource or null if not found or directory * @throws IOException if there is any transport error */ @Nullable public static InputStream findInputStreamForResource(@Nonnull final ZipFile zipFile, @Nonnull final String resourcePath) throws IOException { final ZipEntry entry = zipFile.getEntry(resourcePath); InputStream result = null; if (entry != null && !entry.isDirectory()) { result = zipFile.getInputStream(entry); } return result; } /** * Read who;e zip item into byte array. * * @param zipFile zip file * @param path path to resource * @return byte array or null if not found * @throws IOException thrown if there is any transport error */ @Nullable public static byte[] toByteArray(@Nonnull final ZipFile zipFile, @Nonnull final String path) throws IOException { final InputStream in = findInputStreamForResource(zipFile, path); byte[] result = null; if (in != null) { try { result = IOUtils.toByteArray(in); } finally { IOUtils.closeQuietly(in); } } return result; } @Nonnull public static Document loadHtmlDocument(@Nonnull final InputStream inStream, @Nullable final String charset, final boolean autoClose) throws ParserConfigurationException, IOException { try { final org.jsoup.nodes.Document result = Jsoup.parse(IOUtils.toString(inStream, charset)); return new W3CDom().fromJsoup(result); } finally { if (autoClose) { IOUtils.closeQuietly(inStream); } } } /** * Load and parse XML document from input stream. * * @param inStream stream to read document * @param charset charset to be used for loading, can be null * @param autoClose true if stream must be closed, false otherwise * @return parsed document * @throws IOException will be thrown if transport error * @throws ParserConfigurationException will be thrown if parsing error * @throws SAXException will be thrown if SAX error * @since 1.4.0 */ @Nonnull public static Document loadXmlDocument(@Nonnull final InputStream inStream, @Nullable final String charset, final boolean autoClose) throws SAXException, IOException, ParserConfigurationException { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (final ParserConfigurationException ex) { LOGGER.error("Can't set feature for XML parser : " + ex.getMessage(), ex); throw new SAXException("Can't set flag to use security processing of XML file"); } try { factory.setFeature("http://apache.org/xml/features/validation/schema", false); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); } catch (final ParserConfigurationException ex) { LOGGER.warn("Can't set some features for XML parser : " + ex.getMessage()); } factory.setIgnoringComments(true); factory.setValidating(false); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document; try { final InputStream stream; if (charset == null) { stream = inStream; } else { stream = new ByteArrayInputStream(IOUtils.toString(inStream, charset).getBytes(StandardCharsets.UTF_8)); } document = builder.parse(stream); } finally { if (autoClose) { IOUtils.closeQuietly(inStream); } } return document; } /** * Get first direct child for name. * * @param node element to find children * @param elementName name of child element * @return found first child or null if not found * @since 1.4.0 */ @Nullable public static Element findFirstElement(@Nonnull final Element node, @Nonnull final String elementName) { Element result = null; for (final Element l : Utils.findDirectChildrenForName(node, elementName)) { result = l; break; } return result; } /** * Find all direct children with defined name. * * @param element parent element * @param childElementname child element name * @return list of found elements * @since 1.4.0 */ @Nonnull @MustNotContainNull public static List<Element> findDirectChildrenForName(@Nonnull final Element element, @Nonnull final String childElementname) { final List<Element> resultList = new ArrayList<>(); final NodeList list = element.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { final Node node = list.item(i); if (element.equals(node.getParentNode()) && node instanceof Element && childElementname.equals(node.getNodeName())) { resultList.add((Element) node); } } return resultList; } /** * Allows to check that some string has URI in appropriate format. * * @param uri string to be checked, must not be null * @return true if the string contains correct uri, false otherwise */ public static boolean isUriCorrect(@Nonnull final String uri) { return URI_PATTERN.matcher(uri).matches(); } /** * Get max image size. * * @return max image size * @see #MAX_IMAGE_SIDE_SIZE_IN_PIXELS * @see #PROPERTY_MAX_EMBEDDED_IMAGE_SIDE_SIZE */ public static int getMaxImageSize() { int result = MAX_IMAGE_SIDE_SIZE_IN_PIXELS; try { final String defined = System.getProperty(PROPERTY_MAX_EMBEDDED_IMAGE_SIDE_SIZE); if (defined != null) { LOGGER.info("Detected redefined max size for embedded image side : " + defined); //NOI18N result = Math.max(8, Integer.parseInt(defined.trim())); } } catch (NumberFormatException ex) { LOGGER.error("Error during image size decoding : ", ex); //NOI18N } return result; } /** * Load and encode image into Base64. * * @param in stream to read image * @param maxSize max size of image, if less or zero then don't rescale * @return null if it was impossible to load image for its format, loaded * prepared image * @throws IOException if any error during conversion or loading * @since 1.4.0 */ @Nullable public static String rescaleImageAndEncodeAsBase64(@Nonnull final InputStream in, final int maxSize) throws IOException { final Image image = ImageIO.read(in); String result = null; if (image != null) { result = rescaleImageAndEncodeAsBase64(image, maxSize); } return result; } /** * Load and encode image into Base64 from file. * * @param file image file * @param maxSize max size of image, if less or zero then don't rescale * @return image * @throws IOException if any error during conversion or loading * @since 1.4.0 */ @Nonnull public static String rescaleImageAndEncodeAsBase64(@Nonnull final File file, final int maxSize) throws IOException { final Image image = ImageIO.read(file); if (image == null) { throw new IllegalArgumentException("Can't load image file : " + file); //NOI18N } return rescaleImageAndEncodeAsBase64(image, maxSize); } /** * Get default render quality for host OS. * * @return the render quality for host OS, must not be null * @since 1.4.5 */ @Nonnull public static RenderQuality getDefaultRenderQialityForOs() { RenderQuality result = RenderQuality.DEFAULT; if (SystemUtils.IS_OS_MAC || SystemUtils.IS_OS_WINDOWS) { result = RenderQuality.QUALITY; } return result; } /** * Rescale image and encode into Base64. * * @param image image to rescale and encode * @param maxSize max size of image, if less or zero then don't rescale * @return scaled and encoded image * @throws IOException if it was impossible to encode image * @since 1.4.0 */ @Nonnull public static String rescaleImageAndEncodeAsBase64(@Nonnull Image image, final int maxSize) throws IOException { final int width = image.getWidth(null); final int height = image.getHeight(null); final int maxImageSideSize = maxSize > 0 ? maxSize : Math.max(width, height); final float imageScale = width > maxImageSideSize || height > maxImageSideSize ? (float) maxImageSideSize / (float) Math.max(width, height) : 1.0f; if (!(image instanceof RenderedImage) || Float.compare(imageScale, 1.0f) != 0) { final int swidth; final int sheight; if (Float.compare(imageScale, 1.0f) == 0) { swidth = width; sheight = height; } else { swidth = Math.round(imageScale * width); sheight = Math.round(imageScale * height); } final BufferedImage buffer = new BufferedImage(swidth, sheight, BufferedImage.TYPE_INT_ARGB); final Graphics2D gfx = buffer.createGraphics(); gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); gfx.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); gfx.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); gfx.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); gfx.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE); gfx.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); gfx.drawImage(image, AffineTransform.getScaleInstance(imageScale, imageScale), null); gfx.dispose(); image = buffer; } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { if (!ImageIO.write((RenderedImage) image, "png", bos)) { throw new IOException("Can't encode image as PNG"); } } finally { IOUtils.closeQuietly(bos); } return Utils.base64encode(bos.toByteArray()); } public static int calculateColorBrightness(@Nonnull final Color color) { return (int) Math.sqrt(color.getRed() * color.getRed() * .241d + color.getGreen() * color.getGreen() * .691d + color.getBlue() * color.getBlue() * .068d); } public static boolean isDarkTheme() { final Color panelBack = UIManager.getColor("Panel.background"); if (panelBack == null) { return false; } else { return calculateColorBrightness(panelBack) < 150; } } @Nonnull public static String convertCamelCasedToHumanForm(@Nonnull final String camelCasedString, final boolean capitalizeFirstChar) { final StringBuilder result = new StringBuilder(); boolean notFirst = false; for (final char c : camelCasedString.toCharArray()) { if (notFirst) { if (Character.isUpperCase(c)) { result.append(' '); result.append(Character.toLowerCase(c)); } else { result.append(c); } } else { notFirst = true; if (capitalizeFirstChar) { result.append(Character.toUpperCase(c)); } else { result.append(c); } } } return result.toString(); } @Nonnull @MustNotContainNull public static Topic[] getLeftToRightOrderedChildrens(@Nonnull final Topic topic) { final List<Topic> result = new ArrayList<>(); if (topic.getTopicLevel() == 0) { for (final Topic t : topic.getChildren()) { if (AbstractCollapsableElement.isLeftSidedTopic(t)) { result.add(t); } } for (final Topic t : topic.getChildren()) { if (!AbstractCollapsableElement.isLeftSidedTopic(t)) { result.add(t); } } } else { result.addAll(topic.getChildren()); } return result.toArray(new Topic[0]); } public static boolean safeObjectEquals(@Nullable final Object obj1, @Nullable final Object obj2) { if (obj1 == obj2) { return true; } if (obj1 == null || obj2 == null) { return false; } return obj1.equals(obj2); } public static void setAttribute(@Nonnull final String name, @Nullable final String value, @Nonnull @MustNotContainNull final Topic[] topics) { for (final Topic t : topics) { t.setAttribute(name, value); } } @Nullable public static Color html2color(@Nullable final String str, final boolean hasAlpha) { Color result = null; if (str != null && !str.isEmpty() && str.charAt(0) == '#') { try { String color = str.substring(1); if (color.length() > 6) { color = color.substring(color.length() - 6); } if (color.length() == 6) { result = new Color(Integer.parseInt(color, 16), hasAlpha); } else if (color.length() == 3) { final int r = Integer.parseInt(color.charAt(0) + "0", 16); final int g = Integer.parseInt(color.charAt(1) + "0", 16); final int b = Integer.parseInt(color.charAt(2) + "0", 16); result = new Color(r, g, b); } } catch (NumberFormatException ex) { LOGGER.warn(String.format("Can't convert %s to color", str)); } } return result; } @Nullable public static String color2html(@Nullable final Color color, final boolean hasAlpha) { String result = null; if (color != null) { final StringBuilder buffer = new StringBuilder(); buffer.append('#'); final int[] components; if (hasAlpha) { components = new int[]{color.getAlpha(), color.getRed(), color.getGreen(), color.getBlue()}; } else { components = new int[]{color.getRed(), color.getGreen(), color.getBlue()}; } for (final int c : components) { final String str = Integer.toHexString(c & 0xFF).toUpperCase(Locale.ENGLISH); if (str.length() < 2) { buffer.append('0'); } buffer.append(str); } result = buffer.toString(); } return result; } @Nonnull public static String getFirstLine(@Nonnull final String text) { return text.replace("\r", "").split("\\n")[0]; //NOI18N } @Nonnull public static String makeShortTextVersion(@Nonnull String text, final int maxLength) { if (text.length() > maxLength) { text = text.substring(0, maxLength) + "..."; //NOI18N } return text; } public static void safeSwingCall(@Nonnull final Runnable runnable) { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); } else { SwingUtilities.invokeLater(runnable); } } public static void safeSwingBlockingCall(@Nonnull final Runnable runnable) { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); } else { try { SwingUtilities.invokeAndWait(runnable); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } catch (InvocationTargetException ex) { throw new RuntimeException("Detected exception during SwingUtilities.invokeAndWait", ex); } } } @Nonnull @MustNotContainNull public static String[] breakToLines(@Nonnull final String text) { final int lineNum = numberOfLines(text); final String[] result = new String[lineNum]; final StringBuilder line = new StringBuilder(); int index = 0; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == '\n') { result[index++] = line.toString(); line.setLength(0); } else { line.append(text.charAt(i)); } } result[index] = line.toString(); return result; } public static int numberOfLines(@Nonnull final String text) { int result = 1; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == '\n') { result++; } } return result; } @ImplementationNote("Must be called from Swing UI thread") public static void foldUnfoldTree(@Nonnull final JTree tree, final boolean unfold) { final TreeModel model = tree.getModel(); if (model != null) { final Object root = model.getRoot(); if (root != null) { final TreePath thePath = new TreePath(root); setTreeState(tree, thePath, true, unfold); if (!unfold) { setTreeState(tree, thePath, false, true); } } } } private static void setTreeState(@Nonnull final JTree tree, @Nonnull final TreePath path, final boolean recursively, final boolean unfold) { final Object lastNode = path.getLastPathComponent(); for (int i = 0; i < tree.getModel().getChildCount(lastNode); i++) { final Object child = tree.getModel().getChild(lastNode, i); final TreePath pathToChild = path.pathByAddingChild(child); if (recursively) { setTreeState(tree, pathToChild, recursively, unfold); } } if (unfold) { tree.expandPath(path); } else { tree.collapsePath(path); } } public static @Nonnull String removeAllISOControlsButTabs(@Nonnull final String str) { final StringBuilder result = new StringBuilder(str.length()); for (final char c : str.toCharArray()) { if (c != '\t' && Character.isISOControl(c)) { continue; } result.append(c); } return result.toString(); } @Nullable public static Point2D findRectEdgeIntersection(@Nonnull final Rectangle2D rect, final double outboundX, final double outboundY) { final int detectedSide = rect.outcode(outboundX, outboundY); if ((detectedSide & (Rectangle2D.OUT_TOP | Rectangle2D.OUT_BOTTOM)) != 0) { final boolean top = (detectedSide & Rectangle2D.OUT_BOTTOM) == 0; final double dx = outboundX - rect.getCenterX(); if (dx == 0.0d) { return new Point2D.Double(rect.getCenterX(), top ? rect.getMinY() : rect.getMaxY()); } else { final double halfy = top ? rect.getHeight() / 2 : -rect.getHeight() / 2; final double coeff = (outboundY - rect.getCenterY()) / dx; final double calculatedX = rect.getCenterX() - (halfy / coeff); if (calculatedX >= rect.getMinX() && calculatedX <= rect.getMaxX()) { return new Point2D.Double(calculatedX, top ? rect.getMinY() : rect.getMaxY()); } } } if ((detectedSide & (Rectangle2D.OUT_LEFT | Rectangle2D.OUT_RIGHT)) != 0) { final boolean left = (detectedSide & Rectangle2D.OUT_RIGHT) == 0; final double dy = outboundY - rect.getCenterY(); if (dy == 0.0d) { return new Point2D.Double(left ? rect.getMinX() : rect.getMaxX(), rect.getCenterY()); } else { final double halfx = left ? rect.getWidth() / 2 : -rect.getWidth() / 2; final double coeff = (outboundX - rect.getCenterX()) / dy; final double calculatedY = rect.getCenterY() - (halfx / coeff); if (calculatedY >= rect.getMinY() && calculatedY <= rect.getMaxY()) { return new Point2D.Double(left ? rect.getMinX() : rect.getMaxX(), calculatedY); } } } return null; } public static boolean isPlantUmlFileExtension(@Nonnull final String lowerCasedTrimmedExtension) { boolean result = false; if (lowerCasedTrimmedExtension.length() > 1 && lowerCasedTrimmedExtension.charAt(0) == 'p') { result = "pu".equals(lowerCasedTrimmedExtension) || "puml".equals(lowerCasedTrimmedExtension) || "plantuml".equals(lowerCasedTrimmedExtension); } return result; } @Nullable public static Image scaleImage(@Nonnull final Image src, final double baseScaleX, final double baseScaleY, final double scale) { final int imgw = src.getWidth(null); final int imgh = src.getHeight(null); final int scaledW = (int) Math.round(imgw * baseScaleX * scale); final int scaledH = (int) Math.round(imgh * baseScaleY * scale); BufferedImage result = null; if (scaledH > 0 && scaledW > 0) { try { result = new BufferedImage(scaledW, scaledH, BufferedImage.TYPE_INT_ARGB); final Graphics2D g = (Graphics2D) result.getGraphics(); RenderQuality.QUALITY.prepare(g); g.drawImage(src, 0, 0, scaledW, scaledH, null); g.dispose(); } catch (OutOfMemoryError e) { LOGGER.error("OutOfmemoryError in scaleImage (" + baseScaleX + ',' + baseScaleY + ',' + scale + ')', e); throw e; } } return result; } @Nonnull public static Image renderWithTransparency(final float opacity, @Nonnull final AbstractElement element, @Nonnull final MindMapPanelConfig config, @Nonnull final RenderQuality quality) { final AbstractElement cloned = element.makeCopy(); final Rectangle2D bounds = cloned.getBounds(); final float increase = config.safeScaleFloatValue(config.getElementBorderWidth() + config.getShadowOffset(), 0.0f); final int imageWidth = (int) Math.round(bounds.getWidth() + increase); final int imageHeight = (int) Math.round(bounds.getHeight() + increase); bounds.setRect(0.0d, 0.0d, bounds.getWidth(), bounds.getHeight()); final BufferedImage result = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB); for (int y = 0; y < imageHeight; y++) { for (int x = 0; x < imageWidth; x++) { result.setRGB(x, y, 0); } } final Graphics2D g = result.createGraphics(); final MMGraphics gfx = new MMGraphics2DWrapper(g); try { quality.prepare(g); cloned.doPaint(gfx, config, false); } finally { gfx.dispose(); } int alpha; if (opacity <= 0.0f) { alpha = 0x00; } else if (opacity >= 1.0f) { alpha = 0xFF; } else { alpha = Math.round(0xFF * opacity); } alpha <<= 24; for (int y = 0; y < imageHeight; y++) { for (int x = 0; x < imageWidth; x++) { final int curAlpha = result.getRGB(x, y) >>> 24; if (curAlpha == 0xFF) { result.setRGB(x, y, (result.getRGB(x, y) & 0xFFFFFF) | alpha); } else if (curAlpha != 0x00) { final int calculated = Math.round(curAlpha * opacity) << 24; result.setRGB(x, y, (result.getRGB(x, y) & 0xFFFFFF) | calculated); } } } return result; } @Nonnull public static Color makeContrastColor(@Nonnull final Color color) { return new Color(color.getRed() ^ 0xFF, color.getGreen() ^ 0xFF, color.getBlue() ^ 0xFF); } @Nonnull @MustNotContainNull private static List<JMenuItem> findPopupMenuItems( @Nonnull final PluginContext context, @Nonnull final PopUpSection section, final boolean fullScreenModeActive, @Nonnull @MayContainNull final List<JMenuItem> list, @Nullable final Topic topicUnderMouse, @Nonnull @MustNotContainNull final List<PopUpMenuItemPlugin> pluginMenuItems ) { list.clear(); for (final PopUpMenuItemPlugin p : pluginMenuItems) { if (fullScreenModeActive && !p.isCompatibleWithFullScreenMode()) { continue; } if (p.getSection() == section) { if (!(p.needsTopicUnderMouse() || p.needsSelectedTopics()) || (p.needsTopicUnderMouse() && topicUnderMouse != null) || (p.needsSelectedTopics() && context.getSelectedTopics().length > 0)) { final JMenuItem item = p.makeMenuItem(context, topicUnderMouse); if (item != null) { item.setEnabled(p.isEnabled(context, topicUnderMouse)); list.add(item); } } } } return list; } public static void assertSwingDispatchThread() { if (!SwingUtilities.isEventDispatchThread()) { throw new Error("Must be called in Swing dispatch thread"); } } @Nonnull @MustNotContainNull private static List<JMenuItem> putAllItemsAsSection(@Nonnull final JPopupMenu menu, @Nullable final JMenu subMenu, @Nonnull @MustNotContainNull final List<JMenuItem> items) { if (!items.isEmpty()) { if (menu.getComponentCount() > 0) { menu.add(UI_COMPO_FACTORY.makeMenuSeparator()); } for (final JMenuItem i : items) { if (subMenu == null) { menu.add(i); } else { subMenu.add(i); } } if (subMenu != null) { menu.add(subMenu); } } return items; } public static boolean isDataFlavorAvailable(@Nonnull final Clipboard clipboard, @Nonnull final DataFlavor flavor) { boolean result = false; try { result = clipboard.isDataFlavorAvailable(flavor); } catch (final IllegalStateException ex) { LOGGER.warn("Can't get access to clipboard : " + ex.getMessage()); } return result; } @Nonnull public static JPopupMenu makePopUp( @Nonnull final PluginContext context, final boolean fullScreenModeActive, @Nullable final Topic topicUnderMouse ) { final JPopupMenu result = UI_COMPO_FACTORY.makePopupMenu(); final List<PopUpMenuItemPlugin> pluginMenuItems = MindMapPluginRegistry.getInstance().findFor(PopUpMenuItemPlugin.class); final List<JMenuItem> tmpList = new ArrayList<>(); final boolean isModelNotEmpty = context.getPanel().getModel().getRoot() != null; putAllItemsAsSection(result, null, findPopupMenuItems(context, PopUpSection.MAIN, fullScreenModeActive, tmpList, topicUnderMouse, pluginMenuItems)); putAllItemsAsSection(result, null, findPopupMenuItems(context, PopUpSection.MANIPULATORS, fullScreenModeActive, tmpList, topicUnderMouse, pluginMenuItems)); putAllItemsAsSection(result, null, findPopupMenuItems(context, PopUpSection.EXTRAS, fullScreenModeActive, tmpList, topicUnderMouse, pluginMenuItems)); final JMenu exportMenu = UI_COMPO_FACTORY.makeMenu(BUNDLE.getString("MMDExporters.SubmenuName")); exportMenu.setIcon(ICON_SERVICE.getIconForId(IconID.POPUP_EXPORT)); final JMenu importMenu = UI_COMPO_FACTORY.makeMenu(BUNDLE.getString("MMDImporters.SubmenuName")); importMenu.setIcon(ICON_SERVICE.getIconForId(IconID.POPUP_IMPORT)); putAllItemsAsSection(result, importMenu, findPopupMenuItems(context, PopUpSection.IMPORT, fullScreenModeActive, tmpList, topicUnderMouse, pluginMenuItems)); if (isModelNotEmpty) { putAllItemsAsSection(result, exportMenu, findPopupMenuItems(context, PopUpSection.EXPORT, fullScreenModeActive, tmpList, topicUnderMouse, pluginMenuItems)); } putAllItemsAsSection(result, null, findPopupMenuItems(context, PopUpSection.TOOLS, fullScreenModeActive, tmpList, topicUnderMouse, pluginMenuItems)); putAllItemsAsSection(result, null, findPopupMenuItems(context, PopUpSection.MISC, fullScreenModeActive, tmpList, topicUnderMouse, pluginMenuItems)); return result; } public static boolean isKeyStrokeEvent(@Nullable final KeyStroke keyStroke, final int keyEventType, @Nullable final KeyEvent event) { boolean result = false; if (keyStroke != null && event != null) { if (keyEventType == keyStroke.getKeyEventType()) { result = ((keyStroke.getModifiers() & event.getModifiers()) == keyStroke.getModifiers()) && (keyStroke.getKeyCode() == event.getKeyCode()); } } return result; } @Nonnull @MustNotContainNull private static List<JButton> findAllOptionPaneButtons(@Nonnull final JComponent component) { final List<JButton> result = new ArrayList<>(); Arrays.stream(component.getComponents()) .filter(x -> x instanceof JComponent) .map(x -> (JComponent) x) .forEach(x -> { if (x instanceof JButton) { if ("OptionPane.button".equals(x.getName())) { result.add((JButton) x); } } else { result.addAll(findAllOptionPaneButtons(x)); } }); return result; } private static void replaceActionListenerForButton(@Nonnull final JButton button, @Nonnull final ActionListener listener) { final ActionListener[] currentListeners = button.getActionListeners(); for (final ActionListener l : currentListeners) { button.removeActionListener(l); } button.addActionListener(listener); } @Nonnull @SafeVarargs @ReturnsOriginal public static JComponent catchEscInParentDialog( @Nonnull final JComponent component, @Nonnull final DialogProvider dialogProvider, @Nullable final Predicate<JDialog> doClose, @Nonnull @MustNotContainNull final Consumer<JDialog>... beforeClose) { component.addHierarchyListener(new HierarchyListener() { final Consumer<JDialog> processor = dialog -> { final boolean close; if (doClose == null) { close = true; } else { if (doClose.test(dialog)) { close = dialogProvider .msgConfirmOkCancel(dialog, BUNDLE.getString("Utils.confirmActionTitle"), BUNDLE.getString("Utils.closeForContentChange")); } else { close = true; } } if (close) { try { for (final Consumer<JDialog> c : beforeClose) { try { c.accept(dialog); } catch (Exception ex) { LOGGER.error("Error during before close call", ex); } } } finally { dialog.dispose(); } } }; private final KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false); private final List<WindowListener> foundWindowListeners = new ArrayList<>(); @Override public void hierarchyChanged(@Nonnull final HierarchyEvent e) { final Window window = SwingUtilities.getWindowAncestor(component); if (window instanceof JDialog && (e.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) != 0) { final JDialog dialog = (JDialog) window; final List<JButton> dialogButtons = findAllOptionPaneButtons(dialog.getRootPane()); dialogButtons.stream() .filter(x -> "cancel".equalsIgnoreCase(x.getText())) .forEach(x -> replaceActionListenerForButton(x, be -> { processor.accept(dialog); })); dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); final WindowListener windowListener = new WindowListener() { @Override public void windowClosing(@Nonnull final WindowEvent e) { processor.accept(dialog); } @Override public void windowOpened(@Nonnull final WindowEvent e) { foundWindowListeners.forEach(x -> x.windowOpened(e)); } @Override public void windowClosed(@Nonnull final WindowEvent e) { foundWindowListeners.forEach(x -> x.windowClosed(e)); } @Override public void windowIconified(@Nonnull final WindowEvent e) { foundWindowListeners.forEach(x -> x.windowIconified(e)); } @Override public void windowDeiconified(@Nonnull final WindowEvent e) { foundWindowListeners.forEach(x -> x.windowDeiconified(e)); } @Override public void windowActivated(@Nonnull final WindowEvent e) { foundWindowListeners.forEach(x -> x.windowActivated(e)); } @Override public void windowDeactivated(@Nonnull final WindowEvent e) { foundWindowListeners.forEach(x -> x.windowDeactivated(e)); } }; if (this.foundWindowListeners.isEmpty()) { final WindowListener[] windowListeners = dialog.getWindowListeners(); for (final WindowListener w : windowListeners) { dialog.removeWindowListener(w); this.foundWindowListeners.add(w); } dialog.addWindowListener(windowListener); } final InputMap inputMap = dialog.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(escapeKeyStroke, "PRESSING_ESCAPE"); final ActionMap actionMap = dialog.getRootPane().getActionMap(); actionMap.put("PRESSING_ESCAPE", new AbstractAction() { @Override public void actionPerformed(@Nonnull final ActionEvent e) { processor.accept(dialog); } }); } } }); return component; } @Nonnull public static byte[] base64decode(@Nonnull final String text) throws IOException { return Base64.decode(text); } @Nonnull public static String strip(@Nonnull final String str, final boolean leading) { if (str.trim().isEmpty()) { return ""; } final Matcher matcher = STRIP_PATTERN.matcher(str); if (!matcher.find()) { throw new Error("Unexpected error in strip(String): " + str); } return leading ? matcher.group(2) + matcher.group(3) : matcher.group(1) + matcher.group(2); } @Nonnull public static String base64encode(@Nonnull final byte[] data) { return Base64.encodeBytes(data); } }
mind-map/mind-map-swing-panel/src/main/java/com/igormaznitsa/mindmap/swing/panel/utils/Utils.java
/* * Copyright 2015-2018 Igor Maznitsa. * * 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.igormaznitsa.mindmap.swing.panel.utils; import com.igormaznitsa.meta.annotation.ImplementationNote; import com.igormaznitsa.meta.annotation.MayContainNull; import com.igormaznitsa.meta.annotation.MustNotContainNull; import com.igormaznitsa.meta.annotation.ReturnsOriginal; import com.igormaznitsa.mindmap.model.Topic; import com.igormaznitsa.mindmap.model.logger.Logger; import com.igormaznitsa.mindmap.model.logger.LoggerFactory; import com.igormaznitsa.mindmap.plugins.MindMapPluginRegistry; import com.igormaznitsa.mindmap.plugins.PopUpSection; import com.igormaznitsa.mindmap.plugins.api.PluginContext; import com.igormaznitsa.mindmap.plugins.api.PopUpMenuItemPlugin; import com.igormaznitsa.mindmap.swing.panel.DialogProvider; import com.igormaznitsa.mindmap.swing.panel.MindMapPanelConfig; import com.igormaznitsa.mindmap.swing.panel.ui.AbstractCollapsableElement; import com.igormaznitsa.mindmap.swing.panel.ui.AbstractElement; import com.igormaznitsa.mindmap.swing.panel.ui.gfx.MMGraphics; import com.igormaznitsa.mindmap.swing.panel.ui.gfx.MMGraphics2DWrapper; import com.igormaznitsa.mindmap.swing.services.*; import net.iharder.Base64; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.SystemUtils; import org.jsoup.Jsoup; import org.jsoup.helper.W3CDom; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.event.*; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.RenderedImage; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public final class Utils { public static final ResourceBundle BUNDLE = java.util.ResourceBundle.getBundle("com/igormaznitsa/mindmap/swing/panel/Bundle"); public static final UIComponentFactory UI_COMPO_FACTORY = UIComponentFactoryProvider.findInstance(); public static final ImageIconService ICON_SERVICE = ImageIconServiceProvider.findInstance(); public static final String PROPERTY_MAX_EMBEDDED_IMAGE_SIDE_SIZE = "mmap.max.image.side.size"; //NOI18N public static final boolean LTR_LANGUAGE = ComponentOrientation.getOrientation(new Locale(System.getProperty("user.language"))).isLeftToRight(); private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class); private static final Pattern URI_PATTERN = Pattern.compile("^(?:([^:\\s]+):)(?://(?:[^?/@\\s]*@)?([^/?\\s]*)/?)?([^?\\s]+)?(?:\\?([^#\\s]*))?(?:#\\S*)?$"); private static final int MAX_IMAGE_SIDE_SIZE_IN_PIXELS = 350; private static final Pattern STRIP_PATTERN = Pattern.compile("^(\\s*)(.*[^\\s])(\\s*)$"); private Utils() { } /** * Get input stream for resource in zip file. * * @param zipFile zip file * @param resourcePath path to resource * @return input stream for resource or null if not found or directory * @throws IOException if there is any transport error */ @Nullable public static InputStream findInputStreamForResource(@Nonnull final ZipFile zipFile, @Nonnull final String resourcePath) throws IOException { final ZipEntry entry = zipFile.getEntry(resourcePath); InputStream result = null; if (entry != null && !entry.isDirectory()) { result = zipFile.getInputStream(entry); } return result; } /** * Read who;e zip item into byte array. * * @param zipFile zip file * @param path path to resource * @return byte array or null if not found * @throws IOException thrown if there is any transport error */ @Nullable public static byte[] toByteArray(@Nonnull final ZipFile zipFile, @Nonnull final String path) throws IOException { final InputStream in = findInputStreamForResource(zipFile, path); byte[] result = null; if (in != null) { try { result = IOUtils.toByteArray(in); } finally { IOUtils.closeQuietly(in); } } return result; } @Nonnull public static Document loadHtmlDocument(@Nonnull final InputStream inStream, @Nullable final String charset, final boolean autoClose) throws ParserConfigurationException, IOException { try { final org.jsoup.nodes.Document result = Jsoup.parse(IOUtils.toString(inStream, charset)); return new W3CDom().fromJsoup(result); } finally { if (autoClose) { IOUtils.closeQuietly(inStream); } } } /** * Load and parse XML document from input stream. * * @param inStream stream to read document * @param charset charset to be used for loading, can be null * @param autoClose true if stream must be closed, false otherwise * @return parsed document * @throws IOException will be thrown if transport error * @throws ParserConfigurationException will be thrown if parsing error * @throws SAXException will be thrown if SAX error * @since 1.4.0 */ @Nonnull public static Document loadXmlDocument(@Nonnull final InputStream inStream, @Nullable final String charset, final boolean autoClose) throws SAXException, IOException, ParserConfigurationException { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (final ParserConfigurationException ex) { LOGGER.error("Can't set feature for XML parser : " + ex.getMessage(), ex); throw new SAXException("Can't set flag to use security processing of XML file"); } try { factory.setFeature("http://apache.org/xml/features/validation/schema", false); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); } catch (final ParserConfigurationException ex) { LOGGER.warn("Can't set some features for XML parser : " + ex.getMessage()); } factory.setIgnoringComments(true); factory.setValidating(false); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document; try { final InputStream stream; if (charset == null) { stream = inStream; } else { stream = new ByteArrayInputStream(IOUtils.toString(inStream, charset).getBytes(StandardCharsets.UTF_8)); } document = builder.parse(stream); } finally { if (autoClose) { IOUtils.closeQuietly(inStream); } } return document; } /** * Get first direct child for name. * * @param node element to find children * @param elementName name of child element * @return found first child or null if not found * @since 1.4.0 */ @Nullable public static Element findFirstElement(@Nonnull final Element node, @Nonnull final String elementName) { Element result = null; for (final Element l : Utils.findDirectChildrenForName(node, elementName)) { result = l; break; } return result; } /** * Find all direct children with defined name. * * @param element parent element * @param childElementname child element name * @return list of found elements * @since 1.4.0 */ @Nonnull @MustNotContainNull public static List<Element> findDirectChildrenForName(@Nonnull final Element element, @Nonnull final String childElementname) { final List<Element> resultList = new ArrayList<>(); final NodeList list = element.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { final Node node = list.item(i); if (element.equals(node.getParentNode()) && node instanceof Element && childElementname.equals(node.getNodeName())) { resultList.add((Element) node); } } return resultList; } /** * Allows to check that some string has URI in appropriate format. * * @param uri string to be checked, must not be null * @return true if the string contains correct uri, false otherwise */ public static boolean isUriCorrect(@Nonnull final String uri) { return URI_PATTERN.matcher(uri).matches(); } /** * Get max image size. * * @return max image size * @see #MAX_IMAGE_SIDE_SIZE_IN_PIXELS * @see #PROPERTY_MAX_EMBEDDED_IMAGE_SIDE_SIZE */ public static int getMaxImageSize() { int result = MAX_IMAGE_SIDE_SIZE_IN_PIXELS; try { final String defined = System.getProperty(PROPERTY_MAX_EMBEDDED_IMAGE_SIDE_SIZE); if (defined != null) { LOGGER.info("Detected redefined max size for embedded image side : " + defined); //NOI18N result = Math.max(8, Integer.parseInt(defined.trim())); } } catch (NumberFormatException ex) { LOGGER.error("Error during image size decoding : ", ex); //NOI18N } return result; } /** * Load and encode image into Base64. * * @param in stream to read image * @param maxSize max size of image, if less or zero then don't rescale * @return null if it was impossible to load image for its format, loaded * prepared image * @throws IOException if any error during conversion or loading * @since 1.4.0 */ @Nullable public static String rescaleImageAndEncodeAsBase64(@Nonnull final InputStream in, final int maxSize) throws IOException { final Image image = ImageIO.read(in); String result = null; if (image != null) { result = rescaleImageAndEncodeAsBase64(image, maxSize); } return result; } /** * Load and encode image into Base64 from file. * * @param file image file * @param maxSize max size of image, if less or zero then don't rescale * @return image * @throws IOException if any error during conversion or loading * @since 1.4.0 */ @Nonnull public static String rescaleImageAndEncodeAsBase64(@Nonnull final File file, final int maxSize) throws IOException { final Image image = ImageIO.read(file); if (image == null) { throw new IllegalArgumentException("Can't load image file : " + file); //NOI18N } return rescaleImageAndEncodeAsBase64(image, maxSize); } /** * Get default render quality for host OS. * * @return the render quality for host OS, must not be null * @since 1.4.5 */ @Nonnull public static RenderQuality getDefaultRenderQialityForOs() { RenderQuality result = RenderQuality.DEFAULT; if (SystemUtils.IS_OS_MAC || SystemUtils.IS_OS_WINDOWS) { result = RenderQuality.QUALITY; } return result; } /** * Rescale image and encode into Base64. * * @param image image to rescale and encode * @param maxSize max size of image, if less or zero then don't rescale * @return scaled and encoded image * @throws IOException if it was impossible to encode image * @since 1.4.0 */ @Nonnull public static String rescaleImageAndEncodeAsBase64(@Nonnull Image image, final int maxSize) throws IOException { final int width = image.getWidth(null); final int height = image.getHeight(null); final int maxImageSideSize = maxSize > 0 ? maxSize : Math.max(width, height); final float imageScale = width > maxImageSideSize || height > maxImageSideSize ? (float) maxImageSideSize / (float) Math.max(width, height) : 1.0f; if (!(image instanceof RenderedImage) || Float.compare(imageScale, 1.0f) != 0) { final int swidth; final int sheight; if (Float.compare(imageScale, 1.0f) == 0) { swidth = width; sheight = height; } else { swidth = Math.round(imageScale * width); sheight = Math.round(imageScale * height); } final BufferedImage buffer = new BufferedImage(swidth, sheight, BufferedImage.TYPE_INT_ARGB); final Graphics2D gfx = buffer.createGraphics(); gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); gfx.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); gfx.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); gfx.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); gfx.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE); gfx.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); gfx.drawImage(image, AffineTransform.getScaleInstance(imageScale, imageScale), null); gfx.dispose(); image = buffer; } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { if (!ImageIO.write((RenderedImage) image, "png", bos)) { throw new IOException("Can't encode image as PNG"); } } finally { IOUtils.closeQuietly(bos); } return Utils.base64encode(bos.toByteArray()); } public static int calculateColorBrightness(@Nonnull final Color color) { return (int) Math.sqrt(color.getRed() * color.getRed() * .241d + color.getGreen() * color.getGreen() * .691d + color.getBlue() * color.getBlue() * .068d); } public static boolean isDarkTheme() { final Color panelBack = UIManager.getColor("Panel.background"); if (panelBack == null) { return false; } else { return calculateColorBrightness(panelBack) < 150; } } @Nonnull public static String convertCamelCasedToHumanForm(@Nonnull final String camelCasedString, final boolean capitalizeFirstChar) { final StringBuilder result = new StringBuilder(); boolean notFirst = false; for (final char c : camelCasedString.toCharArray()) { if (notFirst) { if (Character.isUpperCase(c)) { result.append(' '); result.append(Character.toLowerCase(c)); } else { result.append(c); } } else { notFirst = true; if (capitalizeFirstChar) { result.append(Character.toUpperCase(c)); } else { result.append(c); } } } return result.toString(); } @Nonnull @MustNotContainNull public static Topic[] getLeftToRightOrderedChildrens(@Nonnull final Topic topic) { final List<Topic> result = new ArrayList<>(); if (topic.getTopicLevel() == 0) { for (final Topic t : topic.getChildren()) { if (AbstractCollapsableElement.isLeftSidedTopic(t)) { result.add(t); } } for (final Topic t : topic.getChildren()) { if (!AbstractCollapsableElement.isLeftSidedTopic(t)) { result.add(t); } } } else { result.addAll(topic.getChildren()); } return result.toArray(new Topic[0]); } public static boolean safeObjectEquals(@Nullable final Object obj1, @Nullable final Object obj2) { if (obj1 == obj2) { return true; } if (obj1 == null || obj2 == null) { return false; } return obj1.equals(obj2); } public static void setAttribute(@Nonnull final String name, @Nullable final String value, @Nonnull @MustNotContainNull final Topic[] topics) { for (final Topic t : topics) { t.setAttribute(name, value); } } @Nullable public static Color html2color(@Nullable final String str, final boolean hasAlpha) { Color result = null; if (str != null && !str.isEmpty() && str.charAt(0) == '#') { try { String color = str.substring(1); if (color.length() > 6) { color = color.substring(color.length() - 6); } if (color.length() == 6) { result = new Color(Integer.parseInt(color, 16), hasAlpha); } else if (color.length() == 3) { final int r = Integer.parseInt(color.charAt(0) + "0", 16); final int g = Integer.parseInt(color.charAt(1) + "0", 16); final int b = Integer.parseInt(color.charAt(2) + "0", 16); result = new Color(r, g, b); } } catch (NumberFormatException ex) { LOGGER.warn(String.format("Can't convert %s to color", str)); } } return result; } @Nullable public static String color2html(@Nullable final Color color, final boolean hasAlpha) { String result = null; if (color != null) { final StringBuilder buffer = new StringBuilder(); buffer.append('#'); final int[] components; if (hasAlpha) { components = new int[]{color.getAlpha(), color.getRed(), color.getGreen(), color.getBlue()}; } else { components = new int[]{color.getRed(), color.getGreen(), color.getBlue()}; } for (final int c : components) { final String str = Integer.toHexString(c & 0xFF).toUpperCase(Locale.ENGLISH); if (str.length() < 2) { buffer.append('0'); } buffer.append(str); } result = buffer.toString(); } return result; } @Nonnull public static String getFirstLine(@Nonnull final String text) { return text.replace("\r", "").split("\\n")[0]; //NOI18N } @Nonnull public static String makeShortTextVersion(@Nonnull String text, final int maxLength) { if (text.length() > maxLength) { text = text.substring(0, maxLength) + "..."; //NOI18N } return text; } public static void safeSwingCall(@Nonnull final Runnable runnable) { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); } else { SwingUtilities.invokeLater(runnable); } } public static void safeSwingBlockingCall(@Nonnull final Runnable runnable) { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); } else { try { SwingUtilities.invokeAndWait(runnable); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } catch (InvocationTargetException ex) { throw new RuntimeException("Detected exception during SwingUtilities.invokeAndWait", ex); } } } @Nonnull @MustNotContainNull public static String[] breakToLines(@Nonnull final String text) { final int lineNum = numberOfLines(text); final String[] result = new String[lineNum]; final StringBuilder line = new StringBuilder(); int index = 0; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == '\n') { result[index++] = line.toString(); line.setLength(0); } else { line.append(text.charAt(i)); } } result[index] = line.toString(); return result; } public static int numberOfLines(@Nonnull final String text) { int result = 1; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == '\n') { result++; } } return result; } @ImplementationNote("Must be called from Swing UI thread") public static void foldUnfoldTree(@Nonnull final JTree tree, final boolean unfold) { final TreeModel model = tree.getModel(); if (model != null) { final Object root = model.getRoot(); if (root != null) { final TreePath thePath = new TreePath(root); setTreeState(tree, thePath, true, unfold); if (!unfold) { setTreeState(tree, thePath, false, true); } } } } private static void setTreeState(@Nonnull final JTree tree, @Nonnull final TreePath path, final boolean recursively, final boolean unfold) { final Object lastNode = path.getLastPathComponent(); for (int i = 0; i < tree.getModel().getChildCount(lastNode); i++) { final Object child = tree.getModel().getChild(lastNode, i); final TreePath pathToChild = path.pathByAddingChild(child); if (recursively) { setTreeState(tree, pathToChild, recursively, unfold); } } if (unfold) { tree.expandPath(path); } else { tree.collapsePath(path); } } public static @Nonnull String removeAllISOControlsButTabs(@Nonnull final String str) { final StringBuilder result = new StringBuilder(str.length()); for (final char c : str.toCharArray()) { if (c != '\t' && Character.isISOControl(c)) { continue; } result.append(c); } return result.toString(); } @Nullable public static Point2D findRectEdgeIntersection(@Nonnull final Rectangle2D rect, final double outboundX, final double outboundY) { final int detectedSide = rect.outcode(outboundX, outboundY); if ((detectedSide & (Rectangle2D.OUT_TOP | Rectangle2D.OUT_BOTTOM)) != 0) { final boolean top = (detectedSide & Rectangle2D.OUT_BOTTOM) == 0; final double dx = outboundX - rect.getCenterX(); if (dx == 0.0d) { return new Point2D.Double(rect.getCenterX(), top ? rect.getMinY() : rect.getMaxY()); } else { final double halfy = top ? rect.getHeight() / 2 : -rect.getHeight() / 2; final double coeff = (outboundY - rect.getCenterY()) / dx; final double calculatedX = rect.getCenterX() - (halfy / coeff); if (calculatedX >= rect.getMinX() && calculatedX <= rect.getMaxX()) { return new Point2D.Double(calculatedX, top ? rect.getMinY() : rect.getMaxY()); } } } if ((detectedSide & (Rectangle2D.OUT_LEFT | Rectangle2D.OUT_RIGHT)) != 0) { final boolean left = (detectedSide & Rectangle2D.OUT_RIGHT) == 0; final double dy = outboundY - rect.getCenterY(); if (dy == 0.0d) { return new Point2D.Double(left ? rect.getMinX() : rect.getMaxX(), rect.getCenterY()); } else { final double halfx = left ? rect.getWidth() / 2 : -rect.getWidth() / 2; final double coeff = (outboundX - rect.getCenterX()) / dy; final double calculatedY = rect.getCenterY() - (halfx / coeff); if (calculatedY >= rect.getMinY() && calculatedY <= rect.getMaxY()) { return new Point2D.Double(left ? rect.getMinX() : rect.getMaxX(), calculatedY); } } } return null; } public static boolean isPlantUmlFileExtension(@Nonnull final String lowerCasedTrimmedExtension) { boolean result = false; if (lowerCasedTrimmedExtension.length() > 1 && lowerCasedTrimmedExtension.charAt(0) == 'p') { result = "pu".equals(lowerCasedTrimmedExtension) || "puml".equals(lowerCasedTrimmedExtension) || "plantuml".equals(lowerCasedTrimmedExtension); } return result; } @Nullable public static Image scaleImage(@Nonnull final Image src, final double baseScaleX, final double baseScaleY, final double scale) { final int imgw = src.getWidth(null); final int imgh = src.getHeight(null); final int scaledW = (int) Math.round(imgw * baseScaleX * scale); final int scaledH = (int) Math.round(imgh * baseScaleY * scale); BufferedImage result = null; if (scaledH > 0 && scaledW > 0) { try { result = new BufferedImage(scaledW, scaledH, BufferedImage.TYPE_INT_ARGB); final Graphics2D g = (Graphics2D) result.getGraphics(); RenderQuality.QUALITY.prepare(g); g.drawImage(src, 0, 0, scaledW, scaledH, null); g.dispose(); } catch (OutOfMemoryError e) { LOGGER.error("OutOfmemoryError in scaleImage (" + baseScaleX + ',' + baseScaleY + ',' + scale + ')', e); throw e; } } return result; } @Nonnull public static Image renderWithTransparency(final float opacity, @Nonnull final AbstractElement element, @Nonnull final MindMapPanelConfig config, @Nonnull final RenderQuality quality) { final AbstractElement cloned = element.makeCopy(); final Rectangle2D bounds = cloned.getBounds(); final float increase = config.safeScaleFloatValue(config.getElementBorderWidth() + config.getShadowOffset(), 0.0f); final int imageWidth = (int) Math.round(bounds.getWidth() + increase); final int imageHeight = (int) Math.round(bounds.getHeight() + increase); bounds.setRect(0.0d, 0.0d, bounds.getWidth(), bounds.getHeight()); final BufferedImage result = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB); for (int y = 0; y < imageHeight; y++) { for (int x = 0; x < imageWidth; x++) { result.setRGB(x, y, 0); } } final Graphics2D g = result.createGraphics(); final MMGraphics gfx = new MMGraphics2DWrapper(g); try { quality.prepare(g); cloned.doPaint(gfx, config, false); } finally { gfx.dispose(); } int alpha; if (opacity <= 0.0f) { alpha = 0x00; } else if (opacity >= 1.0f) { alpha = 0xFF; } else { alpha = Math.round(0xFF * opacity); } alpha <<= 24; for (int y = 0; y < imageHeight; y++) { for (int x = 0; x < imageWidth; x++) { final int curAlpha = result.getRGB(x, y) >>> 24; if (curAlpha == 0xFF) { result.setRGB(x, y, (result.getRGB(x, y) & 0xFFFFFF) | alpha); } else if (curAlpha != 0x00) { final int calculated = Math.round(curAlpha * opacity) << 24; result.setRGB(x, y, (result.getRGB(x, y) & 0xFFFFFF) | calculated); } } } return result; } @Nonnull public static Color makeContrastColor(@Nonnull final Color color) { return new Color(color.getRed() ^ 0xFF, color.getGreen() ^ 0xFF, color.getBlue() ^ 0xFF); } @Nonnull @MustNotContainNull private static List<JMenuItem> findPopupMenuItems( @Nonnull final PluginContext context, @Nonnull final PopUpSection section, final boolean fullScreenModeActive, @Nonnull @MayContainNull final List<JMenuItem> list, @Nullable final Topic topicUnderMouse, @Nonnull @MustNotContainNull final List<PopUpMenuItemPlugin> pluginMenuItems ) { list.clear(); for (final PopUpMenuItemPlugin p : pluginMenuItems) { if (fullScreenModeActive && !p.isCompatibleWithFullScreenMode()) { continue; } if (p.getSection() == section) { if (!(p.needsTopicUnderMouse() || p.needsSelectedTopics()) || (p.needsTopicUnderMouse() && topicUnderMouse != null) || (p.needsSelectedTopics() && context.getSelectedTopics().length > 0)) { final JMenuItem item = p.makeMenuItem(context, topicUnderMouse); if (item != null) { item.setEnabled(p.isEnabled(context, topicUnderMouse)); list.add(item); } } } } return list; } public static void assertSwingDispatchThread() { if (!SwingUtilities.isEventDispatchThread()) { throw new Error("Must be called in Swing dispatch thread"); } } @Nonnull @MustNotContainNull private static List<JMenuItem> putAllItemsAsSection(@Nonnull final JPopupMenu menu, @Nullable final JMenu subMenu, @Nonnull @MustNotContainNull final List<JMenuItem> items) { if (!items.isEmpty()) { if (menu.getComponentCount() > 0) { menu.add(UI_COMPO_FACTORY.makeMenuSeparator()); } for (final JMenuItem i : items) { if (subMenu == null) { menu.add(i); } else { subMenu.add(i); } } if (subMenu != null) { menu.add(subMenu); } } return items; } public static boolean isDataFlavorAvailable(@Nonnull final Clipboard clipboard, @Nonnull final DataFlavor flavor) { boolean result = false; try { result = clipboard.isDataFlavorAvailable(flavor); } catch (final IllegalStateException ex) { LOGGER.warn("Can't get access to clipboard : " + ex.getMessage()); } return result; } @Nonnull public static JPopupMenu makePopUp( @Nonnull final PluginContext context, final boolean fullScreenModeActive, @Nullable final Topic topicUnderMouse ) { final JPopupMenu result = UI_COMPO_FACTORY.makePopupMenu(); final List<PopUpMenuItemPlugin> pluginMenuItems = MindMapPluginRegistry.getInstance().findFor(PopUpMenuItemPlugin.class); final List<JMenuItem> tmpList = new ArrayList<>(); final boolean isModelNotEmpty = context.getPanel().getModel().getRoot() != null; putAllItemsAsSection(result, null, findPopupMenuItems(context, PopUpSection.MAIN, fullScreenModeActive, tmpList, topicUnderMouse, pluginMenuItems)); putAllItemsAsSection(result, null, findPopupMenuItems(context, PopUpSection.MANIPULATORS, fullScreenModeActive, tmpList, topicUnderMouse, pluginMenuItems)); putAllItemsAsSection(result, null, findPopupMenuItems(context, PopUpSection.EXTRAS, fullScreenModeActive, tmpList, topicUnderMouse, pluginMenuItems)); final JMenu exportMenu = UI_COMPO_FACTORY.makeMenu(BUNDLE.getString("MMDExporters.SubmenuName")); exportMenu.setIcon(ICON_SERVICE.getIconForId(IconID.POPUP_EXPORT)); final JMenu importMenu = UI_COMPO_FACTORY.makeMenu(BUNDLE.getString("MMDImporters.SubmenuName")); importMenu.setIcon(ICON_SERVICE.getIconForId(IconID.POPUP_IMPORT)); putAllItemsAsSection(result, importMenu, findPopupMenuItems(context, PopUpSection.IMPORT, fullScreenModeActive, tmpList, topicUnderMouse, pluginMenuItems)); if (isModelNotEmpty) { putAllItemsAsSection(result, exportMenu, findPopupMenuItems(context, PopUpSection.EXPORT, fullScreenModeActive, tmpList, topicUnderMouse, pluginMenuItems)); } putAllItemsAsSection(result, null, findPopupMenuItems(context, PopUpSection.TOOLS, fullScreenModeActive, tmpList, topicUnderMouse, pluginMenuItems)); putAllItemsAsSection(result, null, findPopupMenuItems(context, PopUpSection.MISC, fullScreenModeActive, tmpList, topicUnderMouse, pluginMenuItems)); return result; } public static boolean isKeyStrokeEvent(@Nullable final KeyStroke keyStroke, final int keyEventType, @Nullable final KeyEvent event) { boolean result = false; if (keyStroke != null && event != null) { if (keyEventType == keyStroke.getKeyEventType()) { result = ((keyStroke.getModifiers() & event.getModifiers()) == keyStroke.getModifiers()) && (keyStroke.getKeyCode() == event.getKeyCode()); } } return result; } @Nonnull @MustNotContainNull private static List<JButton> findAllOptionPaneButtons(@Nonnull final JComponent component) { final List<JButton> result = new ArrayList<>(); Arrays.stream(component.getComponents()) .filter(x -> x instanceof JComponent) .map(x -> (JComponent) x) .forEach(x -> { if (x instanceof JButton) { if ("OptionPane.button".equals(x.getName())) { result.add((JButton) x); } } else { result.addAll(findAllOptionPaneButtons(x)); } }); return result; } private static void replaceActionListenerForButton(@Nonnull final JButton button, @Nonnull final ActionListener listener) { final ActionListener[] currentListeners = button.getActionListeners(); for (final ActionListener l : currentListeners) { button.removeActionListener(l); } button.addActionListener(listener); } @Nonnull @SafeVarargs @ReturnsOriginal public static JComponent catchEscInParentDialog( @Nonnull final JComponent component, @Nonnull final DialogProvider dialogProvider, @Nullable final Predicate<JDialog> doClose, @Nonnull @MustNotContainNull final Consumer<JDialog>... beforeClose) { component.addHierarchyListener(new HierarchyListener() { final Consumer<JDialog> processor = dialog -> { final boolean close; if (doClose == null) { close = true; } else { if (doClose.test(dialog)) { close = dialogProvider .msgConfirmOkCancel(dialog, BUNDLE.getString("Utils.confirmActionTitle"), BUNDLE.getString("Utils.closeForContentChange")); } else { close = true; } } if (close) { try { for (final Consumer<JDialog> c : beforeClose) { try { c.accept(dialog); } catch (Exception ex) { LOGGER.error("Error during before close call", ex); } } } finally { dialog.dispose(); } } }; private final KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false); @Override public void hierarchyChanged(@Nonnull final HierarchyEvent e) { final Window window = SwingUtilities.getWindowAncestor(component); if (window instanceof JDialog && (e.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) != 0) { final JDialog dialog = (JDialog) window; final List<JButton> dialogButtons = findAllOptionPaneButtons(dialog.getRootPane()); dialogButtons.stream() .filter(x -> "cancel".equalsIgnoreCase(x.getText())) .forEach(x -> replaceActionListenerForButton(x, be -> { processor.accept(dialog); })); dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); final WindowListener windowListener = new WindowAdapter() { @Override public void windowClosing(@Nonnull final WindowEvent e) { processor.accept(dialog); } }; final WindowListener[] windowListeners = dialog.getWindowListeners(); for (final WindowListener w : windowListeners) { dialog.removeWindowListener(w); } dialog.addWindowListener(windowListener); final InputMap inputMap = dialog.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(escapeKeyStroke, "PRESSING_ESCAPE"); final ActionMap actionMap = dialog.getRootPane().getActionMap(); actionMap.put("PRESSING_ESCAPE", new AbstractAction() { @Override public void actionPerformed(@Nonnull final ActionEvent e) { processor.accept(dialog); } }); } } }); return component; } @Nonnull public static byte[] base64decode(@Nonnull final String text) throws IOException { return Base64.decode(text); } @Nonnull public static String strip(@Nonnull final String str, final boolean leading) { if (str.trim().isEmpty()) { return ""; } final Matcher matcher = STRIP_PATTERN.matcher(str); if (!matcher.find()) { throw new Error("Unexpected error in strip(String): " + str); } return leading ? matcher.group(2) + matcher.group(3) : matcher.group(1) + matcher.group(2); } @Nonnull public static String base64encode(@Nonnull final byte[] data) { return Base64.encodeBytes(data); } }
#86 refactoring to make transition of window listener events
mind-map/mind-map-swing-panel/src/main/java/com/igormaznitsa/mindmap/swing/panel/utils/Utils.java
#86 refactoring to make transition of window listener events
<ide><path>ind-map/mind-map-swing-panel/src/main/java/com/igormaznitsa/mindmap/swing/panel/utils/Utils.java <ide> }; <ide> private final KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false); <ide> <add> private final List<WindowListener> foundWindowListeners = new ArrayList<>(); <add> <ide> @Override <ide> public void hierarchyChanged(@Nonnull final HierarchyEvent e) { <ide> final Window window = SwingUtilities.getWindowAncestor(component); <ide> <ide> dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); <ide> <del> final WindowListener windowListener = new WindowAdapter() { <add> final WindowListener windowListener = new WindowListener() { <ide> @Override <ide> public void windowClosing(@Nonnull final WindowEvent e) { <ide> processor.accept(dialog); <ide> } <add> <add> @Override <add> public void windowOpened(@Nonnull final WindowEvent e) { <add> foundWindowListeners.forEach(x -> x.windowOpened(e)); <add> } <add> <add> @Override <add> public void windowClosed(@Nonnull final WindowEvent e) { <add> foundWindowListeners.forEach(x -> x.windowClosed(e)); <add> } <add> <add> @Override <add> public void windowIconified(@Nonnull final WindowEvent e) { <add> foundWindowListeners.forEach(x -> x.windowIconified(e)); <add> } <add> <add> @Override <add> public void windowDeiconified(@Nonnull final WindowEvent e) { <add> foundWindowListeners.forEach(x -> x.windowDeiconified(e)); <add> } <add> <add> @Override <add> public void windowActivated(@Nonnull final WindowEvent e) { <add> foundWindowListeners.forEach(x -> x.windowActivated(e)); <add> } <add> <add> @Override <add> public void windowDeactivated(@Nonnull final WindowEvent e) { <add> foundWindowListeners.forEach(x -> x.windowDeactivated(e)); <add> } <ide> }; <ide> <del> final WindowListener[] windowListeners = dialog.getWindowListeners(); <del> for (final WindowListener w : windowListeners) { <del> dialog.removeWindowListener(w); <add> if (this.foundWindowListeners.isEmpty()) { <add> final WindowListener[] windowListeners = dialog.getWindowListeners(); <add> for (final WindowListener w : windowListeners) { <add> dialog.removeWindowListener(w); <add> this.foundWindowListeners.add(w); <add> } <add> dialog.addWindowListener(windowListener); <ide> } <del> dialog.addWindowListener(windowListener); <ide> <ide> final InputMap inputMap = dialog.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); <ide> inputMap.put(escapeKeyStroke, "PRESSING_ESCAPE");
Java
bsd-3-clause
c0681e5008babcc5578892c110da83dbe50067d8
0
eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j
/******************************************************************************* * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. *******************************************************************************/ package org.eclipse.rdf4j.common.io; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.ClosedByInterruptException; import java.nio.channels.ClosedChannelException; import java.nio.channels.FileChannel; import java.nio.channels.WritableByteChannel; /** * File wrapper that protects against concurrent file closing events due to e.g. {@link Thread#interrupt() * thread interrupts}. In case the file channel that is used by this class is closed due to such an event, it * will try to reopen the channel. The thread that causes the {@link ClosedByInterruptException} is not * protected, assuming the interrupt is intended to end the thread's operation. * * @author Arjohn Kampman */ public final class NioFile implements Closeable { private final File file; private final String mode; private volatile RandomAccessFile raf; private volatile FileChannel fc; private volatile boolean explictlyClosed; /** * Constructor * Opens a file in read/write mode, creating a new one if the file doesn't exist. * * @param file * @throws IOException */ public NioFile(File file) throws IOException { this(file, "rw"); } /** * Constructor * Opens a file in a specific mode, creating a new one if the file doesn't exist. * * @param file file * @param mode file mode * @throws IOException */ public NioFile(File file, String mode) throws IOException { this.file = file; this.mode = mode; if (!file.exists()) { boolean created = file.createNewFile(); if (!created) { throw new IOException("Failed to create file: " + file); } } explictlyClosed = false; open(); } /** * Open a file channel for random access. * * @throws IOException */ private void open() throws IOException { raf = new RandomAccessFile(file, mode); fc = raf.getChannel(); } /** * Reopen a channel closed by an exception, unless it was closed explicitly. * * @param e exception that closed the channel * @throws IOException */ private synchronized void reopen(ClosedChannelException e) throws IOException { if (explictlyClosed) { throw e; } if (fc.isOpen()) { // file channel has been already reopened by another thread return; } open(); } @Override public synchronized void close() throws IOException { explictlyClosed = true; raf.close(); } /** * Check if a file was closed explicitly. * * @return true if it was closed explicitly */ public boolean isClosed() { return explictlyClosed; } public File getFile() { return file; } /** * Close any open channels and then deletes the file. * * @return <tt>true</tt> if the file has been deleted successfully, <tt>false</tt> otherwise. * @throws IOException * If there was a problem closing the open file channel. */ public boolean delete() throws IOException { // make sure to close file handles prior to deletion close(); return file.delete(); } /** * Performs a protected {@link FileChannel#force(boolean)} call. * * @param metaData * @throws IOException */ public void force(boolean metaData) throws IOException { while (true) { try { fc.force(metaData); return; } catch (ClosedByInterruptException e) { throw e; } catch (ClosedChannelException e) { reopen(e); } } } /** * Performs a protected {@link FileChannel#truncate(long)} call. * * @param size * @throws IOException */ public void truncate(long size) throws IOException { while (true) { try { fc.truncate(size); return; } catch (ClosedByInterruptException e) { throw e; } catch (ClosedChannelException e) { reopen(e); } } } /** * Performs a protected {@link FileChannel#size()} call. * * @return size of the file * @throws IOException */ public long size() throws IOException { while (true) { try { return fc.size(); } catch (ClosedByInterruptException e) { throw e; } catch (ClosedChannelException e) { reopen(e); } } } /** * Performs a protected {@link FileChannel#transferTo(long, long, WritableByteChannel)} call. * * @param position position within the file * @param count number of bytes to transfer * @param target target channel * @return number of bytes transferred * @throws IOException */ public long transferTo(long position, long count, WritableByteChannel target) throws IOException { while (true) { try { return fc.transferTo(position, count, target); } catch (ClosedByInterruptException e) { throw e; } catch (ClosedChannelException e) { reopen(e); } } } /** * Performs a protected {@link FileChannel#write(ByteBuffer, long)} call. * * @param buf buffer * @param offset non-negative offset * @return number of bytes written * @throws IOException */ public int write(ByteBuffer buf, long offset) throws IOException { while (true) { try { return fc.write(buf, offset); } catch (ClosedByInterruptException e) { throw e; } catch (ClosedChannelException e) { reopen(e); } } } /** * Performs a protected {@link FileChannel#read(ByteBuffer, long)} call. * * @param buf buffer to read * @param offset non-negative offset * @return number of bytes read * @throws IOException */ public int read(ByteBuffer buf, long offset) throws IOException { while (true) { try { return fc.read(buf, offset); } catch (ClosedByInterruptException e) { throw e; } catch (ClosedChannelException e) { reopen(e); } } } /** * Write byte array to channel starting at offset. * * @param value byte array to write * @param offset non-negative offset * @throws IOException */ public void writeBytes(byte[] value, long offset) throws IOException { write(ByteBuffer.wrap(value), offset); } /** * Read a byte array of a specifi length from channel starting at offset. * * @param offset * @param length * @return * @throws IOException */ public byte[] readBytes(long offset, int length) throws IOException { ByteBuffer buf = ByteBuffer.allocate(length); read(buf, offset); return buf.array(); } /** * Write single byte to channel starting at offset. * * @param value value to write * @param offset non-negative offset * @throws IOException */ public void writeByte(byte value, long offset) throws IOException { writeBytes(new byte[] { value }, offset); } /** * Read single byte from channel starting at offset. * * @param offset non-negative offset * @return byte * @throws IOException */ public byte readByte(long offset) throws IOException { return readBytes(offset, 1)[0]; } /** * Write long value to channel starting at offset. * * @param value value to write * @param offset non-negative offset * @throws IOException */ public void writeLong(long value, long offset) throws IOException { ByteBuffer buf = ByteBuffer.allocate(8); buf.putLong(0, value); write(buf, offset); } /** * Read long value from channel starting at offset. * * @param offset non-negative offset * @return long * @throws IOException */ public long readLong(long offset) throws IOException { ByteBuffer buf = ByteBuffer.allocate(8); read(buf, offset); return buf.getLong(0); } /** * Write integer value to channel starting at offset. * * @param value value to write * @param offset non-negative offset * @throws IOException */ public void writeInt(int value, long offset) throws IOException { ByteBuffer buf = ByteBuffer.allocate(4); buf.putInt(0, value); write(buf, offset); } /** * Read integer value from channel starting at offset. * * @param offset non-negative offset * @return integer * @throws IOException */ public int readInt(long offset) throws IOException { ByteBuffer buf = ByteBuffer.allocate(4); read(buf, offset); return buf.getInt(0); } }
util/src/main/java/org/eclipse/rdf4j/common/io/NioFile.java
/******************************************************************************* * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. *******************************************************************************/ package org.eclipse.rdf4j.common.io; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.ClosedByInterruptException; import java.nio.channels.ClosedChannelException; import java.nio.channels.FileChannel; import java.nio.channels.WritableByteChannel; /** * File wrapper that protects against concurrent file closing events due to e.g. {@link Thread#interrupt() * thread interrupts}. In case the file channel that is used by this class is closed due to such an event, it * will try to reopen the channel. The thread that causes the {@link ClosedByInterruptException} is not * protected, assuming the interrupt is intended to end the thread's operation. * * @author Arjohn Kampman */ public final class NioFile implements Closeable { private final File file; private final String mode; private volatile RandomAccessFile raf; private volatile FileChannel fc; private volatile boolean explictlyClosed; /** * Constructor * Opens a file in read/write mode, creating a new one if the file doesn't exist. * * @param file * @throws IOException */ public NioFile(File file) throws IOException { this(file, "rw"); } /** * Constructor * Opens a file in a specific mode, creating a new one if the file doesn't exist. * * @param file file * @param mode file mode * @throws IOException */ public NioFile(File file, String mode) throws IOException { this.file = file; this.mode = mode; if (!file.exists()) { boolean created = file.createNewFile(); if (!created) { throw new IOException("Failed to create file: " + file); } } explictlyClosed = false; open(); } /** * Open a file channel for random access. * * @throws IOException */ private void open() throws IOException { raf = new RandomAccessFile(file, mode); fc = raf.getChannel(); } /** * Reopen a channel closed by an exception, unless it was closed explicitly. * * @param e exception that closed the channel * @throws IOException */ private synchronized void reopen(ClosedChannelException e) throws IOException { if (explictlyClosed) { throw e; } if (fc.isOpen()) { // file channel has been already reopened by another thread return; } open(); } @Override public synchronized void close() throws IOException { explictlyClosed = true; raf.close(); } /** * Check if a file was closed explicitly. * * @return true if it was closed explicitly */ public boolean isClosed() { return explictlyClosed; } public File getFile() { return file; } /** * Close any open channels and then deletes the file. * * @return <tt>true</tt> if the file has been deleted successfully, <tt>false</tt> otherwise. * @throws IOException * If there was a problem closing the open file channel. */ public boolean delete() throws IOException { try { return file.delete(); } finally { close(); } } /** * Performs a protected {@link FileChannel#force(boolean)} call. * * @param metaData * @throws IOException */ public void force(boolean metaData) throws IOException { while (true) { try { fc.force(metaData); return; } catch (ClosedByInterruptException e) { throw e; } catch (ClosedChannelException e) { reopen(e); } } } /** * Performs a protected {@link FileChannel#truncate(long)} call. * * @param size * @throws IOException */ public void truncate(long size) throws IOException { while (true) { try { fc.truncate(size); return; } catch (ClosedByInterruptException e) { throw e; } catch (ClosedChannelException e) { reopen(e); } } } /** * Performs a protected {@link FileChannel#size()} call. * * @return size of the file * @throws IOException */ public long size() throws IOException { while (true) { try { return fc.size(); } catch (ClosedByInterruptException e) { throw e; } catch (ClosedChannelException e) { reopen(e); } } } /** * Performs a protected {@link FileChannel#transferTo(long, long, WritableByteChannel)} call. * * @param position position within the file * @param count number of bytes to transfer * @param target target channel * @return number of bytes transferred * @throws IOException */ public long transferTo(long position, long count, WritableByteChannel target) throws IOException { while (true) { try { return fc.transferTo(position, count, target); } catch (ClosedByInterruptException e) { throw e; } catch (ClosedChannelException e) { reopen(e); } } } /** * Performs a protected {@link FileChannel#write(ByteBuffer, long)} call. * * @param buf buffer * @param offset non-negative offset * @return number of bytes written * @throws IOException */ public int write(ByteBuffer buf, long offset) throws IOException { while (true) { try { return fc.write(buf, offset); } catch (ClosedByInterruptException e) { throw e; } catch (ClosedChannelException e) { reopen(e); } } } /** * Performs a protected {@link FileChannel#read(ByteBuffer, long)} call. * * @param buf buffer to read * @param offset non-negative offset * @return number of bytes read * @throws IOException */ public int read(ByteBuffer buf, long offset) throws IOException { while (true) { try { return fc.read(buf, offset); } catch (ClosedByInterruptException e) { throw e; } catch (ClosedChannelException e) { reopen(e); } } } /** * Write byte array to channel starting at offset. * * @param value byte array to write * @param offset non-negative offset * @throws IOException */ public void writeBytes(byte[] value, long offset) throws IOException { write(ByteBuffer.wrap(value), offset); } /** * Read a byte array of a specifi length from channel starting at offset. * * @param offset * @param length * @return * @throws IOException */ public byte[] readBytes(long offset, int length) throws IOException { ByteBuffer buf = ByteBuffer.allocate(length); read(buf, offset); return buf.array(); } /** * Write single byte to channel starting at offset. * * @param value value to write * @param offset non-negative offset * @throws IOException */ public void writeByte(byte value, long offset) throws IOException { writeBytes(new byte[] { value }, offset); } /** * Read single byte from channel starting at offset. * * @param offset non-negative offset * @return byte * @throws IOException */ public byte readByte(long offset) throws IOException { return readBytes(offset, 1)[0]; } /** * Write long value to channel starting at offset. * * @param value value to write * @param offset non-negative offset * @throws IOException */ public void writeLong(long value, long offset) throws IOException { ByteBuffer buf = ByteBuffer.allocate(8); buf.putLong(0, value); write(buf, offset); } /** * Read long value from channel starting at offset. * * @param offset non-negative offset * @return long * @throws IOException */ public long readLong(long offset) throws IOException { ByteBuffer buf = ByteBuffer.allocate(8); read(buf, offset); return buf.getLong(0); } /** * Write integer value to channel starting at offset. * * @param value value to write * @param offset non-negative offset * @throws IOException */ public void writeInt(int value, long offset) throws IOException { ByteBuffer buf = ByteBuffer.allocate(4); buf.putInt(0, value); write(buf, offset); } /** * Read integer value from channel starting at offset. * * @param offset non-negative offset * @return integer * @throws IOException */ public int readInt(long offset) throws IOException { ByteBuffer buf = ByteBuffer.allocate(4); read(buf, offset); return buf.getInt(0); } }
#1294: Fix resource leak in txncache file deletion The temporary txncache.dat file cannot be deleted on Windows as the file is still locked while attempting the deletion. Closing the resource handle properly makes sure that deletion works. Signed-off-by: Andreas Schwarte <[email protected]>
util/src/main/java/org/eclipse/rdf4j/common/io/NioFile.java
#1294: Fix resource leak in txncache file deletion
<ide><path>til/src/main/java/org/eclipse/rdf4j/common/io/NioFile.java <ide> public boolean delete() <ide> throws IOException <ide> { <del> try { <del> return file.delete(); <del> } <del> finally { <del> close(); <del> } <add> // make sure to close file handles prior to deletion <add> close(); <add> return file.delete(); <ide> } <ide> <ide> /**
Java
apache-2.0
56fcf3ea4e0de46eff26f390e91043e73b66afa7
0
molindo/molindo-elasticsync
package at.molindo.elasticsync.jest.internal; import io.searchbox.client.JestClient; import io.searchbox.client.JestResult; import io.searchbox.core.Bulk; import io.searchbox.core.Delete; import io.searchbox.core.Doc; import io.searchbox.core.Index; import io.searchbox.core.MultiGet; import io.searchbox.core.Search; import io.searchbox.core.Search.Builder; import io.searchbox.core.SearchScroll; import io.searchbox.params.Parameters; import io.searchbox.params.SearchType; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.slf4j.Logger; import at.molindo.elasticsync.api.Document; import at.molindo.elasticsync.api.ElasticsearchIndex; import at.molindo.elasticsync.api.IdAndVersionFactory; import at.molindo.elasticsync.api.LogUtils; import at.molindo.elasticsync.jest.internal.version.IVersionHelper; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; public class ElasticsearchJestIndex implements ElasticsearchIndex { private static final Logger LOG = LogUtils.loggerForThisClass(); private static final List<Doc> EMPTY_DOC_LIST = Collections.emptyList(); static final int BATCH_SIZE = 10_000; // only ids and versions, per shard static final int SCROLL_TIME_IN_MINUTES = 10; private long numItems = 0; private final JestClient client; private final String indexName; private final String query; private final IdAndVersionFactory idAndVersionFactory; private final IVersionHelper versionHelper; public ElasticsearchJestIndex(JestClient client, String indexName, String query, IdAndVersionFactory idAndVersionFactory, IVersionHelper versionHelper) { this.client = client; this.indexName = indexName; this.query = query; this.idAndVersionFactory = idAndVersionFactory; this.versionHelper = versionHelper; } @Override public IdAndVersionFactory getIdAndVersionFactory() { return idAndVersionFactory; } @Override public void downloadTo(String type, OutputStream outputStream) { long begin = System.currentTimeMillis(); doDownloadTo(type, outputStream); LogUtils.infoTimeTaken(LOG, begin, numItems, "Scan & Download completed"); numItems = 0; } private void doDownloadTo(String type, OutputStream outputStream) { try { ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); consumeBatches(objectOutputStream, startScroll(type)); objectOutputStream.close(); } catch (Exception e) { throw new RuntimeException(e); } } void consumeBatches(ObjectOutputStream objectOutputStream, String initialScrollId) throws Exception { String scrollId = initialScrollId; JestResult batchSearchResponse = null; do { SearchScroll.Builder builder = new SearchScroll.Builder(scrollId, SCROLL_TIME_IN_MINUTES + "m"); batchSearchResponse = client.execute(builder.build()); scrollId = batchSearchResponse.getJsonObject().get("_scroll_id").getAsString(); } while (writeSearchResponseToOutputStream(objectOutputStream, batchSearchResponse)); } boolean writeSearchResponseToOutputStream(ObjectOutputStream objectOutputStream, JestResult searchResponse) throws IOException { // "hits":{"total":62319,"max_score":0.0,"hits":[{"_index":"stats","_type":"stats","_id":"MostPopularArtists","_version":1392888398281,"_score":0.0,"_source":{"_id":"MostPopularArtists","_ttl":5 JsonObject obj = searchResponse.getJsonObject().getAsJsonObject("hits"); long total = obj.get("total").getAsLong(); JsonArray hits = obj.getAsJsonArray("hits"); LOG.debug("scroll returned {} of {} total hits", hits.size(), total); for (JsonElement e : hits) { JsonObject hit = e.getAsJsonObject(); String id = hit.get("_id").getAsString(); JsonElement v = hit.get("_version"); Long version; if (v == null) { LOG.debug("missing version for id {}", id); version = 1L; } else { version = v.getAsLong(); } idAndVersionFactory.create(id, version).writeToStream(objectOutputStream); numItems++; } return hits.size() > 0; } String startScroll(String type) { Builder builder = new Search.Builder(versionHelper.createQuery(query)); builder.addIndex(indexName); builder.addType(type); builder.setParameter(Parameters.SIZE, BATCH_SIZE); builder.setParameter(Parameters.EXPLAIN, false); // searchRequestBuilder.setNoFields(); builder.setParameter(Parameters.VERSION, true); builder.setSearchType(SearchType.SCAN); builder.setParameter(Parameters.SCROLL, SCROLL_TIME_IN_MINUTES + "m"); try { JestResult result = client.execute(builder.build()); if (result.isSucceeded()) { return result.getJsonObject().get("_scroll_id").getAsString(); } else { throw new RuntimeException("failed to start scroll operation: " + result.getJsonObject()); } } catch (Exception e) { throw new RuntimeException("failed to start scroll operation", e); } } @Override public void load(List<Document> documents, final Runnable listener) { final Map<String, Map<String, Document>> map = new HashMap<>(); MultiGet.Builder.ByDoc builder = new MultiGet.Builder.ByDoc(EMPTY_DOC_LIST); for (Document doc : documents) { builder.addDoc(new Doc(indexName, doc.getType(), doc.getId())); Map<String, Document> typeMap = map.get(doc.getType()); if (typeMap == null) { map.put(doc.getType(), typeMap = new HashMap<>()); } typeMap.put(doc.getId(), doc); } try { JestResult result = client.execute(builder.build()); JsonArray docs = result.getJsonObject().getAsJsonArray("docs"); for (JsonElement e : docs) { JsonObject item = e.getAsJsonObject(); String type = item.get("_type").getAsString(); String id = item.get("_id").getAsString(); Map<String, Document> typeMap = map.get(type); if (typeMap == null) { LOG.warn("unexpected type returned: " + type); continue; } Document doc = typeMap.get(id); if (doc == null) { LOG.warn("unexpected id returned: " + type + "/" + id); continue; } if (item.get("exists").getAsBoolean()) { long version = item.get("_version").getAsLong(); String source = item.get("_source").toString(); doc.setVersion(version).setSource(source); } else { doc.setDeleted(); } // } } if (listener != null) { listener.run(); } } catch (Exception e) { LOG.error("loading documents failed", e); if (listener != null) { listener.run(); } } } @Override public void index(final List<Document> documents, final Runnable listener) { Bulk.Builder builder = new Bulk.Builder(); for (Document doc : documents) { if (doc.isDeleted()) { builder.addAction(new Delete.Builder(indexName, doc.getType(), doc.getId()) .setParameter(Parameters.VERSION_TYPE, "external") .setParameter(Parameters.VERSION, doc.getVersion() + 1).build()); } else { builder.addAction(new Index.Builder(doc.getSource()).index(indexName).type(doc.getType()) .id(doc.getId()).setParameter(Parameters.VERSION_TYPE, "external") .setParameter(Parameters.VERSION, doc.getVersion()).build()); } } try { JestResult result = client.execute(builder.build()); JsonArray items = result.getJsonObject().getAsJsonArray("items"); Iterator<Document> docIter = documents.iterator(); for (JsonElement e : items) { JsonObject item = e.getAsJsonObject(); if (item.has("error")) { Document document = docIter.next(); LOG.warn("document {} failed {} ({})", document.isDeleted() ? "delete" : "index", document, item .get("error").getAsString()); } } if (listener != null) { listener.run(); } } catch (Exception e) { LOG.error("indexing documents failed", e); if (listener != null) { listener.run(); } } } @Override public void close() { if (client != null) { client.shutdownClient(); } } }
src/main/java/at/molindo/elasticsync/jest/internal/ElasticsearchJestIndex.java
package at.molindo.elasticsync.jest.internal; import io.searchbox.client.JestClient; import io.searchbox.client.JestResult; import io.searchbox.core.Bulk; import io.searchbox.core.Delete; import io.searchbox.core.Doc; import io.searchbox.core.Index; import io.searchbox.core.MultiGet; import io.searchbox.core.Search; import io.searchbox.core.Search.Builder; import io.searchbox.core.SearchScroll; import io.searchbox.params.Parameters; import io.searchbox.params.SearchType; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.slf4j.Logger; import at.molindo.elasticsync.api.Document; import at.molindo.elasticsync.api.ElasticsearchIndex; import at.molindo.elasticsync.api.IdAndVersionFactory; import at.molindo.elasticsync.api.LogUtils; import at.molindo.elasticsync.jest.internal.version.IVersionHelper; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; public class ElasticsearchJestIndex implements ElasticsearchIndex { private static final Logger LOG = LogUtils.loggerForThisClass(); private static final List<Doc> EMPTY_DOC_LIST = Collections.emptyList(); static final int BATCH_SIZE = 100000; // only ids and versions static final int SCROLL_TIME_IN_MINUTES = 10; private long numItems = 0; private final JestClient client; private final String indexName; private final String query; private final IdAndVersionFactory idAndVersionFactory; private final IVersionHelper versionHelper; public ElasticsearchJestIndex(JestClient client, String indexName, String query, IdAndVersionFactory idAndVersionFactory, IVersionHelper versionHelper) { this.client = client; this.indexName = indexName; this.query = query; this.idAndVersionFactory = idAndVersionFactory; this.versionHelper = versionHelper; } @Override public IdAndVersionFactory getIdAndVersionFactory() { return idAndVersionFactory; } @Override public void downloadTo(String type, OutputStream outputStream) { long begin = System.currentTimeMillis(); doDownloadTo(type, outputStream); LogUtils.infoTimeTaken(LOG, begin, numItems, "Scan & Download completed"); numItems = 0; } private void doDownloadTo(String type, OutputStream outputStream) { try { ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); consumeBatches(objectOutputStream, startScroll(type)); objectOutputStream.close(); } catch (Exception e) { throw new RuntimeException(e); } } void consumeBatches(ObjectOutputStream objectOutputStream, String initialScrollId) throws Exception { String scrollId = initialScrollId; JestResult batchSearchResponse = null; do { SearchScroll.Builder builder = new SearchScroll.Builder(scrollId, SCROLL_TIME_IN_MINUTES + "m"); batchSearchResponse = client.execute(builder.build()); scrollId = batchSearchResponse.getJsonObject().get("_scroll_id").getAsString(); } while (writeSearchResponseToOutputStream(objectOutputStream, batchSearchResponse)); } boolean writeSearchResponseToOutputStream(ObjectOutputStream objectOutputStream, JestResult searchResponse) throws IOException { // "hits":{"total":62319,"max_score":0.0,"hits":[{"_index":"stats","_type":"stats","_id":"MostPopularArtists","_version":1392888398281,"_score":0.0,"_source":{"_id":"MostPopularArtists","_ttl":5 JsonArray hits = searchResponse.getJsonObject().getAsJsonObject("hits").getAsJsonArray("hits"); for (JsonElement e : hits) { JsonObject hit = e.getAsJsonObject(); String id = hit.get("_id").getAsString(); long version = hit.get("_version").getAsLong(); idAndVersionFactory.create(id, version).writeToStream(objectOutputStream); numItems++; } return hits.size() > 0; } String startScroll(String type) { Builder builder = new Search.Builder(versionHelper.createQuery(query)); builder.addIndex(indexName); builder.addType(type); builder.setParameter(Parameters.SIZE, BATCH_SIZE); builder.setParameter(Parameters.EXPLAIN, false); // searchRequestBuilder.setNoFields(); builder.setParameter(Parameters.VERSION, true); builder.setSearchType(SearchType.SCAN); builder.setParameter(Parameters.SCROLL, SCROLL_TIME_IN_MINUTES + "m"); try { JestResult result = client.execute(builder.build()); if (result.isSucceeded()) { return result.getJsonObject().get("_scroll_id").getAsString(); } else { throw new RuntimeException("failed to start scroll operation: " + result.getJsonObject()); } } catch (Exception e) { throw new RuntimeException("failed to start scroll operation", e); } } @Override public void load(List<Document> documents, final Runnable listener) { final Map<String, Map<String, Document>> map = new HashMap<>(); MultiGet.Builder.ByDoc builder = new MultiGet.Builder.ByDoc(EMPTY_DOC_LIST); for (Document doc : documents) { builder.addDoc(new Doc(indexName, doc.getType(), doc.getId())); Map<String, Document> typeMap = map.get(doc.getType()); if (typeMap == null) { map.put(doc.getType(), typeMap = new HashMap<>()); } typeMap.put(doc.getId(), doc); } try { JestResult result = client.execute(builder.build()); JsonArray docs = result.getJsonObject().getAsJsonArray("docs"); for (JsonElement e : docs) { JsonObject item = e.getAsJsonObject(); String type = item.get("_type").getAsString(); String id = item.get("_id").getAsString(); Map<String, Document> typeMap = map.get(type); if (typeMap == null) { LOG.warn("unexpected type returned: " + type); continue; } Document doc = typeMap.get(id); if (doc == null) { LOG.warn("unexpected id returned: " + type + "/" + id); continue; } if (item.get("exists").getAsBoolean()) { long version = item.get("_version").getAsLong(); String source = item.get("_source").toString(); doc.setVersion(version).setSource(source); } else { doc.setDeleted(); } // } } if (listener != null) { listener.run(); } } catch (Exception e) { LOG.error("loading documents failed", e); if (listener != null) { listener.run(); } } } @Override public void index(final List<Document> documents, final Runnable listener) { Bulk.Builder builder = new Bulk.Builder(); for (Document doc : documents) { if (doc.isDeleted()) { builder.addAction(new Delete.Builder(indexName, doc.getType(), doc.getId()) .setParameter(Parameters.VERSION_TYPE, "external") .setParameter(Parameters.VERSION, doc.getVersion() + 1).build()); } else { builder.addAction(new Index.Builder(doc.getSource()).index(indexName).type(doc.getType()) .id(doc.getId()).setParameter(Parameters.VERSION_TYPE, "external") .setParameter(Parameters.VERSION, doc.getVersion()).build()); } } try { JestResult result = client.execute(builder.build()); JsonArray items = result.getJsonObject().getAsJsonArray("items"); Iterator<Document> docIter = documents.iterator(); for (JsonElement e : items) { JsonObject item = e.getAsJsonObject(); if (item.has("error")) { Document document = docIter.next(); LOG.warn("document {} failed {} ({})", document.isDeleted() ? "delete" : "index", document, item .get("error").getAsString()); } } if (listener != null) { listener.run(); } } catch (Exception e) { LOG.error("indexing documents failed", e); if (listener != null) { listener.run(); } } } @Override public void close() { if (client != null) { client.shutdownClient(); } } }
handle missing versions (caused by negative versions)
src/main/java/at/molindo/elasticsync/jest/internal/ElasticsearchJestIndex.java
handle missing versions (caused by negative versions)
<ide><path>rc/main/java/at/molindo/elasticsync/jest/internal/ElasticsearchJestIndex.java <ide> <ide> private static final List<Doc> EMPTY_DOC_LIST = Collections.emptyList(); <ide> <del> static final int BATCH_SIZE = 100000; // only ids and versions <add> static final int BATCH_SIZE = 10_000; // only ids and versions, per shard <ide> static final int SCROLL_TIME_IN_MINUTES = 10; <ide> <ide> private long numItems = 0; <ide> <ide> // "hits":{"total":62319,"max_score":0.0,"hits":[{"_index":"stats","_type":"stats","_id":"MostPopularArtists","_version":1392888398281,"_score":0.0,"_source":{"_id":"MostPopularArtists","_ttl":5 <ide> <del> JsonArray hits = searchResponse.getJsonObject().getAsJsonObject("hits").getAsJsonArray("hits"); <add> JsonObject obj = searchResponse.getJsonObject().getAsJsonObject("hits"); <add> <add> long total = obj.get("total").getAsLong(); <add> <add> JsonArray hits = obj.getAsJsonArray("hits"); <add> <add> LOG.debug("scroll returned {} of {} total hits", hits.size(), total); <ide> <ide> for (JsonElement e : hits) { <ide> JsonObject hit = e.getAsJsonObject(); <ide> <ide> String id = hit.get("_id").getAsString(); <del> long version = hit.get("_version").getAsLong(); <add> JsonElement v = hit.get("_version"); <add> <add> Long version; <add> if (v == null) { <add> LOG.debug("missing version for id {}", id); <add> version = 1L; <add> } else { <add> version = v.getAsLong(); <add> } <ide> <ide> idAndVersionFactory.create(id, version).writeToStream(objectOutputStream); <ide> numItems++;
Java
mit
1b59a723a546178b140eba560adc09099fb78fea
0
sormuras/bach,sormuras/bach
/* * Bach - Java Shell Builder * Copyright (C) 2019 Christian Stein * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.sormuras.bach; import java.nio.file.Path; import java.util.Collection; import java.util.List; /*BODY*/ public /*STATIC*/ class Jigsaw { private final Bach bach; private final Project project; private final Project.Realm realm; private final Project.Target target; private final Path classes; public Jigsaw(Bach bach, Project project, Project.Realm realm) { this.bach = bach; this.project = project; this.realm = realm; this.target = project.target(realm); this.classes = target.directory.resolve("jigsaw").resolve("classes"); } public void compile(Collection<String> modules) { bach.log("Compiling %s realm jigsaw modules: %s", realm.name, modules); bach.run( new Command("javac") .addEach(realm.toolArguments.javac) .add("-d", classes) .addIff(realm.preview, "--enable-preview") .addIff(realm.release != 0, "--release", realm.release) .add("--module-path", project.modulePaths(target)) .add("--module-source-path", realm.moduleSourcePath) .add("--module-version", project.version) .addEach(patches(modules)) .add("--module", String.join(",", modules)) // ); for (var module : modules) { var unit = realm.unit(module).orElseThrow(); jarModule(unit); jarSources(unit); } } private List<String> patches(Collection<String> modules) { var patches = new Command("<patches>"); for (var module : modules) { var other = realm.realms.stream() .flatMap(r -> r.units.stream()) .filter(u -> u.name().equals(module)) .findFirst(); other.ifPresent( unit -> patches.add( "--patch-module", unit.sources.stream().map(s -> s.path), v -> module + "=" + v)); } return patches.getArguments(); } private void jarModule(Project.ModuleUnit unit) { var descriptor = unit.info.descriptor(); bach.run( new Command("jar") .add("--create") .add("--file", Util.treeCreate(target.modules).resolve(target.file(unit, ".jar"))) .addIff(bach.verbose(), "--verbose") .addIff("--module-version", descriptor.version()) .addIff("--main-class", descriptor.mainClass()) .add("-C", classes.resolve(descriptor.name())) .add(".") .addEach(unit.resources, (cmd, path) -> cmd.add("-C", path).add("."))); if (bach.verbose()) { bach.run(new Command("jar", "--describe-module", "--file", target.modularJar(unit))); } } private void jarSources(Project.ModuleUnit unit) { bach.run( new Command("jar") .add("--create") .add("--file", target.sourcesJar(unit)) .addIff(bach.verbose(), "--verbose") .add("--no-manifest") .addEach(unit.sources, (cmd, source) -> cmd.add("-C", source.path).add(".")) .addEach(unit.resources, (cmd, path) -> cmd.add("-C", path).add("."))); } }
src/modules/de.sormuras.bach/main/java/de/sormuras/bach/Jigsaw.java
/* * Bach - Java Shell Builder * Copyright (C) 2019 Christian Stein * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.sormuras.bach; import java.nio.file.Path; import java.util.Collection; /*BODY*/ public /*STATIC*/ class Jigsaw { private final Bach bach; private final Project project; private final Project.Realm realm; private final Project.Target target; private final Path classes; public Jigsaw(Bach bach, Project project, Project.Realm realm) { this.bach = bach; this.project = project; this.realm = realm; this.target = project.target(realm); this.classes = target.directory.resolve("jigsaw").resolve("classes"); } public void compile(Collection<String> modules) { bach.log("Compiling %s realm jigsaw modules: %s", realm.name, modules); bach.run( new Command("javac") .addEach(realm.toolArguments.javac) .add("-d", classes) .addIff(realm.preview, "--enable-preview") .addIff(realm.release != 0, "--release", realm.release) .add("--module-path", project.modulePaths(target)) .add("--module-source-path", realm.moduleSourcePath) .add("--module-version", project.version) .add("--module", String.join(",", modules))); for (var module : modules) { var unit = realm.unit(module).orElseThrow(); jarModule(unit); jarSources(unit); } } private void jarModule(Project.ModuleUnit unit) { var descriptor = unit.info.descriptor(); bach.run( new Command("jar") .add("--create") .add("--file", Util.treeCreate(target.modules).resolve(target.file(unit, ".jar"))) .addIff(bach.verbose(), "--verbose") .addIff("--module-version", descriptor.version()) .addIff("--main-class", descriptor.mainClass()) .add("-C", classes.resolve(descriptor.name())) .add(".") .addEach(unit.resources, (cmd, path) -> cmd.add("-C", path).add("."))); if (bach.verbose()) { bach.run(new Command("jar", "--describe-module", "--file", target.modularJar(unit))); } } private void jarSources(Project.ModuleUnit unit) { bach.run( new Command("jar") .add("--create") .add("--file", target.sourcesJar(unit)) .addIff(bach.verbose(), "--verbose") .add("--no-manifest") .addEach(unit.sources, (cmd, source) -> cmd.add("-C", source.path).add(".")) .addEach(unit.resources, (cmd, path) -> cmd.add("-C", path).add("."))); } }
Patch main sources into test modules
src/modules/de.sormuras.bach/main/java/de/sormuras/bach/Jigsaw.java
Patch main sources into test modules
<ide><path>rc/modules/de.sormuras.bach/main/java/de/sormuras/bach/Jigsaw.java <ide> <ide> import java.nio.file.Path; <ide> import java.util.Collection; <add>import java.util.List; <ide> <ide> /*BODY*/ <ide> public /*STATIC*/ class Jigsaw { <ide> .add("--module-path", project.modulePaths(target)) <ide> .add("--module-source-path", realm.moduleSourcePath) <ide> .add("--module-version", project.version) <del> .add("--module", String.join(",", modules))); <add> .addEach(patches(modules)) <add> .add("--module", String.join(",", modules)) // <add> ); <ide> for (var module : modules) { <ide> var unit = realm.unit(module).orElseThrow(); <ide> jarModule(unit); <ide> jarSources(unit); <ide> } <add> } <add> <add> private List<String> patches(Collection<String> modules) { <add> var patches = new Command("<patches>"); <add> for (var module : modules) { <add> var other = <add> realm.realms.stream() <add> .flatMap(r -> r.units.stream()) <add> .filter(u -> u.name().equals(module)) <add> .findFirst(); <add> other.ifPresent( <add> unit -> <add> patches.add( <add> "--patch-module", unit.sources.stream().map(s -> s.path), v -> module + "=" + v)); <add> } <add> return patches.getArguments(); <ide> } <ide> <ide> private void jarModule(Project.ModuleUnit unit) {
JavaScript
bsd-3-clause
9bef68c2bd684e3b8d952cf43796c3f93409cd35
0
codeforamerica/streetmix,codeforamerica/streetmix,codeforamerica/streetmix
import { trackEvent } from '../app/event_tracking' import { infoBubble } from '../info_bubble/info_bubble' import { INFO_BUBBLE_TYPE_SEGMENT } from '../info_bubble/constants' import { setIgnoreStreetChanges } from '../streets/data_model' import { draggingResize } from './drag_and_drop' import { segmentsChanged } from './view' import { BUILDING_SPACE } from './buildings' import { TILE_SIZE, MIN_SEGMENT_WIDTH, MAX_SEGMENT_WIDTH, DRAGGING_TYPE_NONE, SEGMENT_WIDTH_RESOLUTION_IMPERIAL, SEGMENT_WIDTH_CLICK_INCREMENT_IMPERIAL, SEGMENT_WIDTH_DRAGGING_RESOLUTION_IMPERIAL, SEGMENT_WIDTH_RESOLUTION_METRIC, SEGMENT_WIDTH_CLICK_INCREMENT_METRIC, SEGMENT_WIDTH_DRAGGING_RESOLUTION_METRIC } from './constants' import { SETTINGS_UNITS_IMPERIAL } from '../users/constants' import store from '../store' import { changeSegmentWidth } from '../store/actions/street' import { setDraggingType } from '../store/actions/ui' const SHORT_DELAY = 100 export const RESIZE_TYPE_INITIAL = 0 export const RESIZE_TYPE_INCREMENT = 1 export const RESIZE_TYPE_DRAGGING = 2 export const RESIZE_TYPE_PRECISE_DRAGGING = 3 export const RESIZE_TYPE_TYPING = 4 const TOUCH_CONTROLS_FADEOUT_TIME = 3000 const TOUCH_CONTROLS_FADEOUT_DELAY = 3000 const NORMALIZE_PRECISION = 5 export function resizeSegment (dataNo, resizeType, width, units) { // @TODO: don't read state for units; this is a temp kludge because the drag resizing // handler doesn't currently have access to the units. So if it's not provided, grab it // from state const resolution = resolutionForResizeType(resizeType, units || store.getState().street.units) width = normalizeSegmentWidth(width, resolution) cancelSegmentResizeTransitions() store.dispatch(changeSegmentWidth(dataNo, width)) segmentsChanged() return width } export function handleSegmentResizeCancel () { resizeSegment(draggingResize.segmentEl.dataNo, RESIZE_TYPE_INITIAL, draggingResize.originalWidth) handleSegmentResizeEnd() } /** * Updates street section canvas margins when occupiedWidth is greater than default street extent * * The default street extent is equal to the street width + (2 * BUILDING_SPACE). When the occupiedWidth * is greater than the default street extent, the street-section-outer's scrollLeft no longer works properly. * * The solution to the above problem, is to update the street-section-canvas' margins and the building widths * based on how much the occupiedWidth extends greater than the street width and the default street extent. * * This function calculates the street margin based on the remainingWidth and compares it to the previous * street margin. If the previous street margin is not equal to the current street margin, it will update * street-section-canvas' margins accordingly (except in specific situations described within the function) * */ export function updateStreetMargin (canvasRef, streetOuterRef, dontDelay = false) { const streetSectionCanvas = canvasRef || document.querySelector('#street-section-canvas') const streetSectionOuter = streetOuterRef || document.querySelector('#street-section-outer') const prevMargin = Number.parseInt(streetSectionCanvas.style.marginLeft, 10) || BUILDING_SPACE const { remainingWidth } = store.getState().street let streetMargin = Math.round(-remainingWidth * TILE_SIZE / 2) if (!streetMargin || streetMargin < BUILDING_SPACE) { streetMargin = BUILDING_SPACE } const deltaMargin = (streetMargin - prevMargin) if (!deltaMargin) return false const maxScrollLeft = streetSectionOuter.scrollWidth - streetSectionOuter.clientWidth // When scrolled all the way to right and decreasing occupiedWidth, an empty strip // of space is shown briefly before being scrolled if updating streetMargin. // When scrolled all the way to left and decreasing occupiedWidth, cannot update // scrollLeft to keep current segments in view (scrollLeft = 0) // Current solution is to delay updating margin until street is not scrolled all // the way to right or all the way to left or viewport was resized. const delayUpdate = (!dontDelay && deltaMargin < 0 && (Math.abs(deltaMargin) > streetSectionOuter.scrollLeft || streetSectionOuter.scrollLeft === maxScrollLeft)) if (!delayUpdate) { streetSectionCanvas.style.marginLeft = (streetMargin + 25) + 'px' streetSectionCanvas.style.marginRight = (streetMargin + 25) + 'px' } return (!delayUpdate) } export function handleSegmentResizeEnd (event) { setIgnoreStreetChanges(false) updateStreetMargin() segmentsChanged() store.dispatch(setDraggingType(DRAGGING_TYPE_NONE)) var el = draggingResize.floatingEl el.remove() draggingResize.segmentEl.classList.add('immediate-show-drag-handles') infoBubble.considerSegmentEl = draggingResize.segmentEl infoBubble.show(false) scheduleControlsFadeout(draggingResize.segmentEl) infoBubble.considerShowing(event, draggingResize.segmentEl, INFO_BUBBLE_TYPE_SEGMENT) if (draggingResize.width && (draggingResize.originalWidth !== draggingResize.width)) { trackEvent('INTERACTION', 'CHANGE_WIDTH', 'DRAGGING', null, true) } } /** * Returns the minimum resolution for segment / street widths. * Default return value is in metric units. * * @param {*} units - metric or imperial * @param {Number} */ export function getSegmentWidthResolution (units) { if (units === SETTINGS_UNITS_IMPERIAL) { return SEGMENT_WIDTH_RESOLUTION_IMPERIAL } return SEGMENT_WIDTH_RESOLUTION_METRIC } /** * Returns the minimum resolution when click-resizing segments * Default return value is in metric units. * * @param {*} units - metric or imperial * @param {Number} */ export function getSegmentClickResizeResolution (units) { if (units === SETTINGS_UNITS_IMPERIAL) { return SEGMENT_WIDTH_CLICK_INCREMENT_IMPERIAL } return SEGMENT_WIDTH_CLICK_INCREMENT_METRIC } /** * Returns the minimum resolution when drag-resizing segments * Default return value is in metric units. * * @param {Number} units - metric or imperial * @param {Number} */ export function getSegmentDragResizeResolution (units) { if (units === SETTINGS_UNITS_IMPERIAL) { return SEGMENT_WIDTH_DRAGGING_RESOLUTION_IMPERIAL } return SEGMENT_WIDTH_DRAGGING_RESOLUTION_METRIC } /** * Resolution is the precision at which measurements are rounded to, * in order to avoid awkward decimals. There are different levels * of precision depending on what action is performed. The resolution * is also different depending on whether the street is measured in * metric or imperial units. This function returns the minimum resolution * depending on the type of resize action and the measurement units. * * @param {Number} resizeType * @param {Number} units - metric or imperial * @returns {Number} */ export function resolutionForResizeType (resizeType, units) { switch (resizeType) { case RESIZE_TYPE_INITIAL: case RESIZE_TYPE_TYPING: case RESIZE_TYPE_PRECISE_DRAGGING: default: // Always return this resolution if `resizeType` is undefined or wrong value return getSegmentWidthResolution(units) case RESIZE_TYPE_INCREMENT: return getSegmentClickResizeResolution(units) case RESIZE_TYPE_DRAGGING: return getSegmentDragResizeResolution(units) } } /** * Given an input width value, constrains the value to the * minimum or maximum value, then rounds it to nearest precision * * @param {Number} width - input width value * @param {Number} resolution - resolution to round to * @returns {Number} */ export function normalizeSegmentWidth (width, resolution) { if (width < MIN_SEGMENT_WIDTH) { width = MIN_SEGMENT_WIDTH } else if (width > MAX_SEGMENT_WIDTH) { width = MAX_SEGMENT_WIDTH } width = Math.round(width / resolution) * resolution width = Number.parseFloat(width.toFixed(NORMALIZE_PRECISION)) return width } /** * Performs `normalizeSegmentWidth` on an array of segments and * returns the new array. * * @param {Array} segments * @param {Number} units - metric or imperial units * @returns {Array} */ export function normalizeAllSegmentWidths (segments, units) { return segments.map((segment) => ({ ...segment, width: normalizeSegmentWidth(segment.width, resolutionForResizeType(RESIZE_TYPE_INITIAL, units)) })) } let controlsFadeoutDelayTimer = -1 let controlsFadeoutHideTimer = -1 function scheduleControlsFadeout (el) { infoBubble.considerShowing(null, el, INFO_BUBBLE_TYPE_SEGMENT) resumeFadeoutControls() } export function resumeFadeoutControls () { const system = store.getState().system if (!system.touch) { return } cancelFadeoutControls() controlsFadeoutDelayTimer = window.setTimeout(fadeoutControls, TOUCH_CONTROLS_FADEOUT_DELAY) } export function cancelFadeoutControls () { document.body.classList.remove('controls-fade-out') window.clearTimeout(controlsFadeoutDelayTimer) window.clearTimeout(controlsFadeoutHideTimer) } function fadeoutControls () { document.body.classList.add('controls-fade-out') controlsFadeoutHideTimer = window.setTimeout(hideControls, TOUCH_CONTROLS_FADEOUT_TIME) } export function hideControls () { document.body.classList.remove('controls-fade-out') if (infoBubble.segmentEl) { infoBubble.segmentEl.classList.remove('show-drag-handles') window.setTimeout(function () { infoBubble.hide() infoBubble.hideSegment(true) }, 0) } } export function cancelSegmentResizeTransitions () { document.body.classList.add('immediate-segment-resize') window.setTimeout(function () { document.body.classList.remove('immediate-segment-resize') }, SHORT_DELAY) }
assets/scripts/segments/resizing.js
import { trackEvent } from '../app/event_tracking' import { infoBubble } from '../info_bubble/info_bubble' import { INFO_BUBBLE_TYPE_SEGMENT } from '../info_bubble/constants' import { setIgnoreStreetChanges } from '../streets/data_model' import { draggingResize } from './drag_and_drop' import { segmentsChanged } from './view' import { BUILDING_SPACE } from './buildings' import { TILE_SIZE, MIN_SEGMENT_WIDTH, MAX_SEGMENT_WIDTH, DRAGGING_TYPE_NONE, SEGMENT_WIDTH_RESOLUTION_IMPERIAL, SEGMENT_WIDTH_CLICK_INCREMENT_IMPERIAL, SEGMENT_WIDTH_DRAGGING_RESOLUTION_IMPERIAL, SEGMENT_WIDTH_RESOLUTION_METRIC, SEGMENT_WIDTH_CLICK_INCREMENT_METRIC, SEGMENT_WIDTH_DRAGGING_RESOLUTION_METRIC } from './constants' import { SETTINGS_UNITS_IMPERIAL } from '../users/constants' import store from '../store' import { changeSegmentWidth } from '../store/actions/street' import { setDraggingType } from '../store/actions/ui' const SHORT_DELAY = 100 export const RESIZE_TYPE_INITIAL = 0 export const RESIZE_TYPE_INCREMENT = 1 export const RESIZE_TYPE_DRAGGING = 2 export const RESIZE_TYPE_PRECISE_DRAGGING = 3 export const RESIZE_TYPE_TYPING = 4 const TOUCH_CONTROLS_FADEOUT_TIME = 3000 const TOUCH_CONTROLS_FADEOUT_DELAY = 3000 const NORMALIZE_PRECISION = 5 export function resizeSegment (dataNo, resizeType, width) { width = normalizeSegmentWidth(width, resizeType) cancelSegmentResizeTransitions() store.dispatch(changeSegmentWidth(dataNo, width)) segmentsChanged() return width } export function handleSegmentResizeCancel () { resizeSegment(draggingResize.segmentEl.dataNo, RESIZE_TYPE_INITIAL, draggingResize.originalWidth) handleSegmentResizeEnd() } /** * Updates street section canvas margins when occupiedWidth is greater than default street extent * * The default street extent is equal to the street width + (2 * BUILDING_SPACE). When the occupiedWidth * is greater than the default street extent, the street-section-outer's scrollLeft no longer works properly. * * The solution to the above problem, is to update the street-section-canvas' margins and the building widths * based on how much the occupiedWidth extends greater than the street width and the default street extent. * * This function calculates the street margin based on the remainingWidth and compares it to the previous * street margin. If the previous street margin is not equal to the current street margin, it will update * street-section-canvas' margins accordingly (except in specific situations described within the function) * */ export function updateStreetMargin (canvasRef, streetOuterRef, dontDelay = false) { const streetSectionCanvas = canvasRef || document.querySelector('#street-section-canvas') const streetSectionOuter = streetOuterRef || document.querySelector('#street-section-outer') const prevMargin = Number.parseInt(streetSectionCanvas.style.marginLeft, 10) || BUILDING_SPACE const { remainingWidth } = store.getState().street let streetMargin = Math.round(-remainingWidth * TILE_SIZE / 2) if (!streetMargin || streetMargin < BUILDING_SPACE) { streetMargin = BUILDING_SPACE } const deltaMargin = (streetMargin - prevMargin) if (!deltaMargin) return false const maxScrollLeft = streetSectionOuter.scrollWidth - streetSectionOuter.clientWidth // When scrolled all the way to right and decreasing occupiedWidth, an empty strip // of space is shown briefly before being scrolled if updating streetMargin. // When scrolled all the way to left and decreasing occupiedWidth, cannot update // scrollLeft to keep current segments in view (scrollLeft = 0) // Current solution is to delay updating margin until street is not scrolled all // the way to right or all the way to left or viewport was resized. const delayUpdate = (!dontDelay && deltaMargin < 0 && (Math.abs(deltaMargin) > streetSectionOuter.scrollLeft || streetSectionOuter.scrollLeft === maxScrollLeft)) if (!delayUpdate) { streetSectionCanvas.style.marginLeft = (streetMargin + 25) + 'px' streetSectionCanvas.style.marginRight = (streetMargin + 25) + 'px' } return (!delayUpdate) } export function handleSegmentResizeEnd (event) { setIgnoreStreetChanges(false) updateStreetMargin() segmentsChanged() store.dispatch(setDraggingType(DRAGGING_TYPE_NONE)) var el = draggingResize.floatingEl el.remove() draggingResize.segmentEl.classList.add('immediate-show-drag-handles') infoBubble.considerSegmentEl = draggingResize.segmentEl infoBubble.show(false) scheduleControlsFadeout(draggingResize.segmentEl) infoBubble.considerShowing(event, draggingResize.segmentEl, INFO_BUBBLE_TYPE_SEGMENT) if (draggingResize.width && (draggingResize.originalWidth !== draggingResize.width)) { trackEvent('INTERACTION', 'CHANGE_WIDTH', 'DRAGGING', null, true) } } /** * Returns the minimum resolution for segment / street widths. * Default return value is in metric units. * * @param {*} units - metric or imperial * @param {Number} */ export function getSegmentWidthResolution (units) { if (units === SETTINGS_UNITS_IMPERIAL) { return SEGMENT_WIDTH_RESOLUTION_IMPERIAL } return SEGMENT_WIDTH_RESOLUTION_METRIC } /** * Returns the minimum resolution when click-resizing segments * Default return value is in metric units. * * @param {*} units - metric or imperial * @param {Number} */ export function getSegmentClickResizeResolution (units) { if (units === SETTINGS_UNITS_IMPERIAL) { return SEGMENT_WIDTH_CLICK_INCREMENT_IMPERIAL } return SEGMENT_WIDTH_CLICK_INCREMENT_METRIC } /** * Returns the minimum resolution when drag-resizing segments * Default return value is in metric units. * * @param {Number} units - metric or imperial * @param {Number} */ export function getSegmentDragResizeResolution (units) { if (units === SETTINGS_UNITS_IMPERIAL) { return SEGMENT_WIDTH_DRAGGING_RESOLUTION_IMPERIAL } return SEGMENT_WIDTH_DRAGGING_RESOLUTION_METRIC } /** * Resolution is the precision at which measurements are rounded to, * in order to avoid awkward decimals. There are different levels * of precision depending on what action is performed. The resolution * is also different depending on whether the street is measured in * metric or imperial units. This function returns the minimum resolution * depending on the type of resize action and the measurement units. * * @param {Number} resizeType * @param {Number} units - metric or imperial * @returns {Number} */ export function resolutionForResizeType (resizeType, units) { switch (resizeType) { case RESIZE_TYPE_INITIAL: case RESIZE_TYPE_TYPING: case RESIZE_TYPE_PRECISE_DRAGGING: default: // Always return this resolution if `resizeType` is undefined or wrong value return getSegmentWidthResolution(units) case RESIZE_TYPE_INCREMENT: return getSegmentClickResizeResolution(units) case RESIZE_TYPE_DRAGGING: return getSegmentDragResizeResolution(units) } } /** * Given an input width value, constrains the value to the * minimum or maximum value, then rounds it to nearest precision * * @param {Number} width - input width value * @param {Number} resolution - resolution to round to * @returns {Number} */ export function normalizeSegmentWidth (width, resolution) { if (width < MIN_SEGMENT_WIDTH) { width = MIN_SEGMENT_WIDTH } else if (width > MAX_SEGMENT_WIDTH) { width = MAX_SEGMENT_WIDTH } width = Math.round(width / resolution) * resolution width = Number.parseFloat(width.toFixed(NORMALIZE_PRECISION)) return width } /** * Performs `normalizeSegmentWidth` on an array of segments and * returns the new array. * * @param {Array} segments * @param {Number} units - metric or imperial units * @returns {Array} */ export function normalizeAllSegmentWidths (segments, units) { return segments.map((segment) => ({ ...segment, width: normalizeSegmentWidth(segment.width, resolutionForResizeType(RESIZE_TYPE_INITIAL, units)) })) } let controlsFadeoutDelayTimer = -1 let controlsFadeoutHideTimer = -1 function scheduleControlsFadeout (el) { infoBubble.considerShowing(null, el, INFO_BUBBLE_TYPE_SEGMENT) resumeFadeoutControls() } export function resumeFadeoutControls () { const system = store.getState().system if (!system.touch) { return } cancelFadeoutControls() controlsFadeoutDelayTimer = window.setTimeout(fadeoutControls, TOUCH_CONTROLS_FADEOUT_DELAY) } export function cancelFadeoutControls () { document.body.classList.remove('controls-fade-out') window.clearTimeout(controlsFadeoutDelayTimer) window.clearTimeout(controlsFadeoutHideTimer) } function fadeoutControls () { document.body.classList.add('controls-fade-out') controlsFadeoutHideTimer = window.setTimeout(hideControls, TOUCH_CONTROLS_FADEOUT_TIME) } export function hideControls () { document.body.classList.remove('controls-fade-out') if (infoBubble.segmentEl) { infoBubble.segmentEl.classList.remove('show-drag-handles') window.setTimeout(function () { infoBubble.hide() infoBubble.hideSegment(true) }, 0) } } export function cancelSegmentResizeTransitions () { document.body.classList.add('immediate-segment-resize') window.setTimeout(function () { document.body.classList.remove('immediate-segment-resize') }, SHORT_DELAY) }
fix(resize): incorrect drag resolution, resolves #1297
assets/scripts/segments/resizing.js
fix(resize): incorrect drag resolution, resolves #1297
<ide><path>ssets/scripts/segments/resizing.js <ide> <ide> const NORMALIZE_PRECISION = 5 <ide> <del>export function resizeSegment (dataNo, resizeType, width) { <del> width = normalizeSegmentWidth(width, resizeType) <add>export function resizeSegment (dataNo, resizeType, width, units) { <add> // @TODO: don't read state for units; this is a temp kludge because the drag resizing <add> // handler doesn't currently have access to the units. So if it's not provided, grab it <add> // from state <add> const resolution = resolutionForResizeType(resizeType, units || store.getState().street.units) <add> width = normalizeSegmentWidth(width, resolution) <ide> cancelSegmentResizeTransitions() <ide> store.dispatch(changeSegmentWidth(dataNo, width)) <ide> segmentsChanged()
Java
apache-2.0
9796680051fb1af0e03910ead2aad7f3b74e78f2
0
ImmobilienScout24/deadcode4j
package de.is24.deadcode4j.analyzer.javassist; import com.google.common.collect.Lists; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Collection; import java.util.Collections; import java.util.Set; import static com.google.common.collect.Sets.newHashSet; import static java.util.Arrays.asList; /** * Provides convenience methods with which to analyze instances of {@link javassist.CtClass}. * * @since 1.6 */ public final class CtClasses { private static boolean issuedWarningForJavaLangAnnotationRepeatable = false; private CtClasses() { } /** * Retrieves the specified class. * This method swallows class loading issues, returning only those classes that are accessible by the * {@link javassist.CtClass#getClassPool() class pool}. * * @since 1.6 */ @Nullable public static CtClass getCtClass(@Nonnull ClassPool classPool, @Nonnull String className) { CtClass clazz = classPool.getOrNull(className); if (clazz == null) { handleMissingClass(className); } return clazz; } /** * Returns {@code true} if the specified class refers to {@link java.lang.Object}. * * @since 1.6 */ public static boolean isJavaLangObject(@Nullable CtClass loopClass) { return loopClass != null && "java.lang.Object".equals(loopClass.getName()); } /** * Retrieves all interfaces a class implements - either directly, via superclass or via interface inheritance. * * @throws java.lang.RuntimeException if an implemented interface or super class cannot be loaded * @see #getInterfacesOf(javassist.CtClass) * @since 1.6 */ @Nonnull public static Set<String> getAllImplementedInterfaces(@Nonnull final CtClass clazz) { Set<String> interfaces = newHashSet(); CtClass loopClass = clazz; do { for (CtClass anInterface : getInterfacesOf(loopClass)) { interfaces.add(anInterface.getName()); interfaces.addAll(getAllImplementedInterfaces(anInterface)); } loopClass = getSuperclassOf(loopClass); } while (loopClass != null && !isJavaLangObject(loopClass)); return interfaces; } /** * Retrieves all interfaces a class directly implements. * This method swallows class loading issues, returning only those classes that are accessible by the * {@link javassist.CtClass#getClassPool() class pool}. * * @see #getAllImplementedInterfaces(javassist.CtClass) * @since 1.6 */ @Nonnull public static Iterable<CtClass> getInterfacesOf(@Nonnull CtClass clazz) { String[] interfaceNames = clazz.getClassFile2().getInterfaces(); Collection<CtClass> interfaces = Lists.newArrayListWithCapacity(interfaceNames.length); for (String nameOfInterface : interfaceNames) { CtClass interfaze = getCtClass(clazz, nameOfInterface); if (interfaze != null) { interfaces.add(interfaze); } } return interfaces; } /** * Retrieves the superclass. * This method swallows class loading issues, returning only those classes that are accessible by the * {@link javassist.CtClass#getClassPool() class pool}. * * @since 1.6 */ @Nullable public static CtClass getSuperclassOf(@Nonnull CtClass clazz) { String nameOfSuperclass = clazz.getClassFile2().getSuperclass(); return getCtClass(clazz, nameOfSuperclass); } /** * Retrieves the declaring classes in bottom-up order. * This method swallows class loading issues, returning only those classes that are accessible by the * {@link javassist.CtClass#getClassPool() class pool}. * * @since 1.6 */ @Nonnull public static Iterable<CtClass> getDeclaringClassesOf(@Nonnull CtClass clazz) { Collection<CtClass> declaringClasses = Lists.newArrayList(); for (CtClass declarer = clazz; declarer != null; declarer = getDeclaringClassOf(declarer)) { declaringClasses.add(declarer); } return declaringClasses; } /** * Retrieves the nested classes. * This method swallows class loading issues, returning only those classes that are accessible by the * {@link javassist.CtClass#getClassPool() class pool}. * * @since 1.6 */ @Nonnull public static Iterable<CtClass> getNestedClassesOf(@Nonnull CtClass clazz) { try { return asList(clazz.getNestedClasses()); } catch (NotFoundException e) { handleMissingClass(e.getMessage()); return Collections.emptyList(); } } private static Logger getLogger() { return LoggerFactory.getLogger(CtClasses.class); } private static void handleMissingClass(@Nonnull String className) { if ("java.lang.annotation.Repeatable".equals(className)) { if (issuedWarningForJavaLangAnnotationRepeatable) { return; } getLogger().warn("Running with JDK < 8, but classes or libraries refer to JDK8 annotation {}.", className); issuedWarningForJavaLangAnnotationRepeatable = true; } else { getLogger().warn("The class path is not correctly set up; could not load {}!", className); } } @Nullable private static CtClass getCtClass(@Nonnull CtClass classProvidingPool, @Nonnull String className) { return getCtClass(classProvidingPool.getClassPool(), className); } @Nullable private static CtClass getDeclaringClassOf(@Nonnull CtClass clazz) { try { return clazz.getDeclaringClass(); } catch (NotFoundException e) { handleMissingClass(e.getMessage()); return null; } } }
src/main/java/de/is24/deadcode4j/analyzer/javassist/CtClasses.java
package de.is24.deadcode4j.analyzer.javassist; import com.google.common.collect.Lists; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Collection; import java.util.Collections; import java.util.Set; import static com.google.common.collect.Sets.newHashSet; import static java.util.Arrays.asList; /** * Provides convenience methods with which to analyze instances of {@link javassist.CtClass}. * * @since 1.6 */ public final class CtClasses { private static boolean issuedWarningForJavaLangAnnotationRepeatable = false; private CtClasses() { } /** * Retrieves the specified class. * This method swallows class loading issues, returning only those classes that are accessible by the * {@link javassist.CtClass#getClassPool() class pool}. * * @since 1.6 */ @Nullable public static CtClass getCtClass(@Nonnull ClassPool classPool, @Nonnull String className) { CtClass clazz = classPool.getOrNull(className); if (clazz == null) { handleMissingClass(className); } return clazz; } /** * Returns {@code true} if the specified class refers to {@link java.lang.Object}. * * @since 1.6 */ public static boolean isJavaLangObject(@Nullable CtClass loopClass) { return loopClass != null && "java.lang.Object".equals(loopClass.getName()); } /** * Retrieves all interfaces a class implements - either directly, via superclass or via interface inheritance. * * @throws java.lang.RuntimeException if an implemented interface or super class cannot be loaded * @see #getInterfacesOf(javassist.CtClass) * @since 1.6 */ @Nonnull public static Set<String> getAllImplementedInterfaces(@Nonnull final CtClass clazz) { Set<String> interfaces = newHashSet(); CtClass loopClass = clazz; do { for (CtClass anInterface : getInterfacesOf(loopClass)) { interfaces.add(anInterface.getName()); interfaces.addAll(getAllImplementedInterfaces(anInterface)); } loopClass = getSuperclassOf(loopClass); } while (loopClass != null && !isJavaLangObject(loopClass)); return interfaces; } /** * Retrieves all interfaces a class directly implements. * This method swallows class loading issues, returning only those classes that are accessible by the * {@link javassist.CtClass#getClassPool() class pool}. * * @see #getAllImplementedInterfaces(javassist.CtClass) * @since 1.6 */ @Nonnull public static Iterable<CtClass> getInterfacesOf(@Nonnull CtClass clazz) { String[] interfaceNames = clazz.getClassFile2().getInterfaces(); Collection<CtClass> interfaces = Lists.newArrayListWithCapacity(interfaceNames.length); for (String nameOfInterface : interfaceNames) { CtClass interfaze = getCtClass(clazz, nameOfInterface); if (interfaze != null) { interfaces.add(interfaze); } } return interfaces; } /** * Retrieves the superclass. * This method swallows class loading issues, returning only those classes that are accessible by the * {@link javassist.CtClass#getClassPool() class pool}. * * @since 1.6 */ @Nullable public static CtClass getSuperclassOf(@Nonnull CtClass clazz) { String nameOfSuperclass = clazz.getClassFile2().getSuperclass(); return getCtClass(clazz, nameOfSuperclass); } /** * Retrieves the nested classes. * This method swallows class loading issues, returning only those classes that are accessible by the * {@link javassist.CtClass#getClassPool() class pool}. * * @since 1.6 */ @Nonnull public static Iterable<CtClass> getNestedClassesOf(@Nonnull CtClass clazz) { try { return asList(clazz.getNestedClasses()); } catch (NotFoundException e) { handleMissingClass(e.getMessage()); return Collections.emptyList(); } } private static Logger getLogger() { return LoggerFactory.getLogger(CtClasses.class); } private static void handleMissingClass(@Nonnull String className) { if ("java.lang.annotation.Repeatable".equals(className)) { if (issuedWarningForJavaLangAnnotationRepeatable) { return; } getLogger().warn("Running with JDK < 8, but classes or libraries refer to JDK8 annotation {}.", className); issuedWarningForJavaLangAnnotationRepeatable = true; } else { getLogger().warn("The class path is not correctly set up; could not load {}!", className); } } @Nullable private static CtClass getCtClass(@Nonnull CtClass classProvidingPool, @Nonnull String className) { return getCtClass(classProvidingPool.getClassPool(), className); } }
start resolving references to inherited types
src/main/java/de/is24/deadcode4j/analyzer/javassist/CtClasses.java
start resolving references to inherited types
<ide><path>rc/main/java/de/is24/deadcode4j/analyzer/javassist/CtClasses.java <ide> <ide> <ide> /** <add> * Retrieves the declaring classes in bottom-up order. <add> * This method swallows class loading issues, returning only those classes that are accessible by the <add> * {@link javassist.CtClass#getClassPool() class pool}. <add> * <add> * @since 1.6 <add> */ <add> @Nonnull <add> public static Iterable<CtClass> getDeclaringClassesOf(@Nonnull CtClass clazz) { <add> Collection<CtClass> declaringClasses = Lists.newArrayList(); <add> for (CtClass declarer = clazz; declarer != null; declarer = getDeclaringClassOf(declarer)) { <add> declaringClasses.add(declarer); <add> } <add> return declaringClasses; <add> } <add> <add> /** <ide> * Retrieves the nested classes. <ide> * This method swallows class loading issues, returning only those classes that are accessible by the <ide> * {@link javassist.CtClass#getClassPool() class pool}. <ide> return getCtClass(classProvidingPool.getClassPool(), className); <ide> } <ide> <add> @Nullable <add> private static CtClass getDeclaringClassOf(@Nonnull CtClass clazz) { <add> try { <add> return clazz.getDeclaringClass(); <add> } catch (NotFoundException e) { <add> handleMissingClass(e.getMessage()); <add> return null; <add> } <add> } <add> <ide> }
JavaScript
agpl-3.0
e74601d132de8246c3e7fb04037ea442d7c36ab5
0
axelor/axelor-development-kit,axelor/axelor-development-kit,axelor/axelor-development-kit,axelor/axelor-development-kit
/* * Axelor Business Solutions * * Copyright (C) 2005-2018 Axelor (<http://axelor.com>). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ (function() { "use strict"; var ui = angular.module('axelor.ui'); /** * The Boolean input widget. */ ui.formInput('Boolean', { css: 'boolean-item', cellCss: 'form-item boolean-item', link: function (scope, element, attrs, model) { element.on('click', 'input:not(.no-toggle)', function (e) { scope.setValue(e.target.checked, true); }); Object.defineProperty(scope, '$value', { get: function () { return model.$viewValue; }, set: function(value) { model.$setViewValue(value); } }); }, template_readonly: null, template_editable: "<label class='ibox'>" + "<input type='checkbox' ng-model='$value' ng-disabled='isReadonly()'>" + "<span class='box'></span>" + "</label>" }); /** * The Boolean widget with label on right. */ ui.formInput('InlineCheckbox', 'Boolean', { css: 'checkbox-inline', metaWidget: true, showTitle: false, link: function (scope, element, attrs, model) { this._super.apply(this, arguments); scope.$watch('attr("title")', function booleanTitleWatch(title) { scope.label = title; }); }, template_readonly: null, template_editable: "<label class='ibox'>" + "<input type='checkbox' ng-model='$value' ng-disabled='isReadonly()'>" + "<div class='box'></div>" + "<span class='title' ui-help-popover>{{label}}</span>" + "</label>" }); ui.formInput('Toggle', 'Boolean', { cellCss: 'form-item toggle-item', metaWidget: true, link: function (scope, element, attrs, model) { this._super.apply(this, arguments); var field = scope.field; var icon = element.find('i'); scope.icon = function () { return model.$viewValue && field.iconActive ? field.iconActive : field.icon; }; scope.toggle = function () { var value = !model.$viewValue; if (scope.setExclusive && field.exclusive) { scope.setExclusive(field.name, scope.record); } scope.setValue(value, true); }; if (field.help || field.title) { element.attr('title', field.help || field.title); } }, template_readonly: null, template_editable: "<button tabindex='-1' class='btn btn-default' ng-class='{active: $value}' ng-click='toggle()'>" + "<i class='fa {{icon()}}'></i>" + "</button>" }); ui.formInput('BooleanSelect', 'Boolean', { css: 'form-item boolean-select-item', metaWidget: true, init: function (scope) { var field = scope.field; var trueText = _t((field.widgetAttrs||{}).trueText) || _t('Yes'); var falseText = _t((field.widgetAttrs||{}).falseText) || _t('No'); scope.$items = [trueText, falseText]; scope.$selection = [{ value: trueText, val: true}, { value: falseText, val: false }]; if (field.nullable) { scope.$selection.unshift({ value: '', val: null }); } scope.format = function (value) { if (field.nullable && (value === null || value === undefined)) { return ""; } return value ? scope.$items[0] : scope.$items[1]; }; }, link_editable: function (scope, element, attrs, model) { var input = element.find('input'); var items = scope.$items; input.autocomplete({ minLength: 0, source: scope.$selection, select: function (e, u) { scope.setValue(u.item.val, true); scope.$applyAsync(); } }).click(function (e) { input.autocomplete("search" , ''); }); scope.doShowSelect = function () { input.autocomplete("search" , ''); }; scope.$render_editable = function () { var value = model.$viewValue; var text = scope.format(value); input.val(text); }; scope.$watch('isReadonly()', function booleanReadonlyWatch(readonly) { input.autocomplete(readonly ? "disable" : "enable"); input.toggleClass('not-readonly', !readonly); }); }, template: "<span class='form-item-container'></span>", template_readonly: '<span>{{text}}</span>', template_editable: "<span class='picker-input'>" + "<input type='text' readonly='readonly' class='no-toggle'>" + "<span class='picker-icons picker-icons-1'>" + "<i class='fa fa-caret-down' ng-click='doShowSelect()'></i>" + "</span>" + "</span>" }); ui.formInput('BooleanRadio', 'BooleanSelect', { css: 'form-item boolean-radio-item', metaWidget: true, link_editable: function (scope, element, attrs, model) { var inputName = _.uniqueId('boolean-radio'); var trueInput = $('<input type="radio" data-value="true" name="' + inputName + '">'); var falseInput = $('<input type="radio" data-value="false" name="' + inputName + '">'); var items = scope.$items; $('<label class="ibox round">') .append(trueInput) .append($('<i class="box">')) .append($('<span class="title">').text(items[0])) .appendTo(element); $('<label class="ibox round">') .append(falseInput) .append($('<i class="box">')) .append($('<span class="title">').text(items[1])) .appendTo(element); scope.$render_editable = function () { var value = model.$viewValue || false; var input = value ? trueInput : falseInput; input.prop('checked', true); }; element.on('change', 'input', function (e) { var value = $(this).data('value') === true; scope.setValue(value, true); scope.$applyAsync(); }); }, template_editable: "<span></span>" }); ui.formInput('BooleanSwitch', 'Boolean', { css: 'form-item', metaWidget: true, template_readonly: null, template_editable: "<label class='iswitch'>" + "<input type='checkbox' ng-model='$value' ng-disabled='isReadonly()'>" + "<span class='box'></span>" + "</label>" }); })();
axelor-web/src/main/webapp/js/form/form.input.boolean.js
/* * Axelor Business Solutions * * Copyright (C) 2005-2018 Axelor (<http://axelor.com>). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ (function() { "use strict"; var ui = angular.module('axelor.ui'); /** * The Boolean input widget. */ ui.formInput('Boolean', { css: 'boolean-item', cellCss: 'form-item boolean-item', link: function (scope, element, attrs, model) { element.on('click', 'input:not(.no-toggle)', function (e) { scope.setValue(e.target.checked, true); }); Object.defineProperty(scope, '$value', { get: function () { return model.$viewValue; }, set: function(value) { model.$setViewValue(value); } }); }, template_readonly: null, template_editable: "<label class='ibox'>" + "<input type='checkbox' ng-model='$value' ng-disabled='isReadonly()'>" + "<span class='box'></span>" + "</label>" }); /** * The Boolean widget with label on right. */ ui.formInput('InlineCheckbox', 'Boolean', { css: 'checkbox-inline', metaWidget: true, showTitle: false, link: function (scope, element, attrs, model) { this._super.apply(this, arguments); scope.$watch('attr("title")', function booleanTitleWatch(title) { scope.label = title; }); }, template_readonly: null, template_editable: "<label class='ibox'>" + "<input type='checkbox' ng-model='$value' ng-disabled='isReadonly()'>" + "<div class='box'></div>" + "<span class='title' ui-help-popover>{{label}}</span>" + "</label>" }); ui.formInput('Toggle', 'Boolean', { cellCss: 'form-item toggle-item', metaWidget: true, link: function (scope, element, attrs, model) { this._super.apply(this, arguments); var field = scope.field; var icon = element.find('i'); scope.icon = function () { return model.$viewValue && field.iconActive ? field.iconActive : field.icon; }; scope.toggle = function () { var value = !model.$viewValue; if (scope.setExclusive && field.exclusive) { scope.setExclusive(field.name, scope.record); } scope.setValue(value, true); }; if (field.help || field.title) { element.attr('title', field.help || field.title); } }, template_readonly: null, template_editable: "<button tabindex='-1' class='btn btn-default' ng-class='{active: $value}' ng-click='toggle()'>" + "<i class='fa {{icon()}}'></i>" + "</button>" }); ui.formInput('BooleanSelect', 'Boolean', { css: 'form-item boolean-select-item', metaWidget: true, init: function (scope) { var field = scope.field; var trueText = _t((field.widgetAttrs||{}).trueText) || _t('Yes'); var falseText = _t((field.widgetAttrs||{}).falseText) || _t('No'); scope.$items = [trueText, falseText]; scope.$selection = [{ value: trueText, val: true}, { value: falseText, val: false }]; if (field.nullable) { scope.$selection.unshift({ value: '', val: null }); } scope.format = function (value) { if (field.nullable && (value === null || value === undefined)) { return ""; } return value ? scope.$items[0] : scope.$items[1]; }; }, link_editable: function (scope, element, attrs, model) { var input = element.find('input'); var items = scope.$items; input.autocomplete({ minLength: 0, source: scope.$selection, select: function (e, u) { scope.setValue(u.item.val, true); scope.$applyAsync(); } }).click(function (e) { input.autocomplete("search" , ''); }); scope.doShowSelect = function () { input.autocomplete("search" , ''); }; scope.$render_editable = function () { var value = model.$viewValue; var text = scope.format(value); input.val(text); }; scope.$watch('isReadonly()', function booleanReadonlyWatch(readonly) { input.autocomplete(readonly ? "disable" : "enable"); input.toggleClass('not-readonly', !readonly); }); }, template: "<span class='form-item-container'></span>", template_readonly: '<span>{{text}}</span>', template_editable: "<span class='picker-input'>" + "<input type='text' readonly='readonly' class='no-toggle'>" + "<span class='picker-icons picker-icons-1'>" + "<i class='fa fa-caret-down' ng-click='doShowSelect()'></i>" + "</span>" + "</span>" }); ui.formInput('BooleanRadio', 'BooleanSelect', { css: 'form-item boolean-radio-item', metaWidget: true, link_editable: function (scope, element, attrs, model) { var inputName = _.uniqueId('boolean-radio'); var trueInput = $('<input type="radio" data-value="true" name="' + inputName + '">'); var falseInput = $('<input type="radio" data-value="false" name="' + inputName + '">'); var items = scope.$items; $('<label class="ibox round">') .append(trueInput) .append($('<i class="box">')) .append($('<span class="title">').text(items[0])) .appendTo(element); $('<label class="ibox round">') .append(falseInput) .append($('<i class="box">')) .append($('<span class="title">').text(items[1])) .appendTo(element); scope.$render_editable = function () { var value = model.$viewValue || false; var input = value ? trueInput : falseInput; input.attr('checked', true); }; element.on('change', 'input', function (e) { var value = $(this).data('value') === true; scope.setValue(value, true); scope.$applyAsync(); }); }, template_editable: "<span></span>" }); ui.formInput('BooleanSwitch', 'Boolean', { css: 'form-item', metaWidget: true, template_readonly: null, template_editable: "<label class='iswitch'>" + "<input type='checkbox' ng-model='$value' ng-disabled='isReadonly()'>" + "<span class='box'></span>" + "</label>" }); })();
Fix boolean-radio widget issue Fixes RM-15256
axelor-web/src/main/webapp/js/form/form.input.boolean.js
Fix boolean-radio widget issue
<ide><path>xelor-web/src/main/webapp/js/form/form.input.boolean.js <ide> scope.$render_editable = function () { <ide> var value = model.$viewValue || false; <ide> var input = value ? trueInput : falseInput; <del> input.attr('checked', true); <add> input.prop('checked', true); <ide> }; <ide> <ide> element.on('change', 'input', function (e) {
Java
mit
ea434663f524c976c265382be206ef75da1b5716
0
DMDirc/DMDirc,ShaneMcC/DMDirc-Client,csmith/DMDirc,csmith/DMDirc,ShaneMcC/DMDirc-Client,csmith/DMDirc,ShaneMcC/DMDirc-Client,greboid/DMDirc,greboid/DMDirc,csmith/DMDirc,greboid/DMDirc,DMDirc/DMDirc,greboid/DMDirc,DMDirc/DMDirc,ShaneMcC/DMDirc-Client,DMDirc/DMDirc
/* * Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack, Gregory Holmes * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc.ui.framemanager.tree; import com.dmdirc.Channel; import com.dmdirc.Config; import com.dmdirc.FrameContainer; import com.dmdirc.Query; import com.dmdirc.Server; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.ui.framemanager.FrameManager; import static com.dmdirc.ui.UIUtilities.SMALL_BORDER; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.util.Hashtable; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; /** * Manages open windows in the application in a tree style view. */ public final class TreeFrameManager implements FrameManager, TreeSelectionListener, MouseListener, ActionListener, MouseMotionListener, MouseWheelListener, AdjustmentListener { /** * display tree. */ private final transient JTree tree; /** * root node. */ private final transient DefaultMutableTreeNode root; /** * data model. */ private final transient TreeViewModel model; /** * node storage, used for adding and deleting nodes correctly. */ private final transient Map<FrameContainer, DefaultMutableTreeNode> nodes; /** * stores colour associated with a node, cheap hack till i rewrite the model. */ private final transient Map<FrameContainer, Color> nodeColours; /** * stores background colour associated with a node, * cheap hack till i rewrite the model. */ private transient DefaultMutableTreeNode rolloverNode; /** * popup menu for menu items on nodes. */ private final transient JPopupMenu popup; /** * close menu item used in popup menus. */ private final transient JMenuItem closeMenuItem; /** * The object that is currently selected. */ private FrameContainer selected; /** Parent JComponent. */ private JComponent parent; /** *node under right click operation. */ private transient DefaultMutableTreeNode popupNode; /** * creates a new instance of the TreeFrameManager. */ public TreeFrameManager() { final TreeViewTreeCellRenderer renderer = new TreeViewTreeCellRenderer(this); nodes = new Hashtable<FrameContainer, DefaultMutableTreeNode>(); nodeColours = new Hashtable<FrameContainer, Color>(); popup = new JPopupMenu(); closeMenuItem = new JMenuItem("Close window"); root = new DefaultMutableTreeNode("DMDirc"); model = new TreeViewModel(root); tree = new JTree(model); closeMenuItem.setActionCommand("Close"); popup.add(closeMenuItem); popup.setOpaque(true); popup.setLightWeightPopupEnabled(true); tree.putClientProperty("JTree.lineStyle", "Angled"); tree.setUI(new javax.swing.plaf.metal.MetalTreeUI()); tree.getInputMap().remove(KeyStroke.getKeyStroke("F2")); tree.getSelectionModel(). setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.setCellRenderer(renderer); tree.setRootVisible(false); tree.setRowHeight(0); tree.setShowsRootHandles(false); tree.setOpaque(true); tree.setBorder(BorderFactory.createEmptyBorder(SMALL_BORDER, SMALL_BORDER, SMALL_BORDER, SMALL_BORDER)); tree.setVisible(true); closeMenuItem.addActionListener(this); tree.addTreeSelectionListener(this); tree.addMouseListener(this); tree.addMouseMotionListener(this); tree.addMouseWheelListener(this); } /** {@inheritDoc} */ public boolean canPositionVertically() { return true; } /** {@inheritDoc} */ public boolean canPositionHorizontally() { return false; } /** {@inheritDoc} */ public void setSelected(final FrameContainer source) { selected = source; SwingUtilities.invokeLater(new Runnable() { public void run() { tree.repaint(); } }); } /** * Retrieves the currently selected object. * @return The object that is currently selected. */ public FrameContainer getSelected() { return selected; } /** * Retrieves the currently selected node. * @return The node that is currently selected. */ public DefaultMutableTreeNode getSelectedNode() { return nodes.get(selected); } /** {@inheritDoc} */ public void showNotification(final FrameContainer source, final Color colour) { if (nodeColours != null) { nodeColours.put(source, colour); SwingUtilities.invokeLater(new Runnable() { public void run() { tree.repaint(); } }); } } /** * Sets the rollover node and repaints the tree. * @param node rollover node. */ public void showRollover(final DefaultMutableTreeNode node) { rolloverNode = node; SwingUtilities.invokeLater(new Runnable() { public void run() { tree.repaint(); } }); } /** * retrives the rollover node. * @return rollover node. */ public DefaultMutableTreeNode getRollover() { return rolloverNode; } /** {@inheritDoc} */ public void clearNotification(final FrameContainer source) { if (nodeColours != null && nodeColours.containsKey(source)) { nodeColours.remove(source); } } /** * retrieves the colour of a specific node. * @param source node to check colour of. * @return colour of the node. */ public Color getNodeColour(final FrameContainer source) { if (nodeColours != null && nodeColours.containsKey(source)) { return nodeColours.get(source); } return null; } /** {@inheritDoc} */ public void setParent(final JComponent parent) { final JScrollPane scrollPane = new JScrollPane(tree); scrollPane.setAutoscrolls(true); scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.getHorizontalScrollBar().addAdjustmentListener(this); parent.setLayout(new BorderLayout()); parent.add(scrollPane); tree.setBackground(Config.getOptionColor("treeview", "backgroundcolour", Config.getOptionColor("ui", "backgroundcolour", Color.WHITE))); tree.setForeground(Config.getOptionColor("treeview", "foregroundcolour", Config.getOptionColor("ui", "foregroundcolour", Color.BLACK))); this.parent = parent; } /** {@inheritDoc} */ public void addServer(final Server server) { final DefaultMutableTreeNode node = new DefaultMutableTreeNode(); nodes.put(server, node); node.setUserObject(server); model.insertNodeInto(node, root); if (root.getChildCount() == 1) { selected = server; } tree.expandPath(new TreePath(node.getPath()).getParentPath()); final Rectangle view = tree.getRowBounds(tree.getRowForPath(new TreePath(node.getPath()))); tree.scrollRectToVisible(new Rectangle(0, (int) view.getY(), 0, 0)); } /** {@inheritDoc} */ public void delServer(final Server server) { if (nodes.get(server) != null) { model.removeNodeFromParent(nodes.get(server)); } } /** {@inheritDoc} */ public void addChannel(final Server server, final Channel channel) { final DefaultMutableTreeNode node = new DefaultMutableTreeNode(); nodes.put(channel, node); node.setUserObject(channel); model.insertNodeInto(node, nodes.get(server)); tree.expandPath(new TreePath(node.getPath()).getParentPath()); final Rectangle view = tree.getRowBounds(tree.getRowForPath(new TreePath(node.getPath()))); tree.scrollRectToVisible(new Rectangle(0, (int) view.getY(), 0, 0)); } /** {@inheritDoc} */ public void delChannel(final Server server, final Channel channel) { if (nodes.get(channel) != null) { model.removeNodeFromParent(nodes.get(channel)); } } /** {@inheritDoc} */ public void addQuery(final Server server, final Query query) { final DefaultMutableTreeNode node = new DefaultMutableTreeNode(); nodes.put(query, node); node.setUserObject(query); model.insertNodeInto(node, nodes.get(server)); tree.expandPath(new TreePath(node.getPath()).getParentPath()); final Rectangle view = tree.getRowBounds(tree.getRowForPath(new TreePath(node.getPath()))); tree.scrollRectToVisible(new Rectangle(0, (int) view.getY(), 0, 0)); } /** {@inheritDoc} */ public void delQuery(final Server server, final Query query) { if (nodes.get(query) != null) { model.removeNodeFromParent(nodes.get(query)); } } /** {@inheritDoc} */ public void addCustom(final Server server, final FrameContainer window) { final DefaultMutableTreeNode node = new DefaultMutableTreeNode(); nodes.put(window, node); node.setUserObject(window); model.insertNodeInto(node, nodes.get(server)); tree.expandPath(new TreePath(node.getPath()).getParentPath()); final Rectangle view = tree.getRowBounds(tree.getRowForPath(new TreePath(node.getPath()))); tree.scrollRectToVisible(new Rectangle(0, (int) view.getY(), 0, 0)); } /** {@inheritDoc} */ public void delCustom(final Server server, final FrameContainer window) { if (nodes.get(window) != null) { model.removeNodeFromParent(nodes.get(window)); } } /** * Returns the maximum size a node can be without causing scrolling. * * @return Maximum node width */ public int getNodeWidth() { if (parent == null) { return 0; } else { return parent.getWidth() - 25; } } /** * valled whenever the value of the selection changes. * @param event selection event. */ public void valueChanged(final TreeSelectionEvent event) { final DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (node == null) { return; } final Object nodeInfo = node.getUserObject(); if (nodeInfo instanceof FrameContainer) { ((FrameContainer) nodeInfo).activateFrame(); } else { Logger.error(ErrorLevel.WARNING, "Unknown node type."); } } /** {@inheritDoc} */ public void adjustmentValueChanged(final AdjustmentEvent e) { //HACK Disregard all scrolling events ((JScrollBar) e.getSource()).setValue(0); } /** * Invoked when the mouse button has been clicked (pressed and released) * on a component. * @param event mouse event. */ public void mouseClicked(final MouseEvent event) { processMouseEvent(event); } /** * Invoked when a mouse button has been pressed on a component. * @param event mouse event. */ public void mousePressed(final MouseEvent event) { processMouseEvent(event); } /** * Invoked when a mouse button has been released on a component. * @param event mouse event. */ public void mouseReleased(final MouseEvent event) { processMouseEvent(event); } /** * Invoked when the mouse enters a component. * @param event mouse event. */ public void mouseEntered(final MouseEvent event) { //Do nothing } /** * Invoked when the mouse exits a component. * @param event mouse event. */ public void mouseExited(final MouseEvent event) { //Do nothing } /** * Processes every mouse button event to check for a popup trigger. * @param event mouse event */ public void processMouseEvent(final MouseEvent event) { if (event.isPopupTrigger()) { final JTree source = (JTree) event.getSource(); final TreePath path = tree.getPathForLocation(event.getX(), event.getY()); if (path != null) { popupNode = (DefaultMutableTreeNode) path.getLastPathComponent(); popup.show(source, event.getX(), event.getY()); } } } /** * Invoked when an action occurs. * @param event action event. */ public void actionPerformed(final ActionEvent event) { if (event.getSource() == closeMenuItem && popupNode != null) { ((FrameContainer) popupNode.getUserObject()).close(); } } /** * Invoked when a mouse button is pressed on a component and then dragged. * * @param event mouse event. */ public void mouseDragged(final MouseEvent event) { final DefaultMutableTreeNode node = getNodeForLocation(event.getX(), event.getY()); this.showRollover(node); if (node != null) { ((FrameContainer) node.getUserObject()).activateFrame(); } } /** * Invoked when the mouse cursor has been moved onto a component but no * buttons have been pushed. * * @param event mouse event. */ public void mouseMoved(final MouseEvent event) { final DefaultMutableTreeNode node = getNodeForLocation(event.getX(), event.getY()); this.showRollover(node); } /** * Returns the node for the specified location, returning null if rollover * is disabled or there is no node at the specified location. * * @param x x coordiantes * @param y y coordiantes * * @return node or null */ private DefaultMutableTreeNode getNodeForLocation(final int x, final int y) { DefaultMutableTreeNode node = null; if (Config.getOptionBool("ui", "treeviewRolloverEnabled")) { final TreePath selectedPath = tree.getPathForLocation(x, y); if (selectedPath == null) { this.showRollover(null); } else { node = (DefaultMutableTreeNode) selectedPath.getLastPathComponent(); this.showRollover((DefaultMutableTreeNode) selectedPath.getLastPathComponent()); } } return node; } /** * Invoked when the mouse wheel is rotated. * @param event mouse event. */ public void mouseWheelMoved(final MouseWheelEvent event) { //get the number of notches (used only for direction) if (event.getWheelRotation() < 0) { changeFocus(true); } else { changeFocus(false); } } /** * Activates the node above or below the active node in the tree. * * @param direction true = up, false = down. */ private void changeFocus(final boolean direction) { DefaultMutableTreeNode thisNode, nextNode; if (getSelectedNode() == null) { //no selected node, get the root node thisNode = root; //are there any servers to select? if (thisNode.getChildCount() > 0) { thisNode = (DefaultMutableTreeNode) thisNode.getChildAt(0); } else { //then wait till there are return; } } else { //use the selected node to start from thisNode = getSelectedNode(); } //are we going up or down? if (direction) { //up nextNode = changeFocusUp(thisNode); } else { //down nextNode = changeFocusDown(thisNode); } //activate the nodes frame //((FrameContainer) nextNode.getUserObject()).activateFrame(); tree.setSelectionPath(new TreePath(nextNode)); } /** * Changes the tree focus up. * * @param node Start node * * @return next node */ private DefaultMutableTreeNode changeFocusUp(final DefaultMutableTreeNode node) { DefaultMutableTreeNode thisNode, nextNode; thisNode = node; if (thisNode.getUserObject() instanceof Server) { if (thisNode.getParent().getIndex(thisNode) == 0) { //first server - last child of parent's last child nextNode = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) thisNode.getParent()).getLastChild(); if (nextNode.getChildCount() > 0) { nextNode = (DefaultMutableTreeNode) nextNode.getLastChild(); } } else { //other servers - last child of previous sibling nextNode = (DefaultMutableTreeNode) (thisNode.getPreviousSibling()).getLastChild(); } } else { if (thisNode.getParent().getIndex(thisNode) == 0) { //first frame - parent nextNode = (DefaultMutableTreeNode) thisNode.getParent(); } else { //other frame - previous sibling nextNode = thisNode.getPreviousSibling(); } } return nextNode; } /** * Changes the tree focus down. * * @param node Start node * * @return next node */ private DefaultMutableTreeNode changeFocusDown(final DefaultMutableTreeNode node) { DefaultMutableTreeNode thisNode, nextNode; thisNode = node; if (thisNode.getUserObject() instanceof Server) { if (thisNode.getChildCount() > 0) { //server has frames, use first nextNode = (DefaultMutableTreeNode) thisNode.getFirstChild(); } else { //server has no frames, use next server nextNode = ((DefaultMutableTreeNode) thisNode.getParent()).getNextSibling(); //no next server, use first if (nextNode == null) { nextNode = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) thisNode.getParent()).getFirstChild(); } } } else { if (thisNode.getParent().getIndex(thisNode) == thisNode.getParent().getChildCount() - 1) { //last frame - get the parents next sibling nextNode = ((DefaultMutableTreeNode) thisNode.getParent()).getNextSibling(); //parent doesnt have a next sibling, get the first child of the grandparent if (nextNode == null) { nextNode = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) thisNode.getParent().getParent()).getFirstChild(); } } else { //other frames - get the next sibling nextNode = thisNode.getNextSibling(); } } return nextNode; } }
src/com/dmdirc/ui/framemanager/tree/TreeFrameManager.java
/* * Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack, Gregory Holmes * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc.ui.framemanager.tree; import com.dmdirc.Channel; import com.dmdirc.Config; import com.dmdirc.FrameContainer; import com.dmdirc.Query; import com.dmdirc.Server; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.ui.framemanager.FrameManager; import static com.dmdirc.ui.UIUtilities.SMALL_BORDER; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.util.Hashtable; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; /** * Manages open windows in the application in a tree style view. */ public final class TreeFrameManager implements FrameManager, TreeSelectionListener, MouseListener, ActionListener, MouseMotionListener, MouseWheelListener, AdjustmentListener { /** * display tree. */ private final transient JTree tree; /** * root node. */ private final transient DefaultMutableTreeNode root; /** * data model. */ private final transient TreeViewModel model; /** * node storage, used for adding and deleting nodes correctly. */ private final transient Map<FrameContainer, DefaultMutableTreeNode> nodes; /** * stores colour associated with a node, cheap hack till i rewrite the model. */ private final transient Map<FrameContainer, Color> nodeColours; /** * stores background colour associated with a node, * cheap hack till i rewrite the model. */ private transient DefaultMutableTreeNode rolloverNode; /** * popup menu for menu items on nodes. */ private final transient JPopupMenu popup; /** * close menu item used in popup menus. */ private final transient JMenuItem closeMenuItem; /** * The object that is currently selected. */ private FrameContainer selected; /** Parent JComponent. */ private JComponent parent; /** *node under right click operation. */ private transient DefaultMutableTreeNode popupNode; /** * creates a new instance of the TreeFrameManager. */ public TreeFrameManager() { final TreeViewTreeCellRenderer renderer = new TreeViewTreeCellRenderer(this); nodes = new Hashtable<FrameContainer, DefaultMutableTreeNode>(); nodeColours = new Hashtable<FrameContainer, Color>(); popup = new JPopupMenu(); closeMenuItem = new JMenuItem("Close window"); root = new DefaultMutableTreeNode("DMDirc"); model = new TreeViewModel(root); tree = new JTree(model); closeMenuItem.setActionCommand("Close"); popup.add(closeMenuItem); popup.setOpaque(true); popup.setLightWeightPopupEnabled(true); tree.putClientProperty("JTree.lineStyle", "Angled"); tree.setUI(new javax.swing.plaf.metal.MetalTreeUI()); tree.getSelectionModel(). setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.setCellRenderer(renderer); tree.setRootVisible(false); tree.setRowHeight(0); tree.setShowsRootHandles(false); tree.setOpaque(true); tree.setBorder(BorderFactory.createEmptyBorder(SMALL_BORDER, SMALL_BORDER, SMALL_BORDER, SMALL_BORDER)); tree.setVisible(true); closeMenuItem.addActionListener(this); tree.addTreeSelectionListener(this); tree.addMouseListener(this); tree.addMouseMotionListener(this); tree.addMouseWheelListener(this); } /** {@inheritDoc} */ public boolean canPositionVertically() { return true; } /** {@inheritDoc} */ public boolean canPositionHorizontally() { return false; } /** {@inheritDoc} */ public void setSelected(final FrameContainer source) { selected = source; SwingUtilities.invokeLater(new Runnable() { public void run() { tree.repaint(); } }); } /** * Retrieves the currently selected object. * @return The object that is currently selected. */ public FrameContainer getSelected() { return selected; } /** * Retrieves the currently selected node. * @return The node that is currently selected. */ public DefaultMutableTreeNode getSelectedNode() { return nodes.get(selected); } /** {@inheritDoc} */ public void showNotification(final FrameContainer source, final Color colour) { if (nodeColours != null) { nodeColours.put(source, colour); SwingUtilities.invokeLater(new Runnable() { public void run() { tree.repaint(); } }); } } /** * Sets the rollover node and repaints the tree. * @param node rollover node. */ public void showRollover(final DefaultMutableTreeNode node) { rolloverNode = node; SwingUtilities.invokeLater(new Runnable() { public void run() { tree.repaint(); } }); } /** * retrives the rollover node. * @return rollover node. */ public DefaultMutableTreeNode getRollover() { return rolloverNode; } /** {@inheritDoc} */ public void clearNotification(final FrameContainer source) { if (nodeColours != null && nodeColours.containsKey(source)) { nodeColours.remove(source); } } /** * retrieves the colour of a specific node. * @param source node to check colour of. * @return colour of the node. */ public Color getNodeColour(final FrameContainer source) { if (nodeColours != null && nodeColours.containsKey(source)) { return nodeColours.get(source); } return null; } /** {@inheritDoc} */ public void setParent(final JComponent parent) { final JScrollPane scrollPane = new JScrollPane(tree); scrollPane.setAutoscrolls(true); scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.getHorizontalScrollBar().addAdjustmentListener(this); parent.setLayout(new BorderLayout()); parent.add(scrollPane); tree.setBackground(Config.getOptionColor("treeview", "backgroundcolour", Config.getOptionColor("ui", "backgroundcolour", Color.WHITE))); tree.setForeground(Config.getOptionColor("treeview", "foregroundcolour", Config.getOptionColor("ui", "foregroundcolour", Color.BLACK))); this.parent = parent; } /** {@inheritDoc} */ public void addServer(final Server server) { final DefaultMutableTreeNode node = new DefaultMutableTreeNode(); nodes.put(server, node); node.setUserObject(server); model.insertNodeInto(node, root); if (root.getChildCount() == 1) { selected = server; } tree.expandPath(new TreePath(node.getPath()).getParentPath()); final Rectangle view = tree.getRowBounds(tree.getRowForPath(new TreePath(node.getPath()))); tree.scrollRectToVisible(new Rectangle(0, (int) view.getY(), 0, 0)); } /** {@inheritDoc} */ public void delServer(final Server server) { if (nodes.get(server) != null) { model.removeNodeFromParent(nodes.get(server)); } } /** {@inheritDoc} */ public void addChannel(final Server server, final Channel channel) { final DefaultMutableTreeNode node = new DefaultMutableTreeNode(); nodes.put(channel, node); node.setUserObject(channel); model.insertNodeInto(node, nodes.get(server)); tree.expandPath(new TreePath(node.getPath()).getParentPath()); final Rectangle view = tree.getRowBounds(tree.getRowForPath(new TreePath(node.getPath()))); tree.scrollRectToVisible(new Rectangle(0, (int) view.getY(), 0, 0)); } /** {@inheritDoc} */ public void delChannel(final Server server, final Channel channel) { if (nodes.get(channel) != null) { model.removeNodeFromParent(nodes.get(channel)); } } /** {@inheritDoc} */ public void addQuery(final Server server, final Query query) { final DefaultMutableTreeNode node = new DefaultMutableTreeNode(); nodes.put(query, node); node.setUserObject(query); model.insertNodeInto(node, nodes.get(server)); tree.expandPath(new TreePath(node.getPath()).getParentPath()); final Rectangle view = tree.getRowBounds(tree.getRowForPath(new TreePath(node.getPath()))); tree.scrollRectToVisible(new Rectangle(0, (int) view.getY(), 0, 0)); } /** {@inheritDoc} */ public void delQuery(final Server server, final Query query) { if (nodes.get(query) != null) { model.removeNodeFromParent(nodes.get(query)); } } /** {@inheritDoc} */ public void addCustom(final Server server, final FrameContainer window) { final DefaultMutableTreeNode node = new DefaultMutableTreeNode(); nodes.put(window, node); node.setUserObject(window); model.insertNodeInto(node, nodes.get(server)); tree.expandPath(new TreePath(node.getPath()).getParentPath()); final Rectangle view = tree.getRowBounds(tree.getRowForPath(new TreePath(node.getPath()))); tree.scrollRectToVisible(new Rectangle(0, (int) view.getY(), 0, 0)); } /** {@inheritDoc} */ public void delCustom(final Server server, final FrameContainer window) { if (nodes.get(window) != null) { model.removeNodeFromParent(nodes.get(window)); } } /** * Returns the maximum size a node can be without causing scrolling. * * @return Maximum node width */ public int getNodeWidth() { if (parent == null) { return 0; } else { return parent.getWidth() - 25; } } /** * valled whenever the value of the selection changes. * @param event selection event. */ public void valueChanged(final TreeSelectionEvent event) { final DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (node == null) { return; } final Object nodeInfo = node.getUserObject(); if (nodeInfo instanceof FrameContainer) { ((FrameContainer) nodeInfo).activateFrame(); } else { Logger.error(ErrorLevel.WARNING, "Unknown node type."); } } /** {@inheritDoc} */ public void adjustmentValueChanged(final AdjustmentEvent e) { //HACK Disregard all scrolling events ((JScrollBar) e.getSource()).setValue(0); } /** * Invoked when the mouse button has been clicked (pressed and released) * on a component. * @param event mouse event. */ public void mouseClicked(final MouseEvent event) { processMouseEvent(event); } /** * Invoked when a mouse button has been pressed on a component. * @param event mouse event. */ public void mousePressed(final MouseEvent event) { processMouseEvent(event); } /** * Invoked when a mouse button has been released on a component. * @param event mouse event. */ public void mouseReleased(final MouseEvent event) { processMouseEvent(event); } /** * Invoked when the mouse enters a component. * @param event mouse event. */ public void mouseEntered(final MouseEvent event) { //Do nothing } /** * Invoked when the mouse exits a component. * @param event mouse event. */ public void mouseExited(final MouseEvent event) { //Do nothing } /** * Processes every mouse button event to check for a popup trigger. * @param event mouse event */ public void processMouseEvent(final MouseEvent event) { if (event.isPopupTrigger()) { final JTree source = (JTree) event.getSource(); final TreePath path = tree.getPathForLocation(event.getX(), event.getY()); if (path != null) { popupNode = (DefaultMutableTreeNode) path.getLastPathComponent(); popup.show(source, event.getX(), event.getY()); } } } /** * Invoked when an action occurs. * @param event action event. */ public void actionPerformed(final ActionEvent event) { if (event.getSource() == closeMenuItem && popupNode != null) { ((FrameContainer) popupNode.getUserObject()).close(); } } /** * Invoked when a mouse button is pressed on a component and then dragged. * * @param event mouse event. */ public void mouseDragged(final MouseEvent event) { final DefaultMutableTreeNode node = getNodeForLocation(event.getX(), event.getY()); this.showRollover(node); if (node != null) { ((FrameContainer) node.getUserObject()).activateFrame(); } } /** * Invoked when the mouse cursor has been moved onto a component but no * buttons have been pushed. * * @param event mouse event. */ public void mouseMoved(final MouseEvent event) { final DefaultMutableTreeNode node = getNodeForLocation(event.getX(), event.getY()); this.showRollover(node); } /** * Returns the node for the specified location, returning null if rollover * is disabled or there is no node at the specified location. * * @param x x coordiantes * @param y y coordiantes * * @return node or null */ private DefaultMutableTreeNode getNodeForLocation(final int x, final int y) { DefaultMutableTreeNode node = null; if (Config.getOptionBool("ui", "treeviewRolloverEnabled")) { final TreePath selectedPath = tree.getPathForLocation(x, y); if (selectedPath == null) { this.showRollover(null); } else { node = (DefaultMutableTreeNode) selectedPath.getLastPathComponent(); this.showRollover((DefaultMutableTreeNode) selectedPath.getLastPathComponent()); } } return node; } /** * Invoked when the mouse wheel is rotated. * @param event mouse event. */ public void mouseWheelMoved(final MouseWheelEvent event) { //get the number of notches (used only for direction) if (event.getWheelRotation() < 0) { changeFocus(true); } else { changeFocus(false); } } /** * Activates the node above or below the active node in the tree. * * @param direction true = up, false = down. */ private void changeFocus(final boolean direction) { DefaultMutableTreeNode thisNode, nextNode; if (getSelectedNode() == null) { //no selected node, get the root node thisNode = root; //are there any servers to select? if (thisNode.getChildCount() > 0) { thisNode = (DefaultMutableTreeNode) thisNode.getChildAt(0); } else { //then wait till there are return; } } else { //use the selected node to start from thisNode = getSelectedNode(); } //are we going up or down? if (direction) { //up nextNode = changeFocusUp(thisNode); } else { //down nextNode = changeFocusDown(thisNode); } //activate the nodes frame //((FrameContainer) nextNode.getUserObject()).activateFrame(); tree.setSelectionPath(new TreePath(nextNode)); } /** * Changes the tree focus up. * * @param node Start node * * @return next node */ private DefaultMutableTreeNode changeFocusUp(final DefaultMutableTreeNode node) { DefaultMutableTreeNode thisNode, nextNode; thisNode = node; if (thisNode.getUserObject() instanceof Server) { if (thisNode.getParent().getIndex(thisNode) == 0) { //first server - last child of parent's last child nextNode = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) thisNode.getParent()).getLastChild(); if (nextNode.getChildCount() > 0) { nextNode = (DefaultMutableTreeNode) nextNode.getLastChild(); } } else { //other servers - last child of previous sibling nextNode = (DefaultMutableTreeNode) (thisNode.getPreviousSibling()).getLastChild(); } } else { if (thisNode.getParent().getIndex(thisNode) == 0) { //first frame - parent nextNode = (DefaultMutableTreeNode) thisNode.getParent(); } else { //other frame - previous sibling nextNode = thisNode.getPreviousSibling(); } } return nextNode; } /** * Changes the tree focus down. * * @param node Start node * * @return next node */ private DefaultMutableTreeNode changeFocusDown(final DefaultMutableTreeNode node) { DefaultMutableTreeNode thisNode, nextNode; thisNode = node; if (thisNode.getUserObject() instanceof Server) { if (thisNode.getChildCount() > 0) { //server has frames, use first nextNode = (DefaultMutableTreeNode) thisNode.getFirstChild(); } else { //server has no frames, use next server nextNode = ((DefaultMutableTreeNode) thisNode.getParent()).getNextSibling(); //no next server, use first if (nextNode == null) { nextNode = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) thisNode.getParent()).getFirstChild(); } } } else { if (thisNode.getParent().getIndex(thisNode) == thisNode.getParent().getChildCount() - 1) { //last frame - get the parents next sibling nextNode = ((DefaultMutableTreeNode) thisNode.getParent()).getNextSibling(); //parent doesnt have a next sibling, get the first child of the grandparent if (nextNode == null) { nextNode = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) thisNode.getParent().getParent()).getFirstChild(); } } else { //other frames - get the next sibling nextNode = thisNode.getNextSibling(); } } return nextNode; } }
Removed random edit action on f2 which was causing scrolling on the treeframe git-svn-id: 50f83ef66c13f323b544ac924010c921a9f4a0f7@1626 00569f92-eb28-0410-84fd-f71c24880f43
src/com/dmdirc/ui/framemanager/tree/TreeFrameManager.java
Removed random edit action on f2 which was causing scrolling on the treeframe
<ide><path>rc/com/dmdirc/ui/framemanager/tree/TreeFrameManager.java <ide> import javax.swing.JScrollBar; <ide> import javax.swing.JScrollPane; <ide> import javax.swing.JTree; <add>import javax.swing.KeyStroke; <ide> import javax.swing.SwingUtilities; <ide> import javax.swing.event.TreeSelectionEvent; <ide> import javax.swing.event.TreeSelectionListener; <ide> <ide> tree.putClientProperty("JTree.lineStyle", "Angled"); <ide> tree.setUI(new javax.swing.plaf.metal.MetalTreeUI()); <add> tree.getInputMap().remove(KeyStroke.getKeyStroke("F2")); <ide> <ide> tree.getSelectionModel(). <ide> setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
Java
apache-2.0
a2e69eaada56450826479511904e694f88f87188
0
b3stia/MaterialTabs,deng1491/MaterialTabs,pittsburgh-studio/MaterialTabs,suzukaze/MaterialTabs,yoslabs/MaterialTabs,huy510cnt/MaterialTabs,dhootha/MaterialTabs,pkexcellent/MaterialTabs,bensonX/MaterialTabs-1,StormGens/MaterialTabs,neokree/MaterialTabs,huy510cnt/MaterialTabs-huy510cnt,kaiaras/MaterialTabs,brooksgod/MaterialTabs,java02014/MaterialTabs,tomoyuki28jp/MaterialTabs,Sshah88/MaterialTabs,willf80/MaterialTabs,Gangadhar82/MaterialTabs
package it.neokree.materialtabs; import java.util.LinkedList; import java.util.List; import java.util.Objects; import it.neokree.materialtabs.R; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.v7.widget.LinearLayoutCompat; import android.util.AttributeSet; import android.view.View; import android.widget.HorizontalScrollView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; /** * A Toolbar that contains multiple tabs * @author neokree * */ @SuppressLint("InflateParams") public class MaterialTabHost extends RelativeLayout implements View.OnClickListener { private int primaryColor; private int accentColor; private int textColor; private int iconColor; private List<MaterialTab> tabs; private boolean hasIcons; private boolean isTablet; private float density; private boolean scrollable; private HorizontalScrollView scrollView; private LinearLayout layout; private ImageButton left; private ImageButton right; private static int tabSelected; public MaterialTabHost(Context context) { this(context, null); } public MaterialTabHost(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MaterialTabHost(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); scrollView = new HorizontalScrollView(context); scrollView.setOverScrollMode(HorizontalScrollView.OVER_SCROLL_NEVER); scrollView.setHorizontalScrollBarEnabled(false); layout = new LinearLayout(context); scrollView.addView(layout); // get attributes if(attrs != null) { TypedArray a = context.getTheme().obtainStyledAttributes(attrs,R.styleable.MaterialTabHost, 0, 0); try { // custom attributes hasIcons = a.getBoolean(R.styleable.MaterialTabHost_hasIcons, false); primaryColor = a.getColor(R.styleable.MaterialTabHost_materialTabsPrimaryColor, Color.parseColor("#009688")); accentColor = a.getColor(R.styleable.MaterialTabHost_accentColor,Color.parseColor("#00b0ff")); iconColor = a.getColor(R.styleable.MaterialTabHost_iconColor,Color.WHITE); textColor = a.getColor(R.styleable.MaterialTabHost_textColor,Color.WHITE); } finally { a.recycle(); } } else { hasIcons = false; } this.isInEditMode(); scrollable = false; isTablet = this.getResources().getBoolean(R.bool.isTablet); density = this.getResources().getDisplayMetrics().density; tabSelected = 0; // initialize tabs list tabs = new LinkedList<MaterialTab>(); // set background color super.setBackgroundColor(primaryColor); } public void setPrimaryColor(int color) { this.primaryColor = color; this.setBackgroundColor(primaryColor); for(MaterialTab tab : tabs) { tab.setPrimaryColor(color); } } public void setAccentColor(int color) { this.accentColor = color; for(MaterialTab tab : tabs) { tab.setAccentColor(color); } } public void setTextColor(int color) { this.textColor = color; for(MaterialTab tab : tabs) { tab.setTextColor(color); } } public void setIconColor(int color) { this.iconColor = color; for(MaterialTab tab : tabs) { tab.setIconColor(color); } } public void addTab(MaterialTab tab) { // add properties to tab tab.setAccentColor(accentColor); tab.setPrimaryColor(primaryColor); tab.setTextColor(textColor); tab.setIconColor(iconColor); tab.setPosition(tabs.size()); // insert new tab in list tabs.add(tab); if(tabs.size() == 4 && !hasIcons) { // switch tabs to scrollable before its draw scrollable = true; } if(tabs.size() == 6 && hasIcons) { scrollable = true; } } public MaterialTab newTab() { return new MaterialTab(this.getContext(),hasIcons); } public void setSelectedNavigationItem(int position) { if(position < 0 || position > tabs.size()) { throw new RuntimeException("Index overflow"); } else { // tab at position will select, other will deselect for(int i = 0; i < tabs.size(); i++) { MaterialTab tab = tabs.get(i); if(i == position) { tab.activateTab(); } else { tabs.get(i).disableTab(); } } // move the tab if it is slidable if(scrollable) { scrollTo(position); } tabSelected = position; } } private void scrollTo(int position) { int totalWidth = 0;//(int) ( 60 * density); for (int i = 0; i < position; i++) { int width = tabs.get(i).getView().getWidth(); if(width == 0) { if(!isTablet) width = (int) (tabs.get(i).getTabMinWidth() + (24 * density)); else width = (int) (tabs.get(i).getTabMinWidth() + (48 * density)); } totalWidth += width; } scrollView.smoothScrollTo(totalWidth, 0); } @Override public void removeAllViews() { for(int i = 0; i<tabs.size();i++) { tabs.remove(i); } layout.removeAllViews(); super.removeAllViews(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if(this.getWidth() != 0 && tabs.size() != 0) notifyDataSetChanged(); } public void notifyDataSetChanged() { super.removeAllViews(); layout.removeAllViews(); if (!scrollable) { // not scrollable tabs int tabWidth = this.getWidth() / tabs.size(); // set params for resizing tabs width LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(tabWidth, HorizontalScrollView.LayoutParams.MATCH_PARENT); for (MaterialTab t : tabs) { layout.addView(t.getView(), params); } } else { //scrollable tabs if(!isTablet) { for (int i = 0; i < tabs.size(); i++) { LinearLayout.LayoutParams params; MaterialTab tab = tabs.get(i); int tabWidth = (int) (tab.getTabMinWidth() + (24 * density)); // 12dp + text/icon width + 12dp if (i == 0) { // first tab View view = new View(layout.getContext()); view.setMinimumWidth((int) (60 * density)); layout.addView(view); } params = new LinearLayout.LayoutParams(tabWidth, HorizontalScrollView.LayoutParams.MATCH_PARENT); layout.addView(tab.getView(), params); if (i == tabs.size() - 1) { // last tab View view = new View(layout.getContext()); view.setMinimumWidth((int) (60 * density)); layout.addView(view); } } } else { // is a tablet for (int i = 0; i < tabs.size(); i++) { LinearLayout.LayoutParams params; MaterialTab tab = tabs.get(i); int tabWidth = (int) (tab.getTabMinWidth() + (48 * density)); // 24dp + text/icon width + 24dp params = new LinearLayout.LayoutParams(tabWidth, HorizontalScrollView.LayoutParams.MATCH_PARENT); layout.addView(tab.getView(), params); } } } if (isTablet && scrollable) { // if device is a tablet and have scrollable tabs add right and left arrows Resources res = getResources(); left = new ImageButton(this.getContext()); left.setId(R.id.left); left.setImageDrawable(res.getDrawable(R.drawable.left_arrow)); left.setBackgroundColor(Color.TRANSPARENT); left.setOnClickListener(this); // set 56 dp width and 48 dp height RelativeLayout.LayoutParams paramsLeft = new LayoutParams((int)( 56 * density),(int) (48 * density)); paramsLeft.addRule(RelativeLayout.ALIGN_PARENT_LEFT); paramsLeft.addRule(RelativeLayout.ALIGN_PARENT_TOP); paramsLeft.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); this.addView(left,paramsLeft); right = new ImageButton(this.getContext()); right.setId(R.id.right); right.setImageDrawable(res.getDrawable(R.drawable.right_arrow)); right.setBackgroundColor(Color.TRANSPARENT); right.setOnClickListener(this); RelativeLayout.LayoutParams paramsRight = new LayoutParams((int)( 56 * density),(int) (48 * density)); paramsRight.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); paramsRight.addRule(RelativeLayout.ALIGN_PARENT_TOP); paramsRight.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); this.addView(right,paramsRight); RelativeLayout.LayoutParams paramsScroll = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); paramsScroll.addRule(RelativeLayout.LEFT_OF, R.id.right); paramsScroll.addRule(RelativeLayout.RIGHT_OF,R.id.left); this.addView(scrollView,paramsScroll); } else { // if is not a tablet add only scrollable content RelativeLayout.LayoutParams paramsScroll = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); this.addView(scrollView,paramsScroll); } this.setSelectedNavigationItem(tabSelected); } public MaterialTab getCurrentTab() { for(MaterialTab tab : tabs) { if (tab.isSelected()) return tab; } return null; } @Override public void onClick(View v) { // on tablet left/right button clicked int currentPosition = this.getCurrentTab().getPosition(); if (v.getId() == R.id.right && currentPosition < tabs.size() -1) { currentPosition++; // set next tab selected this.setSelectedNavigationItem(currentPosition); // change fragment tabs.get(currentPosition).getTabListener().onTabSelected(tabs.get(currentPosition)); return; } if(v.getId() == R.id.left && currentPosition > 0) { currentPosition--; // set previous tab selected this.setSelectedNavigationItem(currentPosition); // change fragment tabs.get(currentPosition).getTabListener().onTabSelected(tabs.get(currentPosition)); return; } } }
MaterialTabsModule/src/main/java/it/neokree/materialtabs/MaterialTabHost.java
package it.neokree.materialtabs; import java.util.LinkedList; import java.util.List; import java.util.Objects; import it.neokree.materialtabs.R; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.v7.widget.LinearLayoutCompat; import android.util.AttributeSet; import android.view.View; import android.widget.HorizontalScrollView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; /** * A Toolbar that contains multiple tabs * @author neokree * */ @SuppressLint("InflateParams") public class MaterialTabHost extends RelativeLayout implements View.OnClickListener { private int primaryColor; private int accentColor; private int textColor; private int iconColor; private List<MaterialTab> tabs; private boolean hasIcons; private boolean isTablet; private float density; private boolean scrollable; private HorizontalScrollView scrollView; private LinearLayout layout; private ImageButton left; private ImageButton right; private static int tabSelected; public MaterialTabHost(Context context) { this(context, null); } public MaterialTabHost(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MaterialTabHost(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); scrollView = new HorizontalScrollView(context); scrollView.setOverScrollMode(HorizontalScrollView.OVER_SCROLL_NEVER); scrollView.setHorizontalScrollBarEnabled(false); layout = new LinearLayout(context); scrollView.addView(layout); // get attributes if(attrs != null) { TypedArray a = context.getTheme().obtainStyledAttributes(attrs,R.styleable.MaterialTabHost, 0, 0); try { // custom attributes hasIcons = a.getBoolean(R.styleable.MaterialTabHost_hasIcons, false); primaryColor = a.getColor(R.styleable.MaterialTabHost_primaryColor, Color.parseColor("#009688")); accentColor = a.getColor(R.styleable.MaterialTabHost_accentColor,Color.parseColor("#00b0ff")); iconColor = a.getColor(R.styleable.MaterialTabHost_iconColor,Color.WHITE); textColor = a.getColor(R.styleable.MaterialTabHost_textColor,Color.WHITE); } finally { a.recycle(); } } else { hasIcons = false; } this.isInEditMode(); scrollable = false; isTablet = this.getResources().getBoolean(R.bool.isTablet); density = this.getResources().getDisplayMetrics().density; tabSelected = 0; // initialize tabs list tabs = new LinkedList<MaterialTab>(); // set background color super.setBackgroundColor(primaryColor); } public void setPrimaryColor(int color) { this.primaryColor = color; this.setBackgroundColor(primaryColor); for(MaterialTab tab : tabs) { tab.setPrimaryColor(color); } } public void setAccentColor(int color) { this.accentColor = color; for(MaterialTab tab : tabs) { tab.setAccentColor(color); } } public void setTextColor(int color) { this.textColor = color; for(MaterialTab tab : tabs) { tab.setTextColor(color); } } public void setIconColor(int color) { this.iconColor = color; for(MaterialTab tab : tabs) { tab.setIconColor(color); } } public void addTab(MaterialTab tab) { // add properties to tab tab.setAccentColor(accentColor); tab.setPrimaryColor(primaryColor); tab.setTextColor(textColor); tab.setIconColor(iconColor); tab.setPosition(tabs.size()); // insert new tab in list tabs.add(tab); if(tabs.size() == 4 && !hasIcons) { // switch tabs to scrollable before its draw scrollable = true; } if(tabs.size() == 6 && hasIcons) { scrollable = true; } } public MaterialTab newTab() { return new MaterialTab(this.getContext(),hasIcons); } public void setSelectedNavigationItem(int position) { if(position < 0 || position > tabs.size()) { throw new RuntimeException("Index overflow"); } else { // tab at position will select, other will deselect for(int i = 0; i < tabs.size(); i++) { MaterialTab tab = tabs.get(i); if(i == position) { tab.activateTab(); } else { tabs.get(i).disableTab(); } } // move the tab if it is slidable if(scrollable) { scrollTo(position); } tabSelected = position; } } private void scrollTo(int position) { int totalWidth = 0;//(int) ( 60 * density); for (int i = 0; i < position; i++) { int width = tabs.get(i).getView().getWidth(); if(width == 0) { if(!isTablet) width = (int) (tabs.get(i).getTabMinWidth() + (24 * density)); else width = (int) (tabs.get(i).getTabMinWidth() + (48 * density)); } totalWidth += width; } scrollView.smoothScrollTo(totalWidth, 0); } @Override public void removeAllViews() { for(int i = 0; i<tabs.size();i++) { tabs.remove(i); } layout.removeAllViews(); super.removeAllViews(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if(this.getWidth() != 0 && tabs.size() != 0) notifyDataSetChanged(); } public void notifyDataSetChanged() { super.removeAllViews(); layout.removeAllViews(); if (!scrollable) { // not scrollable tabs int tabWidth = this.getWidth() / tabs.size(); // set params for resizing tabs width LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(tabWidth, HorizontalScrollView.LayoutParams.MATCH_PARENT); for (MaterialTab t : tabs) { layout.addView(t.getView(), params); } } else { //scrollable tabs if(!isTablet) { for (int i = 0; i < tabs.size(); i++) { LinearLayout.LayoutParams params; MaterialTab tab = tabs.get(i); int tabWidth = (int) (tab.getTabMinWidth() + (24 * density)); // 12dp + text/icon width + 12dp if (i == 0) { // first tab View view = new View(layout.getContext()); view.setMinimumWidth((int) (60 * density)); layout.addView(view); } params = new LinearLayout.LayoutParams(tabWidth, HorizontalScrollView.LayoutParams.MATCH_PARENT); layout.addView(tab.getView(), params); if (i == tabs.size() - 1) { // last tab View view = new View(layout.getContext()); view.setMinimumWidth((int) (60 * density)); layout.addView(view); } } } else { // is a tablet for (int i = 0; i < tabs.size(); i++) { LinearLayout.LayoutParams params; MaterialTab tab = tabs.get(i); int tabWidth = (int) (tab.getTabMinWidth() + (48 * density)); // 24dp + text/icon width + 24dp params = new LinearLayout.LayoutParams(tabWidth, HorizontalScrollView.LayoutParams.MATCH_PARENT); layout.addView(tab.getView(), params); } } } if (isTablet && scrollable) { // if device is a tablet and have scrollable tabs add right and left arrows Resources res = getResources(); left = new ImageButton(this.getContext()); left.setId(R.id.left); left.setImageDrawable(res.getDrawable(R.drawable.left_arrow)); left.setBackgroundColor(Color.TRANSPARENT); left.setOnClickListener(this); // set 56 dp width and 48 dp height RelativeLayout.LayoutParams paramsLeft = new LayoutParams((int)( 56 * density),(int) (48 * density)); paramsLeft.addRule(RelativeLayout.ALIGN_PARENT_LEFT); paramsLeft.addRule(RelativeLayout.ALIGN_PARENT_TOP); paramsLeft.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); this.addView(left,paramsLeft); right = new ImageButton(this.getContext()); right.setId(R.id.right); right.setImageDrawable(res.getDrawable(R.drawable.right_arrow)); right.setBackgroundColor(Color.TRANSPARENT); right.setOnClickListener(this); RelativeLayout.LayoutParams paramsRight = new LayoutParams((int)( 56 * density),(int) (48 * density)); paramsRight.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); paramsRight.addRule(RelativeLayout.ALIGN_PARENT_TOP); paramsRight.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); this.addView(right,paramsRight); RelativeLayout.LayoutParams paramsScroll = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); paramsScroll.addRule(RelativeLayout.LEFT_OF, R.id.right); paramsScroll.addRule(RelativeLayout.RIGHT_OF,R.id.left); this.addView(scrollView,paramsScroll); } else { // if is not a tablet add only scrollable content RelativeLayout.LayoutParams paramsScroll = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); this.addView(scrollView,paramsScroll); } this.setSelectedNavigationItem(tabSelected); } public MaterialTab getCurrentTab() { for(MaterialTab tab : tabs) { if (tab.isSelected()) return tab; } return null; } @Override public void onClick(View v) { // on tablet left/right button clicked int currentPosition = this.getCurrentTab().getPosition(); if (v.getId() == R.id.right && currentPosition < tabs.size() -1) { currentPosition++; // set next tab selected this.setSelectedNavigationItem(currentPosition); // change fragment tabs.get(currentPosition).getTabListener().onTabSelected(tabs.get(currentPosition)); return; } if(v.getId() == R.id.left && currentPosition > 0) { currentPosition--; // set previous tab selected this.setSelectedNavigationItem(currentPosition); // change fragment tabs.get(currentPosition).getTabListener().onTabSelected(tabs.get(currentPosition)); return; } } }
Update MaterialTabHost.java
MaterialTabsModule/src/main/java/it/neokree/materialtabs/MaterialTabHost.java
Update MaterialTabHost.java
<ide><path>aterialTabsModule/src/main/java/it/neokree/materialtabs/MaterialTabHost.java <ide> // custom attributes <ide> hasIcons = a.getBoolean(R.styleable.MaterialTabHost_hasIcons, false); <ide> <del> primaryColor = a.getColor(R.styleable.MaterialTabHost_primaryColor, Color.parseColor("#009688")); <add> primaryColor = a.getColor(R.styleable.MaterialTabHost_materialTabsPrimaryColor, Color.parseColor("#009688")); <ide> accentColor = a.getColor(R.styleable.MaterialTabHost_accentColor,Color.parseColor("#00b0ff")); <ide> iconColor = a.getColor(R.styleable.MaterialTabHost_iconColor,Color.WHITE); <ide> textColor = a.getColor(R.styleable.MaterialTabHost_textColor,Color.WHITE);
Java
mit
3d58719c75fe5e377fb30fec0bd10490e694866d
0
SpongePowered/Mixin
/* * This file is part of Mixin, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.asm.mixin.transformer; import java.util.Locale; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.transformer.ext.Extensions; import org.spongepowered.asm.mixin.transformer.ext.IClassGenerator; import org.spongepowered.asm.service.IMixinAuditTrail; import org.spongepowered.asm.service.MixinService; import org.spongepowered.asm.util.perf.Profiler; import org.spongepowered.asm.util.perf.Profiler.Section; /** * Handles delegation of class generation tasks to the extensions */ public class MixinClassGenerator { /** * Log things for stuff */ static final Logger logger = LogManager.getLogger("mixin"); /** * Transformer extensions */ private final Extensions extensions; /** * Profiler */ private final Profiler profiler; /** * Audit trail (if available); */ private final IMixinAuditTrail auditTrail; /** * ctor */ MixinClassGenerator(MixinEnvironment environment, Extensions extensions) { this.extensions = extensions; this.profiler = MixinEnvironment.getProfiler(); this.auditTrail = MixinService.getService().getAuditTrail(); } synchronized boolean generateClass(MixinEnvironment environment, String name, ClassNode classNode) { if (name == null) { MixinClassGenerator.logger.warn("MixinClassGenerator tried to generate a class with no name!"); return false; } for (IClassGenerator generator : this.extensions.getGenerators()) { Section genTimer = this.profiler.begin("generator", generator.getClass().getSimpleName().toLowerCase(Locale.ROOT)); boolean success = generator.generate(name, classNode); genTimer.end(); if (success) { if (this.auditTrail != null) { this.auditTrail.onGenerate(name, generator.getName()); } this.extensions.export(environment, name.replace('.', '/'), false, classNode); return true; } } return false; } }
src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassGenerator.java
/* * This file is part of Mixin, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.asm.mixin.transformer; import java.util.Locale; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.transformer.ext.Extensions; import org.spongepowered.asm.mixin.transformer.ext.IClassGenerator; import org.spongepowered.asm.service.IMixinAuditTrail; import org.spongepowered.asm.service.MixinService; import org.spongepowered.asm.util.perf.Profiler; import org.spongepowered.asm.util.perf.Profiler.Section; /** * Handles delegation of class generation tasks to the extensions */ public class MixinClassGenerator { /** * Log things for stuff */ static final Logger logger = LogManager.getLogger("mixin"); /** * Transformer extensions */ private final Extensions extensions; /** * Profiler */ private final Profiler profiler; /** * Audit trail (if available); */ private final IMixinAuditTrail auditTrail; /** * ctor */ MixinClassGenerator(MixinEnvironment environment, Extensions extensions) { this.extensions = extensions; this.profiler = MixinEnvironment.getProfiler(); this.auditTrail = MixinService.getService().getAuditTrail(); } synchronized boolean generateClass(MixinEnvironment environment, String name, ClassNode classNode) { if (name == null) { MixinClassGenerator.logger.warn("MixinClassGenerator tried to generate a class with no name!"); return false; } for (IClassGenerator generator : this.extensions.getGenerators()) { Section genTimer = this.profiler.begin("generator", generator.getClass().getSimpleName().toLowerCase(Locale.ROOT)); boolean success = generator.generate(name, classNode); genTimer.end(); if (success) { this.auditTrail.onGenerate(name, generator.getName()); this.extensions.export(environment, name.replace('.', '/'), false, classNode); return true; } } return false; } }
Add missing null check for audit trail in class generator
src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassGenerator.java
Add missing null check for audit trail in class generator
<ide><path>rc/main/java/org/spongepowered/asm/mixin/transformer/MixinClassGenerator.java <ide> boolean success = generator.generate(name, classNode); <ide> genTimer.end(); <ide> if (success) { <del> this.auditTrail.onGenerate(name, generator.getName()); <add> if (this.auditTrail != null) { <add> this.auditTrail.onGenerate(name, generator.getName()); <add> } <ide> this.extensions.export(environment, name.replace('.', '/'), false, classNode); <ide> return true; <ide> }
Java
mit
c668807697f5549a32b08b23120e6d10f2bbe7f7
0
doubleaykay/pollen-app
package mystikos.pollen; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.support.v4.content.res.ResourcesCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.CardView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import android.widget.Toast; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.Calendar; public class MainActivity extends AppCompatActivity { private TextView JnumberToday; private TextView JnumberTomorrow; private TextView JnumberDayAfter; private TextView JtextDayAfter; private JsonElement jelement; private JsonObject jobject; private CardView JcardToday; private CardView JcardTomorrow; private CardView JcardDayAfter; private String[] pollen; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(myToolbar); JnumberToday = (TextView) findViewById(R.id.numberToday); JnumberTomorrow = (TextView) findViewById(R.id.numberTomorrow); JnumberDayAfter = (TextView) findViewById(R.id.numberDayAfter); JtextDayAfter = (TextView) findViewById(R.id.textDayAfter); JcardToday = (CardView) findViewById(R.id.cardToday); JcardTomorrow = (CardView) findViewById(R.id.cardTomorrow); JcardDayAfter = (CardView) findViewById(R.id.cardDayAfter); pollen = new String[5]; run(); } //run when activity created @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); return true; } //inflate menu @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menuAbout: Intent about = new Intent(MainActivity.this, AboutActivity.class); MainActivity.this.startActivity(about); return true; case R.id.menuSettings: Intent settings = new Intent(MainActivity.this, SettingsActivity.class); MainActivity.this.startActivity(settings); finish(); return true; case R.id.menuRefresh: run(); return true; default: return super.onOptionsItemSelected(item); } } //listener for menu items public void run() { //setDayAfterTitleText(); //TODO set day after title text resetCardColor(); setLoadingText(); if (isOnline() == true) { new getPollenDataAsync().execute(); } else { Context context = getApplicationContext(); CharSequence text = "Please connect to the internet to proceed."; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } } //calls other methods, linked to refresh button public boolean isOnline() { Runtime runtime = Runtime.getRuntime(); try { Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8"); int exitValue = ipProcess.waitFor(); return (exitValue == 0); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return false; } private void setDayAfterTitleText() { String[] days = new String[7]; days[0] = "SUNDAY"; days[1] = "MONDAY"; days[2] = "TUESDAY"; days[3] = "WEDNESDAY"; days[4] = "THURSDAY"; days[5] = "FRIDAY"; days[6] = "SATURDAY"; Calendar calendar = Calendar.getInstance(); int day = calendar.get(Calendar.DAY_OF_WEEK); switch (day) { case Calendar.SUNDAY: JtextDayAfter.setText(days[2]); case Calendar.MONDAY: JtextDayAfter.setText(days[3]); case Calendar.TUESDAY: JtextDayAfter.setText(days[4]); case Calendar.WEDNESDAY: JtextDayAfter.setText(days[5]); case Calendar.THURSDAY: JtextDayAfter.setText(days[6]); case Calendar.FRIDAY: JtextDayAfter.setText(days[0]); case Calendar.SATURDAY: JtextDayAfter.setText(days[1]); } } //logic to set the day after text to the day in two days //TODO read from strings file so that this can be localized //TODO DOES NOT WORK private void setLoadingText() { JnumberToday.setText("..."); JnumberTomorrow.setText("..."); JnumberDayAfter.setText("..."); } //set until AsyncTask loads data private void setPollenText() { JnumberToday.setText(pollen[0]); JnumberTomorrow.setText(pollen[1]); JnumberDayAfter.setText(pollen[2]); setCardColor(); } //method to set the textviews for pollen data based on values in pollen array private String getZip() { return PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("zip", ""); } //method to get zip code from shared preferences private void setCardColor() { double pollenToday = Double.parseDouble(pollen[0]); if ( pollenToday <= 4.0) JcardToday.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.green, null)); else if ( pollenToday > 4.0 && pollenToday <= 8.0) JcardToday.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.yellow, null)); else JcardToday.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.red, null)); //today card color double pollenTomorrow = Double.parseDouble(pollen[1]); if ( pollenTomorrow <= 4.0) JcardTomorrow.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.green, null)); else if ( pollenTomorrow > 4.0 && pollenTomorrow <= 8.0) JcardTomorrow.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.yellow, null)); else JcardTomorrow.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.red, null)); //tomorrow card color double pollenDayAfter = Double.parseDouble(pollen[2]); if ( pollenDayAfter <= 4.0) JcardDayAfter.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.green, null)); else if ( pollenDayAfter > 4.0 && pollenDayAfter <= 8.0) JcardDayAfter.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.yellow, null)); else JcardDayAfter.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.red, null)); //day after card color } //set card color based on pollen level private void resetCardColor() { JcardToday.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.card, null)); JcardTomorrow.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.card, null)); JcardDayAfter.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.card, null)); } //reset card background to default private void setLocationText() { String city = pollen[3].replace("\"", ""); String state = pollen[4].replace("\"", ""); String location = city + ", " + state; setTitle(location); } //set title of activity based on parsed location data private class getPollenDataAsync extends AsyncTask<Void, Void, String[]> { protected String[] doInBackground(Void... params) { String[] asyncdata = new String[5]; try { URL url = new URL("http://pollenapps.com/AllergyAlertWebSVC/api/1.0/Forecast/ForecastForZipCode?Zipcode=" + getZip() + "&Affiliateid=9642&AppID=2.2.4&uid=679566639b"); //url with zip code variable //URL url = new URL("http://pollenapps.com/AllergyAlertWebSVC/api/1.0/Forecast/ForecastForZipCode?Zipcode=" + getZip() + "&Affiliateid=9642&AppID=2.1.0&uid=6693636764"); InputStream in = url.openStream(); jelement = new JsonParser().parse(new InputStreamReader(in)); jobject = jelement.getAsJsonObject(); asyncdata[3] = jobject.get("City").toString(); //city name asyncdata[4] = jobject.get("State").toString(); //state abbreviation jobject = jobject.getAsJsonObject("allergyForecast"); asyncdata[0] = jobject.get("Day0").toString(); //pollen today asyncdata[1] = jobject.get("Day1").toString(); //pollen tomorrow asyncdata[2] = jobject.get("Day2").toString(); //pollen day after } catch (Exception e) {e.printStackTrace();} return asyncdata; } protected void onPostExecute(String[] result) { super.onPostExecute(result); pollen[0] = result[0]; pollen[1] = result[1]; pollen[2] = result[2]; pollen[3] = result[3]; pollen[4] = result[4]; if (pollen[0] == null) { Context context = getApplicationContext(); CharSequence text = "Please enter a valid zip code in location settings!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } //if array is blank due to invalid zip code, alert user instead of just crashing else { setPollenText(); setLocationText(); } //if array is not blank, continue as normal } } }
app/src/main/java/mystikos/pollen/MainActivity.java
package mystikos.pollen; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.support.v4.content.res.ResourcesCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.CardView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import android.widget.Toast; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.Calendar; public class MainActivity extends AppCompatActivity { private TextView JnumberToday; private TextView JnumberTomorrow; private TextView JnumberDayAfter; private TextView JtextDayAfter; private JsonElement jelement; private JsonObject jobject; private CardView JcardToday; private CardView JcardTomorrow; private CardView JcardDayAfter; private String[] pollen; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(myToolbar); JnumberToday = (TextView) findViewById(R.id.numberToday); JnumberTomorrow = (TextView) findViewById(R.id.numberTomorrow); JnumberDayAfter = (TextView) findViewById(R.id.numberDayAfter); JtextDayAfter = (TextView) findViewById(R.id.textDayAfter); JcardToday = (CardView) findViewById(R.id.cardToday); JcardTomorrow = (CardView) findViewById(R.id.cardTomorrow); JcardDayAfter = (CardView) findViewById(R.id.cardDayAfter); pollen = new String[5]; run(); } //run when activity created @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); return true; } //inflate menu @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menuAbout: Intent about = new Intent(MainActivity.this, AboutActivity.class); MainActivity.this.startActivity(about); return true; case R.id.menuSettings: Intent settings = new Intent(MainActivity.this, SettingsActivity.class); MainActivity.this.startActivity(settings); finish(); return true; case R.id.menuRefresh: run(); return true; default: return super.onOptionsItemSelected(item); } } //listener for menu items public void run() { //setDayAfterTitleText(); //TODO set day after title text resetCardColor(); setLoadingText(); if (isOnline() == true) { new getPollenDataAsync().execute(); } else { Context context = getApplicationContext(); CharSequence text = "Please connect to the internet to proceed."; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } } //calls other methods, linked to refresh button public boolean isOnline() { Runtime runtime = Runtime.getRuntime(); try { Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8"); int exitValue = ipProcess.waitFor(); return (exitValue == 0); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return false; } private void setDayAfterTitleText() { String[] days = new String[7]; days[0] = "SUNDAY"; days[1] = "MONDAY"; days[2] = "TUESDAY"; days[3] = "WEDNESDAY"; days[4] = "THURSDAY"; days[5] = "FRIDAY"; days[6] = "SATURDAY"; Calendar calendar = Calendar.getInstance(); int day = calendar.get(Calendar.DAY_OF_WEEK); switch (day) { case Calendar.SUNDAY: JtextDayAfter.setText(days[2]); case Calendar.MONDAY: JtextDayAfter.setText(days[3]); case Calendar.TUESDAY: JtextDayAfter.setText(days[4]); case Calendar.WEDNESDAY: JtextDayAfter.setText(days[5]); case Calendar.THURSDAY: JtextDayAfter.setText(days[6]); case Calendar.FRIDAY: JtextDayAfter.setText(days[0]); case Calendar.SATURDAY: JtextDayAfter.setText(days[1]); } } //logic to set the day after text to the day in two days //TODO read from strings file so that this can be localized //TODO DOES NOT WORK private void setLoadingText() { JnumberToday.setText("..."); JnumberTomorrow.setText("..."); JnumberDayAfter.setText("..."); } //set until AsyncTask loads data private void setPollenText() { JnumberToday.setText(pollen[0]); JnumberTomorrow.setText(pollen[1]); JnumberDayAfter.setText(pollen[2]); setCardColor(); } //method to set the textviews for pollen data based on values in pollen array private String getZip() { return PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("zip", ""); } //method to get zip code from shared preferences private void setCardColor() { double pollenToday = Double.parseDouble(pollen[0]); if ( pollenToday <= 4.0) JcardToday.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.green, null)); else if ( pollenToday > 4.0 && pollenToday <= 8.0) JcardToday.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.yellow, null)); else JcardToday.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.red, null)); //today card color double pollenTomorrow = Double.parseDouble(pollen[1]); if ( pollenTomorrow <= 4.0) JcardTomorrow.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.green, null)); else if ( pollenTomorrow > 4.0 && pollenTomorrow <= 8.0) JcardTomorrow.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.yellow, null)); else JcardTomorrow.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.red, null)); //tomorrow card color double pollenDayAfter = Double.parseDouble(pollen[2]); if ( pollenDayAfter <= 4.0) JcardDayAfter.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.green, null)); else if ( pollenDayAfter > 4.0 && pollenDayAfter <= 8.0) JcardDayAfter.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.yellow, null)); else JcardDayAfter.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.red, null)); //day after card color } //set card color based on pollen level private void resetCardColor() { JcardToday.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.card, null)); JcardTomorrow.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.card, null)); JcardDayAfter.setCardBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.card, null)); } //reset card background to default private void setLocationText() { String city = pollen[3].replace("\"", ""); String state = pollen[4].replace("\"", ""); String location = city + ", " + state; setTitle(location); } //set title of activity based on parsed location data private class getPollenDataAsync extends AsyncTask<Void, Void, String[]> { protected String[] doInBackground(Void... params) { String[] asyncdata = new String[5]; try { URL url = new URL("http://pollenapps.com/AllergyAlertWebSVC/api/1.0/Forecast/ForecastForZipCode?Zipcode=" + getZip() + "&Affiliateid=9642&AppID=2.1.0&uid=6693636764"); //url with zip code variable InputStream in = url.openStream(); jelement = new JsonParser().parse(new InputStreamReader(in)); jobject = jelement.getAsJsonObject(); asyncdata[3] = jobject.get("City").toString(); //city name asyncdata[4] = jobject.get("State").toString(); //state abbreviation jobject = jobject.getAsJsonObject("allergyForecast"); asyncdata[0] = jobject.get("Day0").toString(); //pollen today asyncdata[1] = jobject.get("Day1").toString(); //pollen tomorrow asyncdata[2] = jobject.get("Day2").toString(); //pollen day after } catch (Exception e) {e.printStackTrace();} return asyncdata; } protected void onPostExecute(String[] result) { super.onPostExecute(result); pollen[0] = result[0]; pollen[1] = result[1]; pollen[2] = result[2]; pollen[3] = result[3]; pollen[4] = result[4]; if (pollen[0] == null) { Context context = getApplicationContext(); CharSequence text = "Please enter a valid zip code in location settings!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } //if array is blank due to invalid zip code, alert user instead of just crashing else { setPollenText(); setLocationText(); } //if array is not blank, continue as normal } } }
update url to make it work again
app/src/main/java/mystikos/pollen/MainActivity.java
update url to make it work again
<ide><path>pp/src/main/java/mystikos/pollen/MainActivity.java <ide> protected String[] doInBackground(Void... params) { <ide> String[] asyncdata = new String[5]; <ide> try { <del> URL url = new URL("http://pollenapps.com/AllergyAlertWebSVC/api/1.0/Forecast/ForecastForZipCode?Zipcode=" + getZip() + "&Affiliateid=9642&AppID=2.1.0&uid=6693636764"); //url with zip code variable <add> URL url = new URL("http://pollenapps.com/AllergyAlertWebSVC/api/1.0/Forecast/ForecastForZipCode?Zipcode=" + getZip() + "&Affiliateid=9642&AppID=2.2.4&uid=679566639b"); //url with zip code variable <add> //URL url = new URL("http://pollenapps.com/AllergyAlertWebSVC/api/1.0/Forecast/ForecastForZipCode?Zipcode=" + getZip() + "&Affiliateid=9642&AppID=2.1.0&uid=6693636764"); <ide> InputStream in = url.openStream(); <ide> <ide> jelement = new JsonParser().parse(new InputStreamReader(in));
JavaScript
mit
305ee062adc3c03cae45a7bbef5ee745cc5796dd
0
likr/eg-renderer-canvas,likr/eg-renderer-canvas
import * as d3 from 'd3' import { centerTransform, layoutRect } from './centering' import { interpolateVertex, interpolateEdge, diff } from './interpolate' import { renderEdge, renderEdgeLabel, renderVertex, renderVertexLabel } from './render' import {zoom} from './zoom' import {adjustEdge} from './marker-point' const devicePixelRatio = () => { return window.devicePixelRatio || 1.0 } const get = (...args) => { let d = args[0] const key = args[1] const attrs = key.split('.') for (const attr of attrs) { if (!d.hasOwnProperty(attr)) { if (args.length === 2) { throw new Error(`Object doesn't have an attribute ${key}`) } return args[2] } d = d[attr] } return d } const privates = new WeakMap() const setWidth = (e, width) => { const p = privates.get(e) p.canvas.width = width * devicePixelRatio() p.canvas.style.width = `${width}px` } const setHeight = (e, height) => { const p = privates.get(e) p.canvas.height = height * devicePixelRatio() p.canvas.style.height = `${height}px` } const getter = (element, attributeName, defaultValue) => { if (!element.hasAttribute(attributeName)) { return defaultValue } return element.getAttribute(attributeName) } class EgRendererElement extends window.HTMLElement { static get observedAttributes () { return [ 'src', 'width', 'height', 'graph-nodes-property', 'graph-links-property', 'node-id-property', 'node-x-property', 'node-y-property', 'node-width-property', 'node-height-property', 'node-type-property', 'node-visibility-property', 'node-fill-color-property', 'node-fill-opacity-property', 'node-stroke-color-property', 'node-stroke-opacity-property', 'node-stroke-width-property', 'node-label-property', 'node-label-fill-color-property', 'node-label-fill-opacity-property', 'node-label-stroke-color-property', 'node-label-stroke-opacity-property', 'node-label-stroke-width-property', 'link-source-property', 'link-target-property', 'link-stroke-color-property', 'link-stroke-opacity-property', 'link-stroke-width-property', 'link-visibility-property', 'link-source-marker-shape-property', 'link-source-marker-size-property', 'link-target-marker-shape-property', 'link-target-marker-size-property', 'link-label-property', 'link-label-fill-color-property', 'link-label-fill-opacity-property', 'link-label-stroke-color-property', 'link-label-stroke-opacity-property', 'link-label-stroke-width-property', 'default-node-x', 'default-node-y', 'default-node-width', 'default-node-height', 'default-node-type', 'default-node-visibility', 'default-node-fill-color', 'default-node-fill-opacity', 'default-node-stroke-color', 'default-node-stroke-opacity', 'default-node-stroke-width', 'default-node-label', 'default-node-label-fill-color', 'default-node-label-fill-opacity', 'default-node-label-stroke-color', 'default-node-label-stroke-opacity', 'default-node-label-stroke-width', 'default-link-stroke-color', 'default-link-stroke-opacity', 'default-link-stroke-width', 'default-link-visibility', 'default-link-source-marker-shape', 'default-link-source-marker-size', 'default-link-target-marker-shape', 'default-link-target-marker-size', 'default-link-label', 'default-link-label-fill-color', 'default-link-label-fill-opacity', 'default-link-label-stroke-color', 'default-link-label-stroke-opacity', 'default-link-label-stroke-width' ] } constructor () { super() const p = { invalidate: false, originalData: null, canvas: document.createElement('canvas'), data: { vertexIds: [], vertices: new Map(), edgeIds: [], edges: new Map() }, transform: { x: 0, y: 0, k: 1 }, highlightedVertex: null, layout: { update: { vertices: [], edges: [] }, enter: { vertices: [], edges: [] }, exit: { vertices: [], edges: [] } }, margin: 10, layoutTime: 0, ease: d3.easeCubic } p.zoom = zoom(this, p) privates.set(this, p) d3.select(p.canvas) .call(p.zoom) p.canvas.addEventListener('mousemove', (event) => { if (this.canDragNode && event.region) { p.canvas.style.cursor = 'pointer' p.highlightedVertex = event.region } else if (this.canZoom) { p.canvas.style.cursor = 'move' p.highlightedVertex = null } else { p.canvas.style.cursor = 'default' } }) p.canvas.addEventListener('click', (event) => { if (event.region) { this.dispatchEvent(new window.CustomEvent('nodeclick', { detail: { id: event.region } })) } }) } connectedCallback () { const p = privates.get(this) this.appendChild(p.canvas) const render = () => { if (p.invalidate && p.originalData) { this.update(true) } p.invalidate = false const now = new Date() const transitionDuration = this.transitionDuration const t = now > p.layoutTime ? (now - p.layoutTime) / transitionDuration : 1 / transitionDuration const r = p.ease(t) const ctx = p.canvas.getContext('2d') ctx.save() ctx.clearRect(0, 0, p.canvas.width, p.canvas.height) ctx.scale(devicePixelRatio(), devicePixelRatio()) ctx.translate(p.margin, p.margin) ctx.translate(p.transform.x, p.transform.y) ctx.scale(p.transform.k, p.transform.k) if (r < 1) { ctx.globalAlpha = 1 - r for (const edge of p.layout.exit.edges) { renderEdge(ctx, edge) } } ctx.globalAlpha = Math.min(1, r) for (const edge of p.layout.enter.edges) { renderEdge(ctx, edge) } ctx.globalAlpha = 1 for (const {current, next} of p.layout.update.edges) { if (r < 1) { renderEdge(ctx, interpolateEdge(current, next, r)) } else { renderEdge(ctx, next) } } if (r < 1) { ctx.globalAlpha = 1 - r for (const edge of p.layout.exit.edges) { renderEdgeLabel(ctx, edge) } } ctx.globalAlpha = Math.min(1, r) for (const edge of p.layout.enter.edges) { renderEdgeLabel(ctx, edge) } ctx.globalAlpha = 1 for (const {current, next} of p.layout.update.edges) { if (r < 1) { renderEdgeLabel(ctx, interpolateEdge(current, next, r)) } else { renderEdgeLabel(ctx, next) } } if (r < 1) { ctx.globalAlpha = 1 - r for (const vertex of p.layout.exit.vertices) { renderVertex(ctx, vertex) } } ctx.globalAlpha = Math.min(1, r) for (const vertex of p.layout.enter.vertices) { renderVertex(ctx, vertex) } ctx.globalAlpha = 1 for (const {current, next} of p.layout.update.vertices) { if (r < 1) { renderVertex(ctx, interpolateVertex(current, next, r)) } else { renderVertex(ctx, next) } } if (r < 1) { ctx.globalAlpha = 1 - r for (const vertex of p.layout.exit.vertices) { renderVertexLabel(ctx, vertex) } } ctx.globalAlpha = Math.min(1, r) for (const vertex of p.layout.enter.vertices) { renderVertexLabel(ctx, vertex) } ctx.globalAlpha = 1 for (const {current, next} of p.layout.update.vertices) { if (r < 1) { renderVertexLabel(ctx, interpolateVertex(current, next, r)) } else { renderVertexLabel(ctx, next) } } ctx.restore() window.requestAnimationFrame(render) } render() } attributeChangedCallback (attr, oldValue, newValue) { switch (attr) { case 'src': window.fetch(newValue) .then((response) => response.json()) .then((data) => { this.dispatchEvent(new window.CustomEvent('datafetchend', {detail: data})) this.load(data) }) break case 'width': setWidth(this, newValue) break case 'height': setHeight(this, newValue) break default: this.invalidate() } } center () { const {canvas, data, margin, zoom} = privates.get(this) const {layoutWidth, layoutHeight, left, top} = layoutRect(data) const canvasWidth = canvas.width / devicePixelRatio() const canvasHeight = canvas.height / devicePixelRatio() const {x, y, k} = centerTransform(layoutWidth, layoutHeight, left, top, canvasWidth, canvasHeight, margin) zoom.transform(d3.select(canvas), d3.zoomIdentity.translate(x, y).scale(k).translate(-left, -top)) return this } load (data) { privates.get(this).originalData = data return this.update() } update (preservePos = false) { const p = privates.get(this) p.prevData = p.data const data = p.originalData const vertices = get(data, this.graphNodesProperty) .filter((node) => get(node, this.nodeVisibilityProperty, this.defaultNodeVisibility)) .map((node, i) => { const fillColor = d3.color(get(node, this.nodeFillColorProperty, this.defaultNodeFillColor)) fillColor.opacity = +get(node, this.nodeFillOpacityProperty, this.defaultNodeFillOpacity) const strokeColor = d3.color(get(node, this.nodeStrokeColorProperty, this.defaultNodeStrokeColor)) strokeColor.opacity = +get(node, this.nodeStrokeOpacityProperty, this.defaultNodeStrokeOpacity) const labelFillColor = d3.color(get(node, this.nodeLabelFillColorProperty, this.defaultNodeLabelFillColor)) labelFillColor.opacity = +get(node, this.nodeLabelFillOpacityProperty, this.defaultNodeLabelFillOpacity) const labelStrokeColor = d3.color(get(node, this.nodeLabelStrokeColorProperty, this.defaultNodeLabelStrokeColor)) labelStrokeColor.opacity = +get(node, this.nodeLabelStrokeOpacityProperty, this.defaultNodeLabelStrokeOpacity) const u = (this.nodeIdProperty === '$index' ? i : get(node, this.nodeIdProperty)).toString() return { u, x: preservePos && p.prevData.vertices.has(u) ? p.prevData.vertices.get(u).x : +get(node, this.nodeXProperty, this.defaultNodeX), y: preservePos && p.prevData.vertices.has(u) ? p.prevData.vertices.get(u).y : +get(node, this.nodeYProperty, this.defaultNodeY), width: +get(node, this.nodeWidthProperty, this.defaultNodeWidth), height: +get(node, this.nodeHeightProperty, this.defaultNodeHeight), type: get(node, this.nodeTypeProperty, this.defaultNodeType), fillColor, strokeColor, strokeWidth: +get(node, this.nodeStrokeWidthProperty, this.defaultNodeStrokeWidth), label: get(node, this.nodeLabelProperty, this.defaultNodeLabel), labelFillColor, labelStrokeColor, labelStrokeWidth: +get(node, this.nodeLabelStrokeWidthProperty, this.defaultNodeLabelStrokeWidth), labelFontSize: +get(node, this.nodeLabelFontSizeProperty, this.defaultNodeLabelFontSize), labelFontFamily: get(node, this.nodeLabelFontFamilyProperty, this.defaultNodeLabelFontFamily), inEdges: [], outEdges: [], d: node } }) const indices = new Map(vertices.map(({u}, i) => [u, i])) const edges = get(data, this.graphLinksProperty) .filter((link) => get(link, this.linkVisibilityProperty, this.defaultLinkVisibility)) .filter((link) => { const u = get(link, this.linkSourceProperty).toString() const v = get(link, this.linkTargetProperty).toString() return indices.has(u) && indices.has(v) }) .map((link) => { const u = get(link, this.linkSourceProperty).toString() const v = get(link, this.linkTargetProperty).toString() const strokeColor = d3.color(get(link, this.linkStrokeColorProperty, this.defaultLinkStrokeColor)) strokeColor.opacity = +get(link, this.linkStrokeOpacityProperty, this.defaultLinkStrokeOpacity) const labelFillColor = d3.color(get(link, this.linkLabelFillColorProperty, this.defaultLinkLabelFillColor)) labelFillColor.opacity = +get(link, this.linkLabelFillOpacityProperty, this.defaultLinkLabelFillOpacity) const labelStrokeColor = d3.color(get(link, this.linkLabelStrokeColorProperty, this.defaultLinkLabelStrokeColor)) labelStrokeColor.opacity = +get(link, this.linkLabelStrokeOpacityProperty, this.defaultLinkLabelStrokeOpacity) const du = vertices[indices.get(u)] const dv = vertices[indices.get(v)] const newPoints = [[du.x, du.y]] for (const [x, y] of get(link, this.linkBendsProperty, [])) { newPoints.push([x, y]) } newPoints.push([dv.x, dv.y]) const points = preservePos && p.prevData.edges.has(u) && p.prevData.edges.get(u).has(v) ? p.prevData.edges.get(u).get(v).points : newPoints const edge = { u, v, points, type: get(link, this.linkTypeProperty, this.defaultLinkType), strokeColor, strokeWidth: +get(link, this.linkStrokeWidthProperty, this.defaultLinkStrokeWidth), sourceMarkerShape: get(link, this.linkSourceMarkerShapeProperty, this.defaultLinkSourceMarkerShape), sourceMarkerSize: +get(link, this.linkSourceMarkerSizeProperty, this.defaultLinkSourceMarkerSize), targetMarkerShape: get(link, this.linkTargetMarkerShapeProperty, this.defaultLinkTargetMarkerShape), targetMarkerSize: +get(link, this.linkTargetMarkerSizeProperty, this.defaultLinkTargetMarkerSize), label: get(link, this.linkLabelProperty, this.defaultLinkLabel), labelFillColor, labelStrokeColor, labelStrokeWidth: +get(link, this.linkLabelStrokeWidthProperty, this.defaultLinkLabelStrokeWidth), labelFontSize: +get(link, this.linkLabelFontSizeProperty, this.defaultLinkLabelFontSize), labelFontFamily: get(link, this.linkLabelFontFamilyProperty, this.defaultLinkLabelFontFamily), d: link } du.outEdges.push(edge) dv.inEdges.push(edge) return edge }) p.data = { vertexIds: vertices.map(({u}) => u), vertices: new Map(vertices.map((vertex) => [vertex.u, vertex])), edgeIds: edges.map(({u, v}) => [u, v]), edges: new Map(vertices.map((vertex) => [vertex.u, new Map()])) } for (const edge of edges) { p.data.edges.get(edge.u).set(edge.v, edge) } this.onLayout(p.data, preservePos) for (const [u, v] of p.data.edgeIds) { const edge = p.data.edges.get(u).get(v) const du = p.data.vertices.get(u) const dv = p.data.vertices.get(v) adjustEdge(edge, du, dv) } p.layout = diff(p.prevData, p.data) p.layoutTime = new Date() if (this.autoCentering) { this.center() } return this } onLayout () { } invalidate () { privates.get(this).invalidate = true } get autoUpdate () { return !this.hasAttribute('no-auto-update') } set autoUpdate (value) { if (value) { this.removeAttribute('no-auto-update') } else { this.setAttribute('no-auto-update', '') } } get autoCentering () { return !this.hasAttribute('no-auto-centering') } set autoCentering (value) { if (value) { this.removeAttribute('no-auto-centering') } else { this.setAttribute('no-auto-centering', '') } } get canZoom () { return !this.hasAttribute('no-zoom') } set canZoom (value) { if (value) { this.removeAttribute('no-zoom') } else { this.setAttribute('no-zoom', '') } } get canDragNode () { return !this.hasAttribute('no-drag-node') } set canDragNode (value) { if (value) { this.removeAttribute('no-drag-node') } else { this.setAttribute('no-drag-node', '') } } get src () { return getter(this, 'src', null) } set src (value) { this.setAttribute('src', value) } get width () { return getter(this, 'width', 300) } set width (value) { this.setAttribute('width', value) } get height () { return getter(this, 'height', 150) } set height (value) { this.setAttribute('height', value) } get transitionDuration () { return getter(this, 'transition-duration', 0) } set transitionDuration (value) { this.setAttribute('transition-duration', value) } get graphNodesProperty () { return getter(this, 'graph-nodes-property', 'nodes') } set graphNodesProperty (value) { this.setAttribute('graph-nodes-property', value) } get graphLinksProperty () { return getter(this, 'graph-links-property', 'links') } set graphLinksProperty (value) { this.setAttribute('graph-links-property', value) } get nodeIdProperty () { return getter(this, 'node-id-property', '$index') } set nodeIdProperty (value) { this.setAttribute('node-id-property', value) } get nodeXProperty () { return getter(this, 'node-x-property', 'x') } set nodeXProperty (value) { this.setAttribute('node-x-property', value) } get nodeYProperty () { return getter(this, 'node-y-property', 'y') } set nodeYProperty (value) { this.setAttribute('node-y-property', value) } get nodeWidthProperty () { return getter(this, 'node-width-property', 'width') } set nodeWidthProperty (value) { this.setAttribute('node-width-property', value) } get nodeHeightProperty () { return getter(this, 'node-height-property', 'height') } set nodeHeightProperty (value) { this.setAttribute('node-height-property', value) } get nodeFillColorProperty () { return getter(this, 'node-fill-color-property', 'fillColor') } set nodeFillColorProperty (value) { this.setAttribute('node-fill-color-property', value) } get nodeFillOpacityProperty () { return getter(this, 'node-fill-opacity-property', 'fillOpacity') } set nodeFillOpacityProperty (value) { this.setAttribute('node-fill-opacity-property', value) } get nodeStrokeColorProperty () { return getter(this, 'node-stroke-color-property', 'strokeColor') } set nodeStrokeColorProperty (value) { this.setAttribute('node-stroke-color-property', value) } get nodeStrokeOpacityProperty () { return getter(this, 'node-stroke-opacity-property', 'strokeOpacity') } set nodeStrokeOpacityProperty (value) { this.setAttribute('node-stroke-opacity-property', value) } get nodeStrokeWidthProperty () { return getter(this, 'node-stroke-width-property', 'strokeWidth') } set nodeStrokeWidthProperty (value) { this.setAttribute('node-stroke-width-property', value) } get nodeTypeProperty () { return getter(this, 'node-type-property', 'type') } set nodeTypeProperty (value) { this.setAttribute('node-type-property', value) } get nodeVisibilityProperty () { return getter(this, 'node-visibility-property', 'visibility') } set nodeVisibilityProperty (value) { this.setAttribute('node-visibility-property', value) } get nodeLabelProperty () { return getter(this, 'node-label-property', 'label') } set nodeLabelProperty (value) { this.setAttribute('node-label-property', value) } get nodeLabelFillColorProperty () { return getter(this, 'node-label-fill-color-property', 'labelFillColor') } set nodeLabelFillColorProperty (value) { this.setAttribute('node-label-fill-color-property', value) } get nodeLabelFillOpacityProperty () { return getter(this, 'node-label-fill-opacity-property', 'labelFillOpacity') } set nodeLabelFillOpacityProperty (value) { this.setAttribute('node-label-fill-opacity-property', value) } get nodeLabelStrokeColorProperty () { return getter(this, 'node-label-stroke-color-property', 'labelStrokeColor') } set nodeLabelStrokeColorProperty (value) { this.setAttribute('node-label-stroke-color-property', value) } get nodeLabelStrokeOpacityProperty () { return getter(this, 'node-label-stroke-opacity-property', 'labelStrokeOpacity') } set nodeLabelStrokeOpacityProperty (value) { this.setAttribute('node-label-stroke-opacity-property', value) } get nodeLabelStrokeWidthProperty () { return getter(this, 'node-label-stroke-width-property', 'labelStrokeWidth') } set nodeLabelStrokeWidthProperty (value) { this.setAttribute('node-label-stroke-width-property', value) } get nodeLabelFontSizeProperty () { return getter(this, 'node-label-font-size-property', 'labelFontSize') } set nodeLabelFontSizeProperty (value) { this.setAttribute('node-label-font-size-property', value) } get nodeLabelFontFamilyProperty () { return getter(this, 'node-label-font-family-property', 'labelFontFamily') } set nodeLabelFontFamilyProperty (value) { this.setAttribute('node-label-font-family-property', value) } get linkSourceProperty () { return getter(this, 'link-source-property', 'source') } set linkSourceProperty (value) { this.setAttribute('link-source-property', value) } get linkTargetProperty () { return getter(this, 'link-target-property', 'target') } set linkTargetProperty (value) { this.setAttribute('link-target-property', value) } get linkBendsProperty () { return getter(this, 'link-bends-property', 'bends') } set linkBendsProperty (value) { this.setAttribute('link-bends-property', value) } get linkStrokeColorProperty () { return getter(this, 'link-stroke-color-property', 'strokeColor') } set linkStrokeColorProperty (value) { this.setAttribute('link-stroke-color-property', value) } get linkStrokeOpacityProperty () { return getter(this, 'link-stroke-opacity-property', 'strokeOpacity') } set linkStrokeOpacityProperty (value) { this.setAttribute('link-stroke-opacity-property', value) } get linkStrokeWidthProperty () { return getter(this, 'link-stroke-width-property', 'strokeWidth') } set linkStrokeWidthProperty (value) { this.setAttribute('link-stroke-width-property', value) } get linkTypeProperty () { return getter(this, 'link-type-property', 'type') } set linkTypeProperty (value) { this.setAttribute('link-type-property', value) } get linkVisibilityProperty () { return getter(this, 'link-visibility-property', 'visibility') } set linkVisibilityProperty (value) { this.setAttribute('link-visibility-property', value) } get linkSourceMarkerShapeProperty () { return getter(this, 'link-source-marker-shape-property', 'sourceMarkerShape') } set linkSourceMarkerShapeProperty (value) { this.setAttribute('link-source-marker-shape-property', value) } get linkSourceMarkerSizeProperty () { return getter(this, 'link-source-marker-size-property', 'sourceMarkerSize') } set linkSourceMarkerSizeProperty (value) { this.setAttribute('link-source-marker-size-property', value) } get linkTargetMarkerShapeProperty () { return getter(this, 'link-target-marker-shape-property', 'targetMarkerShape') } set linkTargetMarkerShapeProperty (value) { this.setAttribute('link-target-marker-shape-property', value) } get linkTargetMarkerSizeProperty () { return getter(this, 'link-target-marker-size-property', 'targetMarkerSize') } set linkTargetMarkerSizeProperty (value) { this.setAttribute('link-target-marker-size-property', value) } get linkLabelProperty () { return getter(this, 'link-label-property', 'label') } set linkLabelProperty (value) { this.setAttribute('link-label-property', value) } get linkLabelFillColorProperty () { return getter(this, 'link-label-fill-color-property', 'labelFillColor') } set linkLabelFillColorProperty (value) { this.setAttribute('link-label-fill-color-property', value) } get linkLabelFillOpacityProperty () { return getter(this, 'link-label-fill-opacity-property', 'labelFillOpacity') } set linkLabelFillOpacityProperty (value) { this.setAttribute('link-label-fill-opacity-property', value) } get linkLabelStrokeColorProperty () { return getter(this, 'link-label-stroke-color-property', 'labelStrokeColor') } set linkLabelStrokeColorProperty (value) { this.setAttribute('link-label-stroke-color-property', value) } get linkLabelStrokeOpacityProperty () { return getter(this, 'link-label-stroke-opacity-property', 'labelStrokeOpacity') } set linkLabelStrokeOpacityProperty (value) { this.setAttribute('link-label-stroke-opacity-property', value) } get linkLabelStrokeWidthProperty () { return getter(this, 'link-label-stroke-width-property', 'labelStrokeWidth') } set linkLabelStrokeWidthProperty (value) { this.setAttribute('link-label-stroke-width-property', value) } get linkLabelFontSizeProperty () { return getter(this, 'link-label-font-size-property', 'labelFontSize') } set linkLabelFontSizeProperty (value) { this.setAttribute('link-label-font-size-property', value) } get linkLabelFontFamilyProperty () { return getter(this, 'link-label-font-family-property', 'labelFontFamily') } set linkLabelFontFamilyProperty (value) { this.setAttribute('link-label-font-family-property', value) } get defaultNodeX () { return getter(this, 'default-node-x', 0) } set defaultNodeX (value) { this.setAttribute('default-node-x', value) } get defaultNodeY () { return getter(this, 'default-node-y', 0) } set defaultNodeY (value) { this.setAttribute('default-node-y', value) } get defaultNodeWidth () { return getter(this, 'default-node-width', 10) } set defaultNodeWidth (value) { this.setAttribute('default-node-width', value) } get defaultNodeHeight () { return getter(this, 'default-node-height', 10) } set defaultNodeHeight (value) { this.setAttribute('default-node-height', value) } get defaultNodeFillColor () { return getter(this, 'default-node-fill-color', '#fff') } set defaultNodeFillColor (value) { this.setAttribute('default-node-fill-color', value) } get defaultNodeFillOpacity () { return getter(this, 'default-node-fill-opacity', 1) } set defaultNodeFillOpacity (value) { this.setAttribute('default-node-fill-opacity', value) } get defaultNodeStrokeColor () { return getter(this, 'default-node-stroke-color', '#000') } set defaultNodeStrokeColor (value) { this.setAttribute('default-node-stroke-color', value) } get defaultNodeStrokeOpacity () { return getter(this, 'default-node-stroke-opacity', 1) } set defaultNodeStrokeOpacity (value) { this.setAttribute('default-node-stroke-opacity', value) } get defaultNodeStrokeWidth () { return getter(this, 'default-node-stroke-width', 1) } set defaultNodeStrokeWidth (value) { this.setAttribute('default-node-stroke-width', value) } get defaultNodeType () { return getter(this, 'default-node-type', 'circle') } set defaultNodeType (value) { this.setAttribute('default-node-type', value) } get defaultNodeVisibility () { return getter(this, 'default-node-visibility', true) } set defaultNodeVisibility (value) { this.setAttribute('default-node-visibility', value) } get defaultNodeLabel () { return getter(this, 'default-node-label', '') } set defaultNodeLabel (value) { this.setAttribute('default-node-label', value) } get defaultNodeLabelFillColor () { return getter(this, 'default-node-label-fill-color', '#000') } set defaultNodeLabelFillColor (value) { this.setAttribute('default-node-label-fill-color', value) } get defaultNodeLabelFillOpacity () { return getter(this, 'default-node-label-fill-opacity', 1) } set defaultNodeLabelFillOpacity (value) { this.setAttribute('default-node-label-fill-opacity', value) } get defaultNodeLabelStrokeColor () { return getter(this, 'default-node-label-stroke-color', '#fff') } set defaultNodeLabelStrokeColor (value) { this.setAttribute('default-node-label-stroke-color', value) } get defaultNodeLabelStrokeOpacity () { return getter(this, 'default-node-label-stroke-opacity', 1) } set defaultNodeLabelStrokeOpacity (value) { this.setAttribute('default-node-label-stroke-opacity', value) } get defaultNodeLabelStrokeWidth () { return getter(this, 'default-node-label-stroke-width', 0) } set defaultNodeLabelStrokeWidth (value) { this.setAttribute('default-node-label-stroke-width', value) } get defaultNodeLabelFontSize () { return getter(this, 'default-node-label-font-size', 10) } set defaultNodeLabelFontSize (value) { this.setAttribute('default-node-label-font-size', value) } get defaultNodeLabelFontFamily () { return getter(this, 'default-node-label-font-family', 'serif') } set defaultNodeLabelFontFamily (value) { this.setAttribute('default-node-label-font-family', value) } get defaultLinkStrokeColor () { return getter(this, 'default-link-stroke-color', '#000') } set defaultLinkStrokeColor (value) { this.setAttribute('default-link-stroke-color', value) } get defaultLinkStrokeOpacity () { return getter(this, 'default-link-stroke-opacity', 1) } set defaultLinkStrokeOpacity (value) { this.setAttribute('default-link-stroke-opacity', value) } get defaultLinkStrokeWidth () { return getter(this, 'default-link-stroke-width', 1) } set defaultLinkStrokeWidth (value) { this.setAttribute('default-link-stroke-width', value) } get defaultLinkType () { return getter(this, 'default-link-type', 'line') } set defaultLinkType (value) { this.setAttribute('default-link-type', value) } get defaultLinkVisibility () { return getter(this, 'default-link-visibility', true) } set defaultLinkVisibility (value) { this.setAttribute('default-link-visibility', value) } get defaultLinkSourceMarkerShape () { return getter(this, 'default-link-source-marker-shape', 'none') } set defaultLinkSourceMarkerShape (value) { this.setAttribute('default-link-source-marker-shape', value) } get defaultLinkSourceMarkerSize () { return getter(this, 'default-link-source-marker-size', 5) } set defaultLinkSourceMarkerSize (value) { this.setAttribute('default-link-source-marker-size', value) } get defaultLinkTargetMarkerShape () { return getter(this, 'default-link-target-marker-shape', 'none') } set defaultLinkTargetMarkerShape (value) { this.setAttribute('default-link-target-marker-shape', value) } get defaultLinkTargetMarkerSize () { return getter(this, 'default-link-target-marker-size', 5) } set defaultLinkTargetMarkerSize (value) { this.setAttribute('default-link-target-marker-size', value) } get defaultLinkLabel () { return getter(this, 'default-link-label', '') } set defaultLinkLabel (value) { this.setAttribute('default-link-label', value) } get defaultLinkLabelFillColor () { return getter(this, 'default-link-label-fill-color', '#000') } set defaultLinkLabelFillColor (value) { this.setAttribute('default-link-label-fill-color', value) } get defaultLinkLabelFillOpacity () { return getter(this, 'default-link-label-fill-opacity', 1) } set defaultLinkLabelFillOpacity (value) { this.setAttribute('default-link-label-fill-opacity', value) } get defaultLinkLabelStrokeColor () { return getter(this, 'default-link-label-stroke-color', '#fff') } set defaultLinkLabelStrokeColor (value) { this.setAttribute('default-link-label-stroke-color', value) } get defaultLinkLabelStrokeOpacity () { return getter(this, 'default-link-label-stroke-opacity', 1) } set defaultLinkLabelStrokeOpacity (value) { this.setAttribute('default-link-label-stroke-opacity', value) } get defaultLinkLabelStrokeWidth () { return getter(this, 'default-link-label-stroke-width', 0) } set defaultLinkLabelStrokeWidth (value) { this.setAttribute('default-link-label-stroke-width', value) } get defaultLinkLabelFontSize () { return getter(this, 'default-link-label-font-size', 10) } set defaultLinkLabelFontSize (value) { this.setAttribute('default-link-label-font-size', value) } get defaultLinkLabelFontFamily () { return getter(this, 'default-link-label-font-family', 'serif') } set defaultLinkLabelFontFamily (value) { this.setAttribute('default-link-label-font-family', value) } get data () { return privates.get(this).originalData } } window.customElements.define('eg-renderer', EgRendererElement)
src/index.js
import * as d3 from 'd3' import { centerTransform, layoutRect } from './centering' import { interpolateVertex, interpolateEdge, diff } from './interpolate' import { renderEdge, renderEdgeLabel, renderVertex, renderVertexLabel } from './render' import {zoom} from './zoom' import {adjustEdge} from './marker-point' const devicePixelRatio = () => { return window.devicePixelRatio || 1.0 } const get = (...args) => { let d = args[0] const key = args[1] const attrs = key.split('.') for (const attr of attrs) { if (!d.hasOwnProperty(attr)) { if (args.length === 2) { throw new Error(`Object doesn't have an attribute ${key}`) } return args[2] } d = d[attr] } return d } const privates = new WeakMap() const setWidth = (e, width) => { const p = privates.get(e) p.canvas.width = width * devicePixelRatio() p.canvas.style.width = `${width}px` } const setHeight = (e, height) => { const p = privates.get(e) p.canvas.height = height * devicePixelRatio() p.canvas.style.height = `${height}px` } const getter = (element, attributeName, defaultValue) => { if (!element.hasAttribute(attributeName)) { return defaultValue } return element.getAttribute(attributeName) } class EgRendererElement extends window.HTMLElement { static get observedAttributes () { return [ 'src', 'width', 'height', 'graph-nodes-property', 'graph-links-property', 'node-id-property', 'node-x-property', 'node-y-property', 'node-width-property', 'node-height-property', 'node-type-property', 'node-visibility-property', 'node-fill-color-property', 'node-fill-opacity-property', 'node-stroke-color-property', 'node-stroke-opacity-property', 'node-stroke-width-property', 'node-label-property', 'node-label-fill-color-property', 'node-label-fill-opacity-property', 'node-label-stroke-color-property', 'node-label-stroke-opacity-property', 'node-label-stroke-width-property', 'link-source-property', 'link-target-property', 'link-stroke-color-property', 'link-stroke-opacity-property', 'link-stroke-width-property', 'link-visibility-property', 'link-source-marker-shape-property', 'link-source-marker-size-property', 'link-target-marker-shape-property', 'link-target-marker-size-property', 'link-label-property', 'link-label-fill-color-property', 'link-label-fill-opacity-property', 'link-label-stroke-color-property', 'link-label-stroke-opacity-property', 'link-label-stroke-width-property', 'default-node-x', 'default-node-y', 'default-node-width', 'default-node-height', 'default-node-type', 'default-node-visibility', 'default-node-fill-color', 'default-node-fill-opacity', 'default-node-stroke-color', 'default-node-stroke-opacity', 'default-node-stroke-width', 'default-node-label', 'default-node-label-fill-color', 'default-node-label-fill-opacity', 'default-node-label-stroke-color', 'default-node-label-stroke-opacity', 'default-node-label-stroke-width', 'default-link-stroke-color', 'default-link-stroke-opacity', 'default-link-stroke-width', 'default-link-visibility', 'default-link-source-marker-shape', 'default-link-source-marker-size', 'default-link-target-marker-shape', 'default-link-target-marker-size', 'default-link-label', 'default-link-label-fill-color', 'default-link-label-fill-opacity', 'default-link-label-stroke-color', 'default-link-label-stroke-opacity', 'default-link-label-stroke-width' ] } constructor () { super() const p = { invalidate: false, originalData: null, canvas: document.createElement('canvas'), data: { vertexIds: [], vertices: new Map(), edgeIds: [], edges: new Map() }, transform: { x: 0, y: 0, k: 1 }, highlightedVertex: null, layout: { update: { vertices: [], edges: [] }, enter: { vertices: [], edges: [] }, exit: { vertices: [], edges: [] } }, margin: 10, layoutTime: 0, ease: d3.easeCubic } p.zoom = zoom(this, p) privates.set(this, p) d3.select(p.canvas) .call(p.zoom) p.canvas.addEventListener('mousemove', (event) => { if (this.canDragNode && event.region) { p.canvas.style.cursor = 'pointer' p.highlightedVertex = event.region } else if (this.canZoom) { p.canvas.style.cursor = 'move' p.highlightedVertex = null } else { p.canvas.style.cursor = 'default' } }) } connectedCallback () { const p = privates.get(this) this.appendChild(p.canvas) const render = () => { if (p.invalidate && p.originalData) { this.update(true) } p.invalidate = false const now = new Date() const transitionDuration = this.transitionDuration const t = now > p.layoutTime ? (now - p.layoutTime) / transitionDuration : 1 / transitionDuration const r = p.ease(t) const ctx = p.canvas.getContext('2d') ctx.save() ctx.clearRect(0, 0, p.canvas.width, p.canvas.height) ctx.scale(devicePixelRatio(), devicePixelRatio()) ctx.translate(p.margin, p.margin) ctx.translate(p.transform.x, p.transform.y) ctx.scale(p.transform.k, p.transform.k) if (r < 1) { ctx.globalAlpha = 1 - r for (const edge of p.layout.exit.edges) { renderEdge(ctx, edge) } } ctx.globalAlpha = Math.min(1, r) for (const edge of p.layout.enter.edges) { renderEdge(ctx, edge) } ctx.globalAlpha = 1 for (const {current, next} of p.layout.update.edges) { if (r < 1) { renderEdge(ctx, interpolateEdge(current, next, r)) } else { renderEdge(ctx, next) } } if (r < 1) { ctx.globalAlpha = 1 - r for (const edge of p.layout.exit.edges) { renderEdgeLabel(ctx, edge) } } ctx.globalAlpha = Math.min(1, r) for (const edge of p.layout.enter.edges) { renderEdgeLabel(ctx, edge) } ctx.globalAlpha = 1 for (const {current, next} of p.layout.update.edges) { if (r < 1) { renderEdgeLabel(ctx, interpolateEdge(current, next, r)) } else { renderEdgeLabel(ctx, next) } } if (r < 1) { ctx.globalAlpha = 1 - r for (const vertex of p.layout.exit.vertices) { renderVertex(ctx, vertex) } } ctx.globalAlpha = Math.min(1, r) for (const vertex of p.layout.enter.vertices) { renderVertex(ctx, vertex) } ctx.globalAlpha = 1 for (const {current, next} of p.layout.update.vertices) { if (r < 1) { renderVertex(ctx, interpolateVertex(current, next, r)) } else { renderVertex(ctx, next) } } if (r < 1) { ctx.globalAlpha = 1 - r for (const vertex of p.layout.exit.vertices) { renderVertexLabel(ctx, vertex) } } ctx.globalAlpha = Math.min(1, r) for (const vertex of p.layout.enter.vertices) { renderVertexLabel(ctx, vertex) } ctx.globalAlpha = 1 for (const {current, next} of p.layout.update.vertices) { if (r < 1) { renderVertexLabel(ctx, interpolateVertex(current, next, r)) } else { renderVertexLabel(ctx, next) } } ctx.restore() window.requestAnimationFrame(render) } render() } attributeChangedCallback (attr, oldValue, newValue) { switch (attr) { case 'src': window.fetch(newValue) .then((response) => response.json()) .then((data) => { this.dispatchEvent(new window.CustomEvent('datafetchend', {detail: data})) this.load(data) }) break case 'width': setWidth(this, newValue) break case 'height': setHeight(this, newValue) break default: this.invalidate() } } center () { const {canvas, data, margin, zoom} = privates.get(this) const {layoutWidth, layoutHeight, left, top} = layoutRect(data) const canvasWidth = canvas.width / devicePixelRatio() const canvasHeight = canvas.height / devicePixelRatio() const {x, y, k} = centerTransform(layoutWidth, layoutHeight, left, top, canvasWidth, canvasHeight, margin) zoom.transform(d3.select(canvas), d3.zoomIdentity.translate(x, y).scale(k).translate(-left, -top)) return this } load (data) { privates.get(this).originalData = data return this.update() } update (preservePos = false) { const p = privates.get(this) p.prevData = p.data const data = p.originalData const vertices = get(data, this.graphNodesProperty) .filter((node) => get(node, this.nodeVisibilityProperty, this.defaultNodeVisibility)) .map((node, i) => { const fillColor = d3.color(get(node, this.nodeFillColorProperty, this.defaultNodeFillColor)) fillColor.opacity = +get(node, this.nodeFillOpacityProperty, this.defaultNodeFillOpacity) const strokeColor = d3.color(get(node, this.nodeStrokeColorProperty, this.defaultNodeStrokeColor)) strokeColor.opacity = +get(node, this.nodeStrokeOpacityProperty, this.defaultNodeStrokeOpacity) const labelFillColor = d3.color(get(node, this.nodeLabelFillColorProperty, this.defaultNodeLabelFillColor)) labelFillColor.opacity = +get(node, this.nodeLabelFillOpacityProperty, this.defaultNodeLabelFillOpacity) const labelStrokeColor = d3.color(get(node, this.nodeLabelStrokeColorProperty, this.defaultNodeLabelStrokeColor)) labelStrokeColor.opacity = +get(node, this.nodeLabelStrokeOpacityProperty, this.defaultNodeLabelStrokeOpacity) const u = (this.nodeIdProperty === '$index' ? i : get(node, this.nodeIdProperty)).toString() return { u, x: preservePos && p.prevData.vertices.has(u) ? p.prevData.vertices.get(u).x : +get(node, this.nodeXProperty, this.defaultNodeX), y: preservePos && p.prevData.vertices.has(u) ? p.prevData.vertices.get(u).y : +get(node, this.nodeYProperty, this.defaultNodeY), width: +get(node, this.nodeWidthProperty, this.defaultNodeWidth), height: +get(node, this.nodeHeightProperty, this.defaultNodeHeight), type: get(node, this.nodeTypeProperty, this.defaultNodeType), fillColor, strokeColor, strokeWidth: +get(node, this.nodeStrokeWidthProperty, this.defaultNodeStrokeWidth), label: get(node, this.nodeLabelProperty, this.defaultNodeLabel), labelFillColor, labelStrokeColor, labelStrokeWidth: +get(node, this.nodeLabelStrokeWidthProperty, this.defaultNodeLabelStrokeWidth), labelFontSize: +get(node, this.nodeLabelFontSizeProperty, this.defaultNodeLabelFontSize), labelFontFamily: get(node, this.nodeLabelFontFamilyProperty, this.defaultNodeLabelFontFamily), inEdges: [], outEdges: [], d: node } }) const indices = new Map(vertices.map(({u}, i) => [u, i])) const edges = get(data, this.graphLinksProperty) .filter((link) => get(link, this.linkVisibilityProperty, this.defaultLinkVisibility)) .filter((link) => { const u = get(link, this.linkSourceProperty).toString() const v = get(link, this.linkTargetProperty).toString() return indices.has(u) && indices.has(v) }) .map((link) => { const u = get(link, this.linkSourceProperty).toString() const v = get(link, this.linkTargetProperty).toString() const strokeColor = d3.color(get(link, this.linkStrokeColorProperty, this.defaultLinkStrokeColor)) strokeColor.opacity = +get(link, this.linkStrokeOpacityProperty, this.defaultLinkStrokeOpacity) const labelFillColor = d3.color(get(link, this.linkLabelFillColorProperty, this.defaultLinkLabelFillColor)) labelFillColor.opacity = +get(link, this.linkLabelFillOpacityProperty, this.defaultLinkLabelFillOpacity) const labelStrokeColor = d3.color(get(link, this.linkLabelStrokeColorProperty, this.defaultLinkLabelStrokeColor)) labelStrokeColor.opacity = +get(link, this.linkLabelStrokeOpacityProperty, this.defaultLinkLabelStrokeOpacity) const du = vertices[indices.get(u)] const dv = vertices[indices.get(v)] const newPoints = [[du.x, du.y]] for (const [x, y] of get(link, this.linkBendsProperty, [])) { newPoints.push([x, y]) } newPoints.push([dv.x, dv.y]) const points = preservePos && p.prevData.edges.has(u) && p.prevData.edges.get(u).has(v) ? p.prevData.edges.get(u).get(v).points : newPoints const edge = { u, v, points, type: get(link, this.linkTypeProperty, this.defaultLinkType), strokeColor, strokeWidth: +get(link, this.linkStrokeWidthProperty, this.defaultLinkStrokeWidth), sourceMarkerShape: get(link, this.linkSourceMarkerShapeProperty, this.defaultLinkSourceMarkerShape), sourceMarkerSize: +get(link, this.linkSourceMarkerSizeProperty, this.defaultLinkSourceMarkerSize), targetMarkerShape: get(link, this.linkTargetMarkerShapeProperty, this.defaultLinkTargetMarkerShape), targetMarkerSize: +get(link, this.linkTargetMarkerSizeProperty, this.defaultLinkTargetMarkerSize), label: get(link, this.linkLabelProperty, this.defaultLinkLabel), labelFillColor, labelStrokeColor, labelStrokeWidth: +get(link, this.linkLabelStrokeWidthProperty, this.defaultLinkLabelStrokeWidth), labelFontSize: +get(link, this.linkLabelFontSizeProperty, this.defaultLinkLabelFontSize), labelFontFamily: get(link, this.linkLabelFontFamilyProperty, this.defaultLinkLabelFontFamily), d: link } du.outEdges.push(edge) dv.inEdges.push(edge) return edge }) p.data = { vertexIds: vertices.map(({u}) => u), vertices: new Map(vertices.map((vertex) => [vertex.u, vertex])), edgeIds: edges.map(({u, v}) => [u, v]), edges: new Map(vertices.map((vertex) => [vertex.u, new Map()])) } for (const edge of edges) { p.data.edges.get(edge.u).set(edge.v, edge) } this.onLayout(p.data, preservePos) for (const [u, v] of p.data.edgeIds) { const edge = p.data.edges.get(u).get(v) const du = p.data.vertices.get(u) const dv = p.data.vertices.get(v) adjustEdge(edge, du, dv) } p.layout = diff(p.prevData, p.data) p.layoutTime = new Date() if (this.autoCentering) { this.center() } return this } onLayout () { } invalidate () { privates.get(this).invalidate = true } get autoUpdate () { return !this.hasAttribute('no-auto-update') } set autoUpdate (value) { if (value) { this.removeAttribute('no-auto-update') } else { this.setAttribute('no-auto-update', '') } } get autoCentering () { return !this.hasAttribute('no-auto-centering') } set autoCentering (value) { if (value) { this.removeAttribute('no-auto-centering') } else { this.setAttribute('no-auto-centering', '') } } get canZoom () { return !this.hasAttribute('no-zoom') } set canZoom (value) { if (value) { this.removeAttribute('no-zoom') } else { this.setAttribute('no-zoom', '') } } get canDragNode () { return !this.hasAttribute('no-drag-node') } set canDragNode (value) { if (value) { this.removeAttribute('no-drag-node') } else { this.setAttribute('no-drag-node', '') } } get src () { return getter(this, 'src', null) } set src (value) { this.setAttribute('src', value) } get width () { return getter(this, 'width', 300) } set width (value) { this.setAttribute('width', value) } get height () { return getter(this, 'height', 150) } set height (value) { this.setAttribute('height', value) } get transitionDuration () { return getter(this, 'transition-duration', 0) } set transitionDuration (value) { this.setAttribute('transition-duration', value) } get graphNodesProperty () { return getter(this, 'graph-nodes-property', 'nodes') } set graphNodesProperty (value) { this.setAttribute('graph-nodes-property', value) } get graphLinksProperty () { return getter(this, 'graph-links-property', 'links') } set graphLinksProperty (value) { this.setAttribute('graph-links-property', value) } get nodeIdProperty () { return getter(this, 'node-id-property', '$index') } set nodeIdProperty (value) { this.setAttribute('node-id-property', value) } get nodeXProperty () { return getter(this, 'node-x-property', 'x') } set nodeXProperty (value) { this.setAttribute('node-x-property', value) } get nodeYProperty () { return getter(this, 'node-y-property', 'y') } set nodeYProperty (value) { this.setAttribute('node-y-property', value) } get nodeWidthProperty () { return getter(this, 'node-width-property', 'width') } set nodeWidthProperty (value) { this.setAttribute('node-width-property', value) } get nodeHeightProperty () { return getter(this, 'node-height-property', 'height') } set nodeHeightProperty (value) { this.setAttribute('node-height-property', value) } get nodeFillColorProperty () { return getter(this, 'node-fill-color-property', 'fillColor') } set nodeFillColorProperty (value) { this.setAttribute('node-fill-color-property', value) } get nodeFillOpacityProperty () { return getter(this, 'node-fill-opacity-property', 'fillOpacity') } set nodeFillOpacityProperty (value) { this.setAttribute('node-fill-opacity-property', value) } get nodeStrokeColorProperty () { return getter(this, 'node-stroke-color-property', 'strokeColor') } set nodeStrokeColorProperty (value) { this.setAttribute('node-stroke-color-property', value) } get nodeStrokeOpacityProperty () { return getter(this, 'node-stroke-opacity-property', 'strokeOpacity') } set nodeStrokeOpacityProperty (value) { this.setAttribute('node-stroke-opacity-property', value) } get nodeStrokeWidthProperty () { return getter(this, 'node-stroke-width-property', 'strokeWidth') } set nodeStrokeWidthProperty (value) { this.setAttribute('node-stroke-width-property', value) } get nodeTypeProperty () { return getter(this, 'node-type-property', 'type') } set nodeTypeProperty (value) { this.setAttribute('node-type-property', value) } get nodeVisibilityProperty () { return getter(this, 'node-visibility-property', 'visibility') } set nodeVisibilityProperty (value) { this.setAttribute('node-visibility-property', value) } get nodeLabelProperty () { return getter(this, 'node-label-property', 'label') } set nodeLabelProperty (value) { this.setAttribute('node-label-property', value) } get nodeLabelFillColorProperty () { return getter(this, 'node-label-fill-color-property', 'labelFillColor') } set nodeLabelFillColorProperty (value) { this.setAttribute('node-label-fill-color-property', value) } get nodeLabelFillOpacityProperty () { return getter(this, 'node-label-fill-opacity-property', 'labelFillOpacity') } set nodeLabelFillOpacityProperty (value) { this.setAttribute('node-label-fill-opacity-property', value) } get nodeLabelStrokeColorProperty () { return getter(this, 'node-label-stroke-color-property', 'labelStrokeColor') } set nodeLabelStrokeColorProperty (value) { this.setAttribute('node-label-stroke-color-property', value) } get nodeLabelStrokeOpacityProperty () { return getter(this, 'node-label-stroke-opacity-property', 'labelStrokeOpacity') } set nodeLabelStrokeOpacityProperty (value) { this.setAttribute('node-label-stroke-opacity-property', value) } get nodeLabelStrokeWidthProperty () { return getter(this, 'node-label-stroke-width-property', 'labelStrokeWidth') } set nodeLabelStrokeWidthProperty (value) { this.setAttribute('node-label-stroke-width-property', value) } get nodeLabelFontSizeProperty () { return getter(this, 'node-label-font-size-property', 'labelFontSize') } set nodeLabelFontSizeProperty (value) { this.setAttribute('node-label-font-size-property', value) } get nodeLabelFontFamilyProperty () { return getter(this, 'node-label-font-family-property', 'labelFontFamily') } set nodeLabelFontFamilyProperty (value) { this.setAttribute('node-label-font-family-property', value) } get linkSourceProperty () { return getter(this, 'link-source-property', 'source') } set linkSourceProperty (value) { this.setAttribute('link-source-property', value) } get linkTargetProperty () { return getter(this, 'link-target-property', 'target') } set linkTargetProperty (value) { this.setAttribute('link-target-property', value) } get linkBendsProperty () { return getter(this, 'link-bends-property', 'bends') } set linkBendsProperty (value) { this.setAttribute('link-bends-property', value) } get linkStrokeColorProperty () { return getter(this, 'link-stroke-color-property', 'strokeColor') } set linkStrokeColorProperty (value) { this.setAttribute('link-stroke-color-property', value) } get linkStrokeOpacityProperty () { return getter(this, 'link-stroke-opacity-property', 'strokeOpacity') } set linkStrokeOpacityProperty (value) { this.setAttribute('link-stroke-opacity-property', value) } get linkStrokeWidthProperty () { return getter(this, 'link-stroke-width-property', 'strokeWidth') } set linkStrokeWidthProperty (value) { this.setAttribute('link-stroke-width-property', value) } get linkTypeProperty () { return getter(this, 'link-type-property', 'type') } set linkTypeProperty (value) { this.setAttribute('link-type-property', value) } get linkVisibilityProperty () { return getter(this, 'link-visibility-property', 'visibility') } set linkVisibilityProperty (value) { this.setAttribute('link-visibility-property', value) } get linkSourceMarkerShapeProperty () { return getter(this, 'link-source-marker-shape-property', 'sourceMarkerShape') } set linkSourceMarkerShapeProperty (value) { this.setAttribute('link-source-marker-shape-property', value) } get linkSourceMarkerSizeProperty () { return getter(this, 'link-source-marker-size-property', 'sourceMarkerSize') } set linkSourceMarkerSizeProperty (value) { this.setAttribute('link-source-marker-size-property', value) } get linkTargetMarkerShapeProperty () { return getter(this, 'link-target-marker-shape-property', 'targetMarkerShape') } set linkTargetMarkerShapeProperty (value) { this.setAttribute('link-target-marker-shape-property', value) } get linkTargetMarkerSizeProperty () { return getter(this, 'link-target-marker-size-property', 'targetMarkerSize') } set linkTargetMarkerSizeProperty (value) { this.setAttribute('link-target-marker-size-property', value) } get linkLabelProperty () { return getter(this, 'link-label-property', 'label') } set linkLabelProperty (value) { this.setAttribute('link-label-property', value) } get linkLabelFillColorProperty () { return getter(this, 'link-label-fill-color-property', 'labelFillColor') } set linkLabelFillColorProperty (value) { this.setAttribute('link-label-fill-color-property', value) } get linkLabelFillOpacityProperty () { return getter(this, 'link-label-fill-opacity-property', 'labelFillOpacity') } set linkLabelFillOpacityProperty (value) { this.setAttribute('link-label-fill-opacity-property', value) } get linkLabelStrokeColorProperty () { return getter(this, 'link-label-stroke-color-property', 'labelStrokeColor') } set linkLabelStrokeColorProperty (value) { this.setAttribute('link-label-stroke-color-property', value) } get linkLabelStrokeOpacityProperty () { return getter(this, 'link-label-stroke-opacity-property', 'labelStrokeOpacity') } set linkLabelStrokeOpacityProperty (value) { this.setAttribute('link-label-stroke-opacity-property', value) } get linkLabelStrokeWidthProperty () { return getter(this, 'link-label-stroke-width-property', 'labelStrokeWidth') } set linkLabelStrokeWidthProperty (value) { this.setAttribute('link-label-stroke-width-property', value) } get linkLabelFontSizeProperty () { return getter(this, 'link-label-font-size-property', 'labelFontSize') } set linkLabelFontSizeProperty (value) { this.setAttribute('link-label-font-size-property', value) } get linkLabelFontFamilyProperty () { return getter(this, 'link-label-font-family-property', 'labelFontFamily') } set linkLabelFontFamilyProperty (value) { this.setAttribute('link-label-font-family-property', value) } get defaultNodeX () { return getter(this, 'default-node-x', 0) } set defaultNodeX (value) { this.setAttribute('default-node-x', value) } get defaultNodeY () { return getter(this, 'default-node-y', 0) } set defaultNodeY (value) { this.setAttribute('default-node-y', value) } get defaultNodeWidth () { return getter(this, 'default-node-width', 10) } set defaultNodeWidth (value) { this.setAttribute('default-node-width', value) } get defaultNodeHeight () { return getter(this, 'default-node-height', 10) } set defaultNodeHeight (value) { this.setAttribute('default-node-height', value) } get defaultNodeFillColor () { return getter(this, 'default-node-fill-color', '#fff') } set defaultNodeFillColor (value) { this.setAttribute('default-node-fill-color', value) } get defaultNodeFillOpacity () { return getter(this, 'default-node-fill-opacity', 1) } set defaultNodeFillOpacity (value) { this.setAttribute('default-node-fill-opacity', value) } get defaultNodeStrokeColor () { return getter(this, 'default-node-stroke-color', '#000') } set defaultNodeStrokeColor (value) { this.setAttribute('default-node-stroke-color', value) } get defaultNodeStrokeOpacity () { return getter(this, 'default-node-stroke-opacity', 1) } set defaultNodeStrokeOpacity (value) { this.setAttribute('default-node-stroke-opacity', value) } get defaultNodeStrokeWidth () { return getter(this, 'default-node-stroke-width', 1) } set defaultNodeStrokeWidth (value) { this.setAttribute('default-node-stroke-width', value) } get defaultNodeType () { return getter(this, 'default-node-type', 'circle') } set defaultNodeType (value) { this.setAttribute('default-node-type', value) } get defaultNodeVisibility () { return getter(this, 'default-node-visibility', true) } set defaultNodeVisibility (value) { this.setAttribute('default-node-visibility', value) } get defaultNodeLabel () { return getter(this, 'default-node-label', '') } set defaultNodeLabel (value) { this.setAttribute('default-node-label', value) } get defaultNodeLabelFillColor () { return getter(this, 'default-node-label-fill-color', '#000') } set defaultNodeLabelFillColor (value) { this.setAttribute('default-node-label-fill-color', value) } get defaultNodeLabelFillOpacity () { return getter(this, 'default-node-label-fill-opacity', 1) } set defaultNodeLabelFillOpacity (value) { this.setAttribute('default-node-label-fill-opacity', value) } get defaultNodeLabelStrokeColor () { return getter(this, 'default-node-label-stroke-color', '#fff') } set defaultNodeLabelStrokeColor (value) { this.setAttribute('default-node-label-stroke-color', value) } get defaultNodeLabelStrokeOpacity () { return getter(this, 'default-node-label-stroke-opacity', 1) } set defaultNodeLabelStrokeOpacity (value) { this.setAttribute('default-node-label-stroke-opacity', value) } get defaultNodeLabelStrokeWidth () { return getter(this, 'default-node-label-stroke-width', 0) } set defaultNodeLabelStrokeWidth (value) { this.setAttribute('default-node-label-stroke-width', value) } get defaultNodeLabelFontSize () { return getter(this, 'default-node-label-font-size', 10) } set defaultNodeLabelFontSize (value) { this.setAttribute('default-node-label-font-size', value) } get defaultNodeLabelFontFamily () { return getter(this, 'default-node-label-font-family', 'serif') } set defaultNodeLabelFontFamily (value) { this.setAttribute('default-node-label-font-family', value) } get defaultLinkStrokeColor () { return getter(this, 'default-link-stroke-color', '#000') } set defaultLinkStrokeColor (value) { this.setAttribute('default-link-stroke-color', value) } get defaultLinkStrokeOpacity () { return getter(this, 'default-link-stroke-opacity', 1) } set defaultLinkStrokeOpacity (value) { this.setAttribute('default-link-stroke-opacity', value) } get defaultLinkStrokeWidth () { return getter(this, 'default-link-stroke-width', 1) } set defaultLinkStrokeWidth (value) { this.setAttribute('default-link-stroke-width', value) } get defaultLinkType () { return getter(this, 'default-link-type', 'line') } set defaultLinkType (value) { this.setAttribute('default-link-type', value) } get defaultLinkVisibility () { return getter(this, 'default-link-visibility', true) } set defaultLinkVisibility (value) { this.setAttribute('default-link-visibility', value) } get defaultLinkSourceMarkerShape () { return getter(this, 'default-link-source-marker-shape', 'none') } set defaultLinkSourceMarkerShape (value) { this.setAttribute('default-link-source-marker-shape', value) } get defaultLinkSourceMarkerSize () { return getter(this, 'default-link-source-marker-size', 5) } set defaultLinkSourceMarkerSize (value) { this.setAttribute('default-link-source-marker-size', value) } get defaultLinkTargetMarkerShape () { return getter(this, 'default-link-target-marker-shape', 'none') } set defaultLinkTargetMarkerShape (value) { this.setAttribute('default-link-target-marker-shape', value) } get defaultLinkTargetMarkerSize () { return getter(this, 'default-link-target-marker-size', 5) } set defaultLinkTargetMarkerSize (value) { this.setAttribute('default-link-target-marker-size', value) } get defaultLinkLabel () { return getter(this, 'default-link-label', '') } set defaultLinkLabel (value) { this.setAttribute('default-link-label', value) } get defaultLinkLabelFillColor () { return getter(this, 'default-link-label-fill-color', '#000') } set defaultLinkLabelFillColor (value) { this.setAttribute('default-link-label-fill-color', value) } get defaultLinkLabelFillOpacity () { return getter(this, 'default-link-label-fill-opacity', 1) } set defaultLinkLabelFillOpacity (value) { this.setAttribute('default-link-label-fill-opacity', value) } get defaultLinkLabelStrokeColor () { return getter(this, 'default-link-label-stroke-color', '#fff') } set defaultLinkLabelStrokeColor (value) { this.setAttribute('default-link-label-stroke-color', value) } get defaultLinkLabelStrokeOpacity () { return getter(this, 'default-link-label-stroke-opacity', 1) } set defaultLinkLabelStrokeOpacity (value) { this.setAttribute('default-link-label-stroke-opacity', value) } get defaultLinkLabelStrokeWidth () { return getter(this, 'default-link-label-stroke-width', 0) } set defaultLinkLabelStrokeWidth (value) { this.setAttribute('default-link-label-stroke-width', value) } get defaultLinkLabelFontSize () { return getter(this, 'default-link-label-font-size', 10) } set defaultLinkLabelFontSize (value) { this.setAttribute('default-link-label-font-size', value) } get defaultLinkLabelFontFamily () { return getter(this, 'default-link-label-font-family', 'serif') } set defaultLinkLabelFontFamily (value) { this.setAttribute('default-link-label-font-family', value) } get data () { return privates.get(this).originalData } } window.customElements.define('eg-renderer', EgRendererElement)
Add nodeClick event
src/index.js
Add nodeClick event
<ide><path>rc/index.js <ide> p.highlightedVertex = null <ide> } else { <ide> p.canvas.style.cursor = 'default' <add> } <add> }) <add> <add> p.canvas.addEventListener('click', (event) => { <add> if (event.region) { <add> this.dispatchEvent(new window.CustomEvent('nodeclick', { <add> detail: { <add> id: event.region <add> } <add> })) <ide> } <ide> }) <ide> }
Java
apache-2.0
1128027c9821c3e79cc24b752bd61f6dd4ef576a
0
suncycheng/intellij-community,hurricup/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,slisson/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,adedayo/intellij-community,vladmm/intellij-community,adedayo/intellij-community,xfournet/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,caot/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,izonder/intellij-community,amith01994/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,diorcety/intellij-community,apixandru/intellij-community,samthor/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,kdwink/intellij-community,caot/intellij-community,fnouama/intellij-community,diorcety/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,asedunov/intellij-community,jagguli/intellij-community,semonte/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,FHannes/intellij-community,diorcety/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,apixandru/intellij-community,kool79/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,vladmm/intellij-community,fnouama/intellij-community,allotria/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,supersven/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,supersven/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,fnouama/intellij-community,amith01994/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,slisson/intellij-community,amith01994/intellij-community,fitermay/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,semonte/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,allotria/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,diorcety/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,holmes/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,jagguli/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,allotria/intellij-community,apixandru/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,kool79/intellij-community,allotria/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,kdwink/intellij-community,semonte/intellij-community,asedunov/intellij-community,supersven/intellij-community,signed/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,izonder/intellij-community,slisson/intellij-community,signed/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,kool79/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,signed/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,FHannes/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,ibinti/intellij-community,xfournet/intellij-community,asedunov/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,slisson/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,signed/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,da1z/intellij-community,supersven/intellij-community,clumsy/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,kool79/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,adedayo/intellij-community,xfournet/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,signed/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,ryano144/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,signed/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,allotria/intellij-community,ibinti/intellij-community,kdwink/intellij-community,robovm/robovm-studio,slisson/intellij-community,ibinti/intellij-community,blademainer/intellij-community,clumsy/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,semonte/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,samthor/intellij-community,semonte/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,caot/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,signed/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,izonder/intellij-community,robovm/robovm-studio,holmes/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,kdwink/intellij-community,clumsy/intellij-community,izonder/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,allotria/intellij-community,xfournet/intellij-community,fnouama/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,signed/intellij-community,holmes/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,hurricup/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,supersven/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,ibinti/intellij-community,vladmm/intellij-community,dslomov/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,da1z/intellij-community,izonder/intellij-community,xfournet/intellij-community,clumsy/intellij-community,caot/intellij-community,FHannes/intellij-community,fitermay/intellij-community,fitermay/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,asedunov/intellij-community,samthor/intellij-community,allotria/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,robovm/robovm-studio,kool79/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,kool79/intellij-community,Distrotech/intellij-community,holmes/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,samthor/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,amith01994/intellij-community,caot/intellij-community,da1z/intellij-community,suncycheng/intellij-community,allotria/intellij-community,diorcety/intellij-community,hurricup/intellij-community,FHannes/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,apixandru/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,hurricup/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,izonder/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,fitermay/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,holmes/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,signed/intellij-community,holmes/intellij-community,semonte/intellij-community,retomerz/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,adedayo/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,holmes/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,da1z/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,supersven/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,amith01994/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,caot/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,asedunov/intellij-community,ibinti/intellij-community,da1z/intellij-community,robovm/robovm-studio,xfournet/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,signed/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,clumsy/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,asedunov/intellij-community,kdwink/intellij-community,fitermay/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,caot/intellij-community,gnuhub/intellij-community,samthor/intellij-community,clumsy/intellij-community,blademainer/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,slisson/intellij-community,dslomov/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,caot/intellij-community,samthor/intellij-community,nicolargo/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,signed/intellij-community,pwoodworth/intellij-community
/* * Copyright 2000-2014 JetBrains s.r.o. * * 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.intellij.ui.components; import com.intellij.icons.AllIcons; import com.intellij.openapi.Disposable; import com.intellij.openapi.ui.JBMenuItem; import com.intellij.openapi.ui.JBPopupMenu; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.Weighted; import com.intellij.openapi.wm.IdeGlassPane; import com.intellij.openapi.wm.IdeGlassPaneUtil; import com.intellij.ui.ScreenUtil; import com.intellij.util.ui.UIUtil; import javax.swing.*; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.util.HashSet; import java.util.Set; public class JBOptionButton extends JButton implements MouseMotionListener, Weighted { private static final Insets myDownIconInsets = new Insets(0, 6, 0, 4); private Rectangle myMoreRec; private Rectangle myMoreRecMouse; private Action[] myOptions; private JPopupMenu myUnderPopup; private JPopupMenu myAbovePopup; private boolean myPopupIsShowing; private String myOptionTooltipText; private Set<OptionInfo> myOptionInfos = new HashSet<OptionInfo>(); private boolean myOkToProcessDefaultMnemonics = true; private IdeGlassPane myGlassPane; private final Disposable myDisposable = Disposer.newDisposable(); public JBOptionButton(Action action, Action[] options) { super(action); myOptions = options; myMoreRec = new Rectangle(0, 0, AllIcons.General.ArrowDown.getIconWidth(), AllIcons.General.ArrowDown.getIconHeight()); myUnderPopup = fillMenu(true); myAbovePopup = fillMenu(false); enableEvents(AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK); } @Override public void addNotify() { super.addNotify(); if (!ScreenUtil.isStandardAddRemoveNotify(this)) return; myGlassPane = IdeGlassPaneUtil.find(this); if (myGlassPane != null) { myGlassPane.addMouseMotionPreprocessor(this, myDisposable); } } @Override public void removeNotify() { super.removeNotify(); if (!ScreenUtil.isStandardAddRemoveNotify(this)) return; Disposer.dispose(myDisposable); } @Override public double getWeight() { return 0.5; } @Override public void mouseDragged(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { final MouseEvent event = SwingUtilities.convertMouseEvent(e.getComponent(), e, getParent()); final boolean insideRec = getBounds().contains(event.getPoint()); boolean buttonsNotPressed = (e.getModifiersEx() & (InputEvent.BUTTON1_DOWN_MASK | InputEvent.BUTTON2_DOWN_MASK | InputEvent.BUTTON3_DOWN_MASK)) == 0; if (!myPopupIsShowing && insideRec && buttonsNotPressed) { showPopup(null, false); } else if (myPopupIsShowing && !insideRec) { final Component over = SwingUtilities.getDeepestComponentAt(e.getComponent(), e.getX(), e.getY()); JPopupMenu popup = myUnderPopup.isShowing() ? myUnderPopup : myAbovePopup; if (over != null && popup.isShowing()) { final Rectangle rec = new Rectangle(popup.getLocationOnScreen(), popup.getSize()); int delta = 15; rec.x -= delta; rec.width += delta * 2; rec.y -= delta; rec.height += delta * 2; final Point eventPoint = e.getPoint(); SwingUtilities.convertPointToScreen(eventPoint, e.getComponent()); if (rec.contains(eventPoint)) { return; } } closePopup(); } } @Override public Dimension getPreferredSize() { final Dimension size = super.getPreferredSize(); size.width += (myMoreRec.width + myDownIconInsets.left + myDownIconInsets.right); size.height += (myDownIconInsets.top + myDownIconInsets.bottom); return size; } @Override public void doLayout() { super.doLayout(); Insets insets = getInsets(); myMoreRec.x = getSize().width - myMoreRec.width - insets.right + 8; myMoreRec.y = (getHeight() / 2 - myMoreRec.height / 2); myMoreRecMouse = new Rectangle(myMoreRec.x - 8, 0, getWidth() - myMoreRec.x, getHeight()); } @Override public String getToolTipText(MouseEvent event) { if (myMoreRec.x < event.getX()) { return myOptionTooltipText; } else { return super.getToolTipText(event); } } @Override protected void processMouseEvent(MouseEvent e) { if (myMoreRecMouse.contains(e.getPoint())) { if (e.getID() == MouseEvent.MOUSE_PRESSED) { if (!myPopupIsShowing) { togglePopup(); } } } else { super.processMouseEvent(e); } } public void togglePopup() { if (myPopupIsShowing) { closePopup(); } else { showPopup(null, false); } } public void showPopup(final Action actionToSelect, final boolean ensureSelection) { if (myPopupIsShowing) return; myPopupIsShowing = true; final Point loc = getLocationOnScreen(); final Rectangle screen = ScreenUtil.getScreenRectangle(loc); final Dimension popupSize = myUnderPopup.getPreferredSize(); final Rectangle intersection = screen.intersection(new Rectangle(new Point(loc.x, loc.y + getHeight()), popupSize)); final boolean above = intersection.height < popupSize.height; int y = above ? getY() - popupSize.height : getY() + getHeight(); final JPopupMenu popup = above ? myAbovePopup : myUnderPopup; final Ref<PopupMenuListener> listener = new Ref<PopupMenuListener>(); listener.set(new PopupMenuListener() { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { if (popup != null && listener.get() != null) { popup.removePopupMenuListener(listener.get()); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { myPopupIsShowing = false; } }); } @Override public void popupMenuCanceled(PopupMenuEvent e) { } }); popup.addPopupMenuListener(listener.get()); popup.show(this, 0, y); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (popup == null || !popup.isShowing() || !myPopupIsShowing) return; Action selection = actionToSelect; if (selection == null && myOptions.length > 0 && ensureSelection) { selection = getAction(); } if (selection == null) return; final MenuElement[] elements = popup.getSubElements(); for (MenuElement eachElement : elements) { if (eachElement instanceof JMenuItem) { JMenuItem eachItem = (JMenuItem)eachElement; if (selection.equals(eachItem.getAction())) { final MenuSelectionManager mgr = MenuSelectionManager.defaultManager(); final MenuElement[] path = new MenuElement[2]; path[0] = popup; path[1] = eachItem; mgr.setSelectedPath(path); break; } } } } }); } public void closePopup() { myUnderPopup.setVisible(false); myAbovePopup.setVisible(false); } private JPopupMenu fillMenu(boolean under) { final JPopupMenu result = new JBPopupMenu(); if (under && myOptions.length > 0) { final JMenuItem mainAction = new JBMenuItem(getAction()); configureItem(getMenuInfo(getAction()), mainAction); result.add(mainAction); result.addSeparator(); } for (Action each : myOptions) { if (getAction() == each) continue; final OptionInfo info = getMenuInfo(each); final JMenuItem eachItem = new JBMenuItem(each); configureItem(info, eachItem); result.add(eachItem); } if (!under && myOptions.length > 0) { result.addSeparator(); final JMenuItem mainAction = new JBMenuItem(getAction()); configureItem(getMenuInfo(getAction()), mainAction); result.add(mainAction); } return result; } private void configureItem(OptionInfo info, JMenuItem eachItem) { eachItem.setText(info.myPlainText); if (info.myMnemonic >= 0) { eachItem.setMnemonic(info.myMnemonic); eachItem.setDisplayedMnemonicIndex(info.myMnemonicIndex); } myOptionInfos.add(info); } public boolean isOkToProcessDefaultMnemonics() { return myOkToProcessDefaultMnemonics; } public static class OptionInfo { String myPlainText; int myMnemonic; int myMnemonicIndex; JBOptionButton myButton; Action myAction; OptionInfo(String plainText, int mnemonic, int mnemonicIndex, JBOptionButton button, Action action) { myPlainText = plainText; myMnemonic = mnemonic; myMnemonicIndex = mnemonicIndex; myButton = button; myAction = action; } public String getPlainText() { return myPlainText; } public int getMnemonic() { return myMnemonic; } public int getMnemonicIndex() { return myMnemonicIndex; } public JBOptionButton getButton() { return myButton; } public Action getAction() { return myAction; } } private OptionInfo getMenuInfo(Action each) { final String text = (String)each.getValue(Action.NAME); int mnemonic = -1; int mnemonicIndex = -1; StringBuilder plainText = new StringBuilder(); for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); if (ch == '&' || ch == '_') { if (i + 1 < text.length()) { final char mnemonicsChar = text.charAt(i + 1); mnemonic = Character.toUpperCase(mnemonicsChar); mnemonicIndex = i; } continue; } plainText.append(ch); } return new OptionInfo(plainText.toString(), mnemonic, mnemonicIndex, this, each); } public Set<OptionInfo> getOptionInfos() { return myOptionInfos; } @Override protected void paintChildren(Graphics g) { super.paintChildren(g); boolean dark = UIUtil.isUnderDarcula(); int off = dark ? 6 : 0; AllIcons.General.ArrowDown.paintIcon(this, g, myMoreRec.x - off, myMoreRec.y); if (dark) return; final Insets insets = getInsets(); int y1 = myMoreRec.y - 2; int y2 = getHeight() - insets.bottom - 2; if (y1 < getInsets().top) { y1 = insets.top; } final int x = myMoreRec.x - 4; UIUtil.drawDottedLine(((Graphics2D)g), x, y1, x, y2, null, Color.darkGray); } public void setOptionTooltipText(String text) { myOptionTooltipText = text; } public void setOkToProcessDefaultMnemonics(boolean ok) { myOkToProcessDefaultMnemonics = ok; } }
platform/platform-api/src/com/intellij/ui/components/JBOptionButton.java
/* * Copyright 2000-2014 JetBrains s.r.o. * * 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.intellij.ui.components; import com.intellij.icons.AllIcons; import com.intellij.openapi.Disposable; import com.intellij.openapi.ui.JBMenuItem; import com.intellij.openapi.ui.JBPopupMenu; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.Weighted; import com.intellij.openapi.wm.IdeGlassPane; import com.intellij.openapi.wm.IdeGlassPaneUtil; import com.intellij.ui.ScreenUtil; import com.intellij.util.ui.UIUtil; import javax.swing.*; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.util.HashSet; import java.util.Set; public class JBOptionButton extends JButton implements MouseMotionListener, Weighted { private static final Insets myDownIconInsets = new Insets(0, 6, 0, 4); private Rectangle myMoreRec; private Rectangle myMoreRecMouse; private Action[] myOptions; private JPopupMenu myUnderPopup; private JPopupMenu myAbovePopup; private boolean myPopupIsShowing; private String myOptionTooltipText; private Set<OptionInfo> myOptionInfos = new HashSet<OptionInfo>(); private boolean myOkToProcessDefaultMnemonics = true; private IdeGlassPane myGlassPane; private final Disposable myDisposable = Disposer.newDisposable(); public JBOptionButton(Action action, Action[] options) { super(action); myOptions = options; myMoreRec = new Rectangle(0, 0, AllIcons.General.ArrowDown.getIconWidth(), AllIcons.General.ArrowDown.getIconHeight()); myUnderPopup = fillMenu(true); myAbovePopup = fillMenu(false); enableEvents(AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK); } @Override public void addNotify() { super.addNotify(); if (!ScreenUtil.isStandardAddRemoveNotify(this)) return; myGlassPane = IdeGlassPaneUtil.find(this); if (myGlassPane != null) { myGlassPane.addMouseMotionPreprocessor(this, myDisposable); } } @Override public void removeNotify() { super.removeNotify(); if (!ScreenUtil.isStandardAddRemoveNotify(this)) return; Disposer.dispose(myDisposable); } @Override public double getWeight() { return 0.5; } @Override public void mouseDragged(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { final MouseEvent event = SwingUtilities.convertMouseEvent(e.getComponent(), e, getParent()); final boolean insideRec = getBounds().contains(event.getPoint()); boolean buttonsNotPressed = (e.getModifiersEx() & (InputEvent.BUTTON1_DOWN_MASK | InputEvent.BUTTON2_DOWN_MASK | InputEvent.BUTTON3_DOWN_MASK)) == 0; if (!myPopupIsShowing && insideRec && buttonsNotPressed) { showPopup(null, false); } else if (myPopupIsShowing && !insideRec) { final Component over = SwingUtilities.getDeepestComponentAt(e.getComponent(), e.getX(), e.getY()); JPopupMenu popup = myUnderPopup.isShowing() ? myUnderPopup : myAbovePopup; if (over != null && popup.isShowing()) { final Rectangle rec = new Rectangle(popup.getLocationOnScreen(), popup.getSize()); int delta = 15; rec.x -= delta; rec.width += delta * 2; rec.y -= delta; rec.height += delta * 2; final Point eventPoint = e.getPoint(); SwingUtilities.convertPointToScreen(eventPoint, e.getComponent()); if (rec.contains(eventPoint)) { return; } } closePopup(); } } @Override public Dimension getPreferredSize() { final Dimension size = super.getPreferredSize(); size.width += (myMoreRec.width + myDownIconInsets.left + myDownIconInsets.right); size.height += (myDownIconInsets.top + myDownIconInsets.bottom); return size; } @Override public void doLayout() { super.doLayout(); Insets insets = getInsets(); myMoreRec.x = getSize().width - myMoreRec.width - insets.right + 8; myMoreRec.y = (getHeight() / 2 - myMoreRec.height / 2); myMoreRecMouse = new Rectangle(myMoreRec.x - 8, 0, getWidth() - myMoreRec.x, getHeight()); } @Override public String getToolTipText(MouseEvent event) { if (myMoreRec.x < event.getX()) { return myOptionTooltipText; } else { return super.getToolTipText(event); } } @Override protected void processMouseEvent(MouseEvent e) { if (myMoreRecMouse.contains(e.getPoint())) { if (e.getID() == MouseEvent.MOUSE_PRESSED) { if (!myPopupIsShowing) { togglePopup(); } } } else { super.processMouseEvent(e); } } public void togglePopup() { if (myPopupIsShowing) { closePopup(); } else { showPopup(null, false); } } public void showPopup(final Action actionToSelect, final boolean ensureSelection) { if (myPopupIsShowing) return; myPopupIsShowing = true; final Point loc = getLocationOnScreen(); final Rectangle screen = ScreenUtil.getScreenRectangle(loc); final Dimension popupSize = myUnderPopup.getPreferredSize(); final Rectangle intersection = screen.intersection(new Rectangle(new Point(loc.x, loc.y + getHeight()), popupSize)); final boolean above = intersection.height < popupSize.height; int y = above ? getY() - popupSize.height : getY() + getHeight(); final JPopupMenu popup = above ? myAbovePopup : myUnderPopup; final Ref<PopupMenuListener> listener = new Ref<PopupMenuListener>(); listener.set(new PopupMenuListener() { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { if (popup != null && listener.get() != null) { popup.removePopupMenuListener(listener.get()); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { myPopupIsShowing = false; } }); } @Override public void popupMenuCanceled(PopupMenuEvent e) { } }); popup.addPopupMenuListener(listener.get()); popup.show(this, 0, y); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (popup == null || !popup.isShowing() || !myPopupIsShowing) return; Action selection = actionToSelect; if (selection == null && myOptions.length > 0 && ensureSelection) { selection = getAction(); } if (selection == null) return; final MenuElement[] elements = popup.getSubElements(); for (MenuElement eachElement : elements) { if (eachElement instanceof JMenuItem) { JMenuItem eachItem = (JMenuItem)eachElement; if (selection.equals(eachItem.getAction())) { final MenuSelectionManager mgr = MenuSelectionManager.defaultManager(); final MenuElement[] path = new MenuElement[2]; path[0] = popup; path[1] = eachItem; mgr.setSelectedPath(path); break; } } } } }); } public void closePopup() { myUnderPopup.setVisible(false); myAbovePopup.setVisible(false); } private JPopupMenu fillMenu(boolean under) { final JPopupMenu result = new JBPopupMenu(); if (under && myOptions.length > 0) { final JMenuItem mainAction = new JBMenuItem(getAction()); configureItem(getMenuInfo(getAction()), mainAction); result.add(mainAction); result.addSeparator(); } for (Action each : myOptions) { if (getAction() == each) continue; final OptionInfo info = getMenuInfo(each); final JMenuItem eachItem = new JBMenuItem(each); configureItem(info, eachItem); result.add(eachItem); } if (!under && myOptions.length > 0) { result.addSeparator(); final JMenuItem mainAction = new JBMenuItem(getAction()); configureItem(getMenuInfo(getAction()), mainAction); result.add(mainAction); } return result; } private void configureItem(OptionInfo info, JMenuItem eachItem) { eachItem.setText(info.myPlainText); if (info.myMnemonic >= 0) { eachItem.setMnemonic(info.myMnemonic); eachItem.setDisplayedMnemonicIndex(info.myMnemonicIndex); } myOptionInfos.add(info); } public boolean isOkToProcessDefaultMnemonics() { return myOkToProcessDefaultMnemonics; } public static class OptionInfo { String myPlainText; int myMnemonic; int myMnemonicIndex; JBOptionButton myButton; Action myAction; OptionInfo(String plainText, int mnemonic, int mnemonicIndex, JBOptionButton button, Action action) { myPlainText = plainText; myMnemonic = mnemonic; myMnemonicIndex = mnemonicIndex; myButton = button; myAction = action; } public String getPlainText() { return myPlainText; } public int getMnemonic() { return myMnemonic; } public int getMnemonicIndex() { return myMnemonicIndex; } public JBOptionButton getButton() { return myButton; } public Action getAction() { return myAction; } } private OptionInfo getMenuInfo(Action each) { final String text = (String)each.getValue(Action.NAME); int mnemonic = -1; int mnemonicIndex = -1; StringBuilder plainText = new StringBuilder(); for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); if (ch == '&' || ch == '_') { if (i + 1 < text.length()) { final char mnemonicsChar = text.charAt(i + 1); mnemonic = Character.toUpperCase(mnemonicsChar); mnemonicIndex = i; } continue; } plainText.append(ch); } return new OptionInfo(plainText.toString(), mnemonic, mnemonicIndex, this, each); } public Set<OptionInfo> getOptionInfos() { return myOptionInfos; } @Override protected void paintChildren(Graphics g) { super.paintChildren(g); boolean dark = UIUtil.isUnderDarcula(); int off = dark ? 6 : 0; AllIcons.General.ArrowDown.paintIcon(this, g, myMoreRec.x - off, myMoreRec.y); if (dark) return; int y1 = myMoreRec.y - 2; int y2 = myMoreRec.y + myMoreRec.height + 2; final Insets insets = getInsets(); if (y1 < getInsets().top) { y1 = insets.top; } if (y2 > getHeight() - insets.bottom) { y2 = getHeight() - insets.bottom; } final int x = myMoreRec.x - 4; UIUtil.drawDottedLine(((Graphics2D)g), x, y1, x, y2, null, Color.darkGray); } public void setOptionTooltipText(String text) { myOptionTooltipText = text; } public void setOkToProcessDefaultMnemonics(boolean ok) { myOkToProcessDefaultMnemonics = ok; } }
taller dotted separator
platform/platform-api/src/com/intellij/ui/components/JBOptionButton.java
taller dotted separator
<ide><path>latform/platform-api/src/com/intellij/ui/components/JBOptionButton.java <ide> int off = dark ? 6 : 0; <ide> AllIcons.General.ArrowDown.paintIcon(this, g, myMoreRec.x - off, myMoreRec.y); <ide> if (dark) return; <add> <add> final Insets insets = getInsets(); <ide> int y1 = myMoreRec.y - 2; <del> int y2 = myMoreRec.y + myMoreRec.height + 2; <del> <del> final Insets insets = getInsets(); <add> int y2 = getHeight() - insets.bottom - 2; <ide> <ide> if (y1 < getInsets().top) { <ide> y1 = insets.top; <ide> } <ide> <del> if (y2 > getHeight() - insets.bottom) { <del> y2 = getHeight() - insets.bottom; <del> } <del> <ide> final int x = myMoreRec.x - 4; <ide> UIUtil.drawDottedLine(((Graphics2D)g), x, y1, x, y2, null, Color.darkGray); <ide> }
Java
apache-2.0
a361d8856132444ceda5e48f5ab207049ae2970e
0
cosmocode/cosmocode-commons
/** * Copyright 2010 CosmoCode GmbH * * 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 de.cosmocode.commons; import java.text.Collator; import java.util.Collection; import java.util.Locale; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import com.google.common.collect.Ordering; import de.cosmocode.commons.validation.Rule; /** * Utility class inspired by {@link StringUtils}, * providing {@link String} related helper methods. * * @author Willi Schoenborn */ public final class Strings { /** * Natural ordering on {@link String}s which trims comparee * first using {@link TrimMode#NULL} and puts nulls to the end. */ public static final Ordering<String> CASE_SENSITIVE = Ordering.natural().nullsLast().onResultOf(TrimMode.NULL); /** * A case-insensitive version of {@link Strings#CASE_SENSITIVE}. */ public static final Ordering<String> CASE_INSENSITIVE = Ordering.from(String.CASE_INSENSITIVE_ORDER). nullsLast().onResultOf(TrimMode.NULL); public static final String DEFAULT_DELIMITER = " "; private static final Object[] EMPTY_ARRAY = {}; /** * Prevent instantiation. */ private Strings() { } /** * Creates an {@link Ordering} which uses a {@link Collator} based * on the given {@link Locale} to sort Strings. * * @param locale the desired locale * @return a new {@link Ordering} backed by a {@link Collator} * @throws NullPointerException if locale is null */ public static Ordering<String> orderBy(@Nonnull Locale locale) { return new CollatorOrdering(locale); } /** * Returns a Function able to convert strings into their lowercase counterparts * using {@link String#toLowerCase()}. * * <p> * The returned function handles null by returning them. * </p> * * @since 1.9 * @return a function covnerting strings to lowercase */ public static Function<String, String> toLowerCase() { return StringLowerCaseFunction.INSTANCE; } /** * Returns a Function able to convert strings into their lowercase counterparts * using {@link String#toLowerCase(Locale)}. * * <p> * The returned function handles null by returning them. * </p> * * @since 1.9 * @param locale the locale being used to convert to lowercase * @return a function converting strings to lowercase * @throws NullPointerException if locale is null */ public static Function<String, String> toLowerCase(@Nonnull Locale locale) { return new StringLocaleAwareLowerCaseFunction(locale); } /** * Returns a Function able to convert strings into their uppercase counterparts * using {@link String#toUpperCase()}. * * <p> * The returned function handles null by returning them. * </p> * * @since 1.9 * @return a function covnerting strings to uppercase */ public static Function<String, String> toUpperCase() { return StringUpperCaseFunction.INSTANCE; } /** * Returns a Function able to convert strings into their uppercase counterparts * using {@link String#toUpperCase(Locale)}. * * <p> * The returned function handles null by returning them. * </p> * * @since 1.9 * @param locale the locale being used to convert to uppercase * @return a function converting strings to uppercase * @throws NullPointerException if locale is null */ public static Function<String, String> toUpperCase(@Nonnull Locale locale) { return new StringLocaleAwareUpperCaseFunction(locale); } /** * Joines instances of a collection * into a single string instance, * using a parametrizable JoinWalker * which transforms instances of T into Strings. * * Calling this method is equivalent to * {@code Strings.join(collection, " ", walker} * * @deprecated use {@link Joiner}, {@link Function} and {@link Iterables#transform(Iterable, Function)} instead * * @param <T> the generic type * @param collection the element provider * @param walker the function object which transform instances of T into strings * @throws NullPointerException if collection is null or collection is empty and walker is null * @return the joined collection as a string */ @Deprecated public static <T> String join(Collection<? extends T> collection, JoinWalker<? super T> walker) { return Strings.join(collection, DEFAULT_DELIMITER, walker); } /** * Joines instances of a collection * into a single string instance, * using a parametrizable delimeter and * a JoinWalker which transforms instances * of T into Strings. * * @deprecated use {@link Joiner}, {@link Function} and {@link Iterables#transform(Iterable, Function)} instead * * @param <T> the generic type * @param collection the element provider * @param delimiter the string betweens joined elements of collection * @param walker the function object which transform instances of T into strings * @throws NullPointerException if collection is null or collection is empty and walker is null * @return the joined collection as a string */ @Deprecated public static <T> String join(Collection<? extends T> collection, String delimiter, JoinWalker<? super T> walker) { final Iterable<String> transformed = Iterables.transform(collection, JoinWalkers.asFunction(walker)); return Joiner.on(delimiter).useForNull("null").join(transformed); } /** * Checks whether a given {@link String} is a valid * number, containing only digits. * This implementation is performing a blank-check * before using {@link StringUtils#isNumeric(String)}. * * <pre> * StringUtility.isNumeric(null) = false * StringUtility.isNumeric("") = false * StringUtility.isNumeric(" ") = false * StringUtility.isNumeric("123") = true * StringUtility.isNumeric("12 3") = false * StringUtility.isNumeric("ab2c") = false * StringUtility.isNumeric("12-3") = false * StringUtility.isNumeric("12.3") = false * </pre> * * @param s the String to check, may be null * @return true if s is not blank and contains only digits */ public static boolean isNumeric(String s) { return StringUtils.isNotBlank(s) && StringUtils.isNumeric(s); } /** * Checks whether s is blank according * to {@link StringUtils#isBlank(String)} and * returns null in this case. * * <p> * Using this method is equivalent to calling * {@link Strings#defaultIfBlank(String, String)} * with s and null. * </p> * * @param s the string to check * @return null if s is blank, s otherwise */ public static String defaultIfBlank(String s) { return Strings.defaultIfBlank(s, null); } /** * Checks whether s is blank according * to {@link StringUtils#isBlank(String)} and * returns the default value in this case. * * @since 1.6 * @param s the string to check * @param defaultValue the default value to return in case s is blank * @return defaultValue if s is blank, s otherwise */ public static String defaultIfBlank(String s, String defaultValue) { return StringUtils.isBlank(s) ? defaultValue : s; } /** * A nullsafe toString method. * * @since 1.14 * @param object the object * @return {@code object.toString()} or null, if object is null */ public static String toString(@Nullable Object object) { return toString(object, null); } /** * A nullsafe toString method. * * @since 1.14 * @param object the object * @param defaultValue the default value * @return {@code object.toString()} or {@code defaultValue}, if object is null */ public static String toString(@Nullable Object object, String defaultValue) { return object == null ? defaultValue : object.toString(); } /** * Creates a {@link Rule} which evaluates to true * when passed in a string which contains the specified char sequence. * * @since 1.6 * @param s the char sequence which should be contained in the input * @return a rule which returns true when the given input contains s * @throws NullPointerException if s is null */ public static Rule<String> contains(CharSequence s) { return new StringContainsRule(s); } /** * Creates a {@link Rule} which evaluates to true * when passed in a char sequence which is contained in the specified string. * * @since 1.6 * @param s the string which should contain the input * @return a rule which returns true when s contains the given char sequence * @throws NullPointerException if s is null */ public static Rule<CharSequence> containedIn(String s) { return new StringContainedInRule(s); } /** * Ensures that a string passed as a parameter to the calling method is not empty. * * @since 1.6 * @param s the string being checked * @return s */ public static String checkNotEmpty(String s) { return checkNotEmpty(s, "s must not be empty but was '%s'", s); } /** * Ensures that a string passed as a parameter to the calling method is not empty. * * @since 1.6 * @param s the string being checked * @param message the error message * @return s */ public static String checkNotEmpty(String s, String message) { return checkNotEmpty(s, message, EMPTY_ARRAY); } /** * Ensures that a string passed as a parameter to the calling method is not empty. * * @since 1.6 * @param s the string being checked * @param message the error message * @param args the error message arguments * @return s */ public static String checkNotEmpty(String s, String message, Object... args) { Preconditions.checkArgument(StringUtils.isNotEmpty(s), message, args); return s; } /** * Ensures that a string passed as a parameter to the calling method is not blank. * * @since 1.6 * @param s the string being checked * @return version of s */ public static String checkNotBlank(String s) { return checkNotBlank(s, "s must not be blank but was '%s'", s); } /** * Ensures that a string passed as a parameter to the calling method is not blank. * * @since 1.6 * @param s the string being checked * @param message the error message * @return version of s */ public static String checkNotBlank(String s, String message) { return checkNotBlank(s, message, EMPTY_ARRAY); } /** * Ensures that a string passed as a parameter to the calling method is not blank. * * @since 1.6 * @param s the string being checked * @param args the error message arguments * @param message the error message * @return version of s */ public static String checkNotBlank(String s, String message, Object... args) { Preconditions.checkArgument(StringUtils.isNotBlank(s), message, args); return s; } }
src/main/java/de/cosmocode/commons/Strings.java
/** * Copyright 2010 CosmoCode GmbH * * 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 de.cosmocode.commons; import java.text.Collator; import java.util.Collection; import java.util.Locale; import javax.annotation.Nonnull; import org.apache.commons.lang.StringUtils; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import com.google.common.collect.Ordering; import de.cosmocode.commons.validation.Rule; /** * Utility class inspired by {@link StringUtils}, * providing {@link String} related helper methods. * * @author Willi Schoenborn */ public final class Strings { /** * Natural ordering on {@link String}s which trims comparee * first using {@link TrimMode#NULL} and puts nulls to the end. */ public static final Ordering<String> CASE_SENSITIVE = Ordering.natural().nullsLast().onResultOf(TrimMode.NULL); /** * A case-insensitive version of {@link Strings#CASE_SENSITIVE}. */ public static final Ordering<String> CASE_INSENSITIVE = Ordering.from(String.CASE_INSENSITIVE_ORDER). nullsLast().onResultOf(TrimMode.NULL); public static final String DEFAULT_DELIMITER = " "; private static final Object[] EMPTY_ARRAY = {}; /** * Prevent instantiation. */ private Strings() { } /** * Creates an {@link Ordering} which uses a {@link Collator} based * on the given {@link Locale} to sort Strings. * * @param locale the desired locale * @return a new {@link Ordering} backed by a {@link Collator} * @throws NullPointerException if locale is null */ public static Ordering<String> orderBy(@Nonnull Locale locale) { return new CollatorOrdering(locale); } /** * Returns a Function able to convert strings into their lowercase counterparts * using {@link String#toLowerCase()}. * * <p> * The returned function handles null by returning them. * </p> * * @since 1.9 * @return a function covnerting strings to lowercase */ public static Function<String, String> toLowerCase() { return StringLowerCaseFunction.INSTANCE; } /** * Returns a Function able to convert strings into their lowercase counterparts * using {@link String#toLowerCase(Locale)}. * * <p> * The returned function handles null by returning them. * </p> * * @since 1.9 * @param locale the locale being used to convert to lowercase * @return a function converting strings to lowercase * @throws NullPointerException if locale is null */ public static Function<String, String> toLowerCase(@Nonnull Locale locale) { return new StringLocaleAwareLowerCaseFunction(locale); } /** * Returns a Function able to convert strings into their uppercase counterparts * using {@link String#toUpperCase()}. * * <p> * The returned function handles null by returning them. * </p> * * @since 1.9 * @return a function covnerting strings to uppercase */ public static Function<String, String> toUpperCase() { return StringUpperCaseFunction.INSTANCE; } /** * Returns a Function able to convert strings into their uppercase counterparts * using {@link String#toUpperCase(Locale)}. * * <p> * The returned function handles null by returning them. * </p> * * @since 1.9 * @param locale the locale being used to convert to uppercase * @return a function converting strings to uppercase * @throws NullPointerException if locale is null */ public static Function<String, String> toUpperCase(@Nonnull Locale locale) { return new StringLocaleAwareUpperCaseFunction(locale); } /** * Joines instances of a collection * into a single string instance, * using a parametrizable JoinWalker * which transforms instances of T into Strings. * * Calling this method is equivalent to * {@code Strings.join(collection, " ", walker} * * @deprecated use {@link Joiner}, {@link Function} and {@link Iterables#transform(Iterable, Function)} instead * * @param <T> the generic type * @param collection the element provider * @param walker the function object which transform instances of T into strings * @throws NullPointerException if collection is null or collection is empty and walker is null * @return the joined collection as a string */ @Deprecated public static <T> String join(Collection<? extends T> collection, JoinWalker<? super T> walker) { return Strings.join(collection, DEFAULT_DELIMITER, walker); } /** * Joines instances of a collection * into a single string instance, * using a parametrizable delimeter and * a JoinWalker which transforms instances * of T into Strings. * * @deprecated use {@link Joiner}, {@link Function} and {@link Iterables#transform(Iterable, Function)} instead * * @param <T> the generic type * @param collection the element provider * @param delimiter the string betweens joined elements of collection * @param walker the function object which transform instances of T into strings * @throws NullPointerException if collection is null or collection is empty and walker is null * @return the joined collection as a string */ @Deprecated public static <T> String join(Collection<? extends T> collection, String delimiter, JoinWalker<? super T> walker) { final Iterable<String> transformed = Iterables.transform(collection, JoinWalkers.asFunction(walker)); return Joiner.on(delimiter).useForNull("null").join(transformed); } /** * Checks whether a given {@link String} is a valid * number, containing only digits. * This implementation is performing a blank-check * before using {@link StringUtils#isNumeric(String)}. * * <pre> * StringUtility.isNumeric(null) = false * StringUtility.isNumeric("") = false * StringUtility.isNumeric(" ") = false * StringUtility.isNumeric("123") = true * StringUtility.isNumeric("12 3") = false * StringUtility.isNumeric("ab2c") = false * StringUtility.isNumeric("12-3") = false * StringUtility.isNumeric("12.3") = false * </pre> * * @param s the String to check, may be null * @return true if s is not blank and contains only digits */ public static boolean isNumeric(String s) { return StringUtils.isNotBlank(s) && StringUtils.isNumeric(s); } /** * Checks whether s is blank according * to {@link StringUtils#isBlank(String)} and * returns null in this case. * * <p> * Using this method is equivalent to calling * {@link Strings#defaultIfBlank(String, String)} * with s and null. * </p> * * @param s the string to check * @return null if s is blank, s otherwise */ public static String defaultIfBlank(String s) { return Strings.defaultIfBlank(s, null); } /** * Checks whether s is blank according * to {@link StringUtils#isBlank(String)} and * returns the default value in this case. * * @since 1.6 * @param s the string to check * @param defaultValue the default value to return in case s is blank * @return defaultValue if s is blank, s otherwise */ public static String defaultIfBlank(String s, String defaultValue) { return StringUtils.isBlank(s) ? defaultValue : s; } /** * Creates a {@link Rule} which evaluates to true * when passed in a string which contains the specified char sequence. * * @since 1.6 * @param s the char sequence which should be contained in the input * @return a rule which returns true when the given input contains s * @throws NullPointerException if s is null */ public static Rule<String> contains(CharSequence s) { return new StringContainsRule(s); } /** * Creates a {@link Rule} which evaluates to true * when passed in a char sequence which is contained in the specified string. * * @since 1.6 * @param s the string which should contain the input * @return a rule which returns true when s contains the given char sequence * @throws NullPointerException if s is null */ public static Rule<CharSequence> containedIn(String s) { return new StringContainedInRule(s); } /** * Ensures that a string passed as a parameter to the calling method is not empty. * * @since 1.6 * @param s the string being checked * @return s */ public static String checkNotEmpty(String s) { return checkNotEmpty(s, "s must not be empty but was '%s'", s); } /** * Ensures that a string passed as a parameter to the calling method is not empty. * * @since 1.6 * @param s the string being checked * @param message the error message * @return s */ public static String checkNotEmpty(String s, String message) { return checkNotEmpty(s, message, EMPTY_ARRAY); } /** * Ensures that a string passed as a parameter to the calling method is not empty. * * @since 1.6 * @param s the string being checked * @param message the error message * @param args the error message arguments * @return s */ public static String checkNotEmpty(String s, String message, Object... args) { Preconditions.checkArgument(StringUtils.isNotEmpty(s), message, args); return s; } /** * Ensures that a string passed as a parameter to the calling method is not blank. * * @since 1.6 * @param s the string being checked * @return version of s */ public static String checkNotBlank(String s) { return checkNotBlank(s, "s must not be blank but was '%s'", s); } /** * Ensures that a string passed as a parameter to the calling method is not blank. * * @since 1.6 * @param s the string being checked * @param message the error message * @return version of s */ public static String checkNotBlank(String s, String message) { return checkNotBlank(s, message, EMPTY_ARRAY); } /** * Ensures that a string passed as a parameter to the calling method is not blank. * * @since 1.6 * @param s the string being checked * @param args the error message arguments * @param message the error message * @return version of s */ public static String checkNotBlank(String s, String message, Object... args) { Preconditions.checkArgument(StringUtils.isNotBlank(s), message, args); return s; } }
added toString methods
src/main/java/de/cosmocode/commons/Strings.java
added toString methods
<ide><path>rc/main/java/de/cosmocode/commons/Strings.java <ide> import java.util.Locale; <ide> <ide> import javax.annotation.Nonnull; <add>import javax.annotation.Nullable; <ide> <ide> import org.apache.commons.lang.StringUtils; <ide> <ide> } <ide> <ide> /** <add> * A nullsafe toString method. <add> * <add> * @since 1.14 <add> * @param object the object <add> * @return {@code object.toString()} or null, if object is null <add> */ <add> public static String toString(@Nullable Object object) { <add> return toString(object, null); <add> } <add> <add> /** <add> * A nullsafe toString method. <add> * <add> * @since 1.14 <add> * @param object the object <add> * @param defaultValue the default value <add> * @return {@code object.toString()} or {@code defaultValue}, if object is null <add> */ <add> public static String toString(@Nullable Object object, String defaultValue) { <add> return object == null ? defaultValue : object.toString(); <add> } <add> <add> /** <ide> * Creates a {@link Rule} which evaluates to true <ide> * when passed in a string which contains the specified char sequence. <ide> *
Java
apache-2.0
4df08b49f71a679e1b9961c7e7b68ccccdc1d0d5
0
quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus
package org.jboss.shamrock.undertow; import static javax.servlet.DispatcherType.REQUEST; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.EventListener; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import javax.annotation.security.DeclareRoles; import javax.annotation.security.RunAs; import javax.inject.Inject; import javax.servlet.Filter; import javax.servlet.Servlet; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.ServletSecurity; import javax.servlet.annotation.WebFilter; import javax.servlet.annotation.WebListener; import javax.servlet.annotation.WebServlet; import org.jboss.annotation.javaee.Descriptions; import org.jboss.annotation.javaee.DisplayNames; import org.jboss.annotation.javaee.Icons; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationTarget; import org.jboss.jandex.AnnotationValue; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.jandex.IndexView; import org.jboss.metadata.javaee.spec.DescriptionGroupMetaData; import org.jboss.metadata.javaee.spec.DescriptionImpl; import org.jboss.metadata.javaee.spec.DescriptionsImpl; import org.jboss.metadata.javaee.spec.DisplayNameImpl; import org.jboss.metadata.javaee.spec.DisplayNamesImpl; import org.jboss.metadata.javaee.spec.IconImpl; import org.jboss.metadata.javaee.spec.IconsImpl; import org.jboss.metadata.javaee.spec.ParamValueMetaData; import org.jboss.metadata.javaee.spec.RunAsMetaData; import org.jboss.metadata.javaee.spec.SecurityRoleMetaData; import org.jboss.metadata.javaee.spec.SecurityRolesMetaData; import org.jboss.metadata.web.spec.AnnotationMetaData; import org.jboss.metadata.web.spec.AnnotationsMetaData; import org.jboss.metadata.web.spec.DispatcherType; import org.jboss.metadata.web.spec.EmptyRoleSemanticType; import org.jboss.metadata.web.spec.FilterMappingMetaData; import org.jboss.metadata.web.spec.FilterMetaData; import org.jboss.metadata.web.spec.FiltersMetaData; import org.jboss.metadata.web.spec.HttpMethodConstraintMetaData; import org.jboss.metadata.web.spec.ListenerMetaData; import org.jboss.metadata.web.spec.MultipartConfigMetaData; import org.jboss.metadata.web.spec.ServletMappingMetaData; import org.jboss.metadata.web.spec.ServletMetaData; import org.jboss.metadata.web.spec.ServletSecurityMetaData; import org.jboss.metadata.web.spec.ServletsMetaData; import org.jboss.metadata.web.spec.TransportGuaranteeType; import org.jboss.metadata.web.spec.WebMetaData; import org.jboss.shamrock.deployment.ArchiveContext; import org.jboss.shamrock.deployment.ProcessorContext; import org.jboss.shamrock.deployment.ResourceProcessor; import org.jboss.shamrock.deployment.RuntimePriority; import org.jboss.shamrock.deployment.ShamrockConfig; import org.jboss.shamrock.deployment.codegen.BytecodeRecorder; import org.jboss.shamrock.runtime.InjectionInstance; import org.jboss.shamrock.undertow.runtime.UndertowDeploymentTemplate; import io.undertow.servlet.api.FilterInfo; import io.undertow.servlet.api.InstanceFactory; import io.undertow.servlet.api.ServletInfo; import io.undertow.servlet.handlers.DefaultServlet; public class ServletResourceProcessor implements ResourceProcessor { private static final DotName webFilter = DotName.createSimple(WebFilter.class.getName()); private static final DotName webListener = DotName.createSimple(WebListener.class.getName()); private static final DotName webServlet = DotName.createSimple(WebServlet.class.getName()); private static final DotName runAs = DotName.createSimple(RunAs.class.getName()); private static final DotName declareRoles = DotName.createSimple(DeclareRoles.class.getName()); private static final DotName multipartConfig = DotName.createSimple(MultipartConfig.class.getName()); private static final DotName servletSecurity = DotName.createSimple(ServletSecurity.class.getName()); @Inject private ShamrockConfig config; @Inject private ServletDeployment deployment; @Override public void process(ArchiveContext archiveContext, ProcessorContext processorContext) throws Exception { processorContext.addReflectiveClass(false, false, DefaultServlet.class.getName()); processorContext.addReflectiveClass(false, false, "io.undertow.server.protocol.http.HttpRequestParser$$generated"); processorContext.addRuntimeInitializedClasses("io.undertow.server.protocol.ajp.AjpServerResponseConduit"); processorContext.addRuntimeInitializedClasses("io.undertow.server.protocol.ajp.AjpServerRequestConduit"); //TODO: this should be somewhere else, as SSL is not specific to Undertow processorContext.addRuntimeInitializedClasses("org.wildfly.openssl.OpenSSLEngine"); handleResources(archiveContext, processorContext); try (BytecodeRecorder context = processorContext.addStaticInitTask(RuntimePriority.UNDERTOW_CREATE_DEPLOYMENT)) { UndertowDeploymentTemplate template = context.getRecordingProxy(UndertowDeploymentTemplate.class); template.createDeployment("test"); } final IndexView index = archiveContext.getCombinedIndex(); WebMetaData result = processAnnotations(index); try (BytecodeRecorder context = processorContext.addStaticInitTask(RuntimePriority.UNDERTOW_REGISTER_SERVLET)) { UndertowDeploymentTemplate template = context.getRecordingProxy(UndertowDeploymentTemplate.class); //add servlets if (result.getServlets() != null) { for (ServletMetaData servlet : result.getServlets()) { processorContext.addReflectiveClass(false, false, servlet.getServletClass()); InjectionInstance<? extends Servlet> injection = (InjectionInstance<? extends Servlet>) context.newInstanceFactory(servlet.getServletClass()); InstanceFactory<? extends Servlet> factory = template.createInstanceFactory(injection); AtomicReference<ServletInfo> sref = template.registerServlet(null, servlet.getServletName(), context.classProxy(servlet.getServletClass()), servlet.isAsyncSupported(), servlet.getLoadOnStartupInt(), factory); if (servlet.getInitParam() != null) { for (ParamValueMetaData init : servlet.getInitParam()) { template.addServletInitParam(sref, init.getParamName(), init.getParamValue()); } } if(servlet.getMultipartConfig() != null) { template.setMultipartConfig(sref, servlet.getMultipartConfig().getLocation(), servlet.getMultipartConfig().getMaxFileSize(), servlet.getMultipartConfig().getMaxRequestSize(), servlet.getMultipartConfig().getFileSizeThreshold()); } } } //servlet mappings if (result.getServletMappings() != null) { for (ServletMappingMetaData mapping : result.getServletMappings()) { for (String m : mapping.getUrlPatterns()) { template.addServletMapping(null, mapping.getServletName(), m); } } } //filters if (result.getFilters() != null) { for (FilterMetaData filter : result.getFilters()) { processorContext.addReflectiveClass(false, false, filter.getFilterClass()); InjectionInstance<? extends Filter> injection = (InjectionInstance<? extends Filter>) context.newInstanceFactory(filter.getFilterClass()); InstanceFactory<? extends Filter> factory = template.createInstanceFactory(injection); AtomicReference<FilterInfo> sref = template.registerFilter(null, filter.getFilterName(), context.classProxy(filter.getFilterClass()), filter.isAsyncSupported(), factory); if (filter.getInitParam() != null) { for (ParamValueMetaData init : filter.getInitParam()) { template.addFilterInitParam(sref, init.getParamName(), init.getParamValue()); } } } } if (result.getFilterMappings() != null) { for (FilterMappingMetaData mapping : result.getFilterMappings()) { for (String m : mapping.getUrlPatterns()) { if (mapping.getDispatchers() == null || mapping.getDispatchers().isEmpty()) { template.addFilterMapping(null, mapping.getFilterName(), m, REQUEST); } else { for (DispatcherType dispatcher : mapping.getDispatchers()) { template.addFilterMapping(null, mapping.getFilterName(), m, javax.servlet.DispatcherType.valueOf(dispatcher.name())); } } } } } //listeners if (result.getListeners() != null) { for (ListenerMetaData listener : result.getListeners()) { processorContext.addReflectiveClass(false, false, listener.getListenerClass()); InjectionInstance<? extends EventListener> injection = (InjectionInstance<? extends EventListener>) context.newInstanceFactory(listener.getListenerClass()); InstanceFactory<? extends EventListener> factory = template.createInstanceFactory(injection); template.registerListener(null, context.classProxy(listener.getListenerClass()), factory); } } for (ServletData servlet : deployment.getServlets()) { String servletClass = servlet.getServletClass(); InjectionInstance<? extends Servlet> injection = (InjectionInstance<? extends Servlet>) context.newInstanceFactory(servletClass); InstanceFactory<? extends Servlet> factory = template.createInstanceFactory(injection); template.registerServlet(null, servlet.getName(), context.classProxy(servletClass), true, servlet.getLoadOnStartup(), factory); for (String m : servlet.getMapings()) { template.addServletMapping(null, servlet.getName(), m); } } } try (BytecodeRecorder context = processorContext.addStaticInitTask(RuntimePriority.UNDERTOW_DEPLOY)) { UndertowDeploymentTemplate template = context.getRecordingProxy(UndertowDeploymentTemplate.class); template.bootServletContainer(null); } try (BytecodeRecorder context = processorContext.addDeploymentTask(RuntimePriority.UNDERTOW_START)) { UndertowDeploymentTemplate template = context.getRecordingProxy(UndertowDeploymentTemplate.class); template.startUndertow(null, null, config.getConfig("http.port", "8080")); } } private void handleResources(ArchiveContext archiveContext, ProcessorContext processorContext) throws IOException { Path resources = archiveContext.getRootArchive().getChildPath("META-INF/resources"); if(resources != null) { Files.walk(resources).forEach(new Consumer<Path>() { @Override public void accept(Path path) { if(!Files.isDirectory(path)) { processorContext.addResource(archiveContext.getRootArchive().getArchiveRoot().relativize(path).toString()); } } }); } } @Override public int getPriority() { return 100; } /** * Process a single index. * * @param index the annotation index */ protected WebMetaData processAnnotations(IndexView index) { WebMetaData metaData = new WebMetaData(); // @WebServlet final Collection<AnnotationInstance> webServletAnnotations = index.getAnnotations(webServlet); if (webServletAnnotations != null && webServletAnnotations.size() > 0) { ServletsMetaData servlets = new ServletsMetaData(); List<ServletMappingMetaData> servletMappings = new ArrayList<ServletMappingMetaData>(); for (final AnnotationInstance annotation : webServletAnnotations) { ServletMetaData servlet = new ServletMetaData(); AnnotationTarget target = annotation.target(); ClassInfo classInfo = ClassInfo.class.cast(target); servlet.setServletClass(classInfo.toString()); AnnotationValue nameValue = annotation.value("name"); if (nameValue == null || nameValue.asString().isEmpty()) { servlet.setName(classInfo.toString()); } else { servlet.setName(nameValue.asString()); } AnnotationValue loadOnStartup = annotation.value("loadOnStartup"); if (loadOnStartup != null && loadOnStartup.asInt() >= 0) { servlet.setLoadOnStartupInt(loadOnStartup.asInt()); } AnnotationValue asyncSupported = annotation.value("asyncSupported"); if (asyncSupported != null) { servlet.setAsyncSupported(asyncSupported.asBoolean()); } AnnotationValue initParamsValue = annotation.value("initParams"); if (initParamsValue != null) { AnnotationInstance[] initParamsAnnotations = initParamsValue.asNestedArray(); if (initParamsAnnotations != null && initParamsAnnotations.length > 0) { List<ParamValueMetaData> initParams = new ArrayList<ParamValueMetaData>(); for (AnnotationInstance initParamsAnnotation : initParamsAnnotations) { ParamValueMetaData initParam = new ParamValueMetaData(); AnnotationValue initParamName = initParamsAnnotation.value("name"); AnnotationValue initParamValue = initParamsAnnotation.value(); AnnotationValue initParamDescription = initParamsAnnotation.value("description"); initParam.setParamName(initParamName.asString()); initParam.setParamValue(initParamValue.asString()); if (initParamDescription != null) { Descriptions descriptions = getDescription(initParamDescription.asString()); if (descriptions != null) { initParam.setDescriptions(descriptions); } } initParams.add(initParam); } servlet.setInitParam(initParams); } } AnnotationValue descriptionValue = annotation.value("description"); AnnotationValue displayNameValue = annotation.value("displayName"); AnnotationValue smallIconValue = annotation.value("smallIcon"); AnnotationValue largeIconValue = annotation.value("largeIcon"); DescriptionGroupMetaData descriptionGroup = getDescriptionGroup((descriptionValue == null) ? "" : descriptionValue.asString(), (displayNameValue == null) ? "" : displayNameValue.asString(), (smallIconValue == null) ? "" : smallIconValue.asString(), (largeIconValue == null) ? "" : largeIconValue.asString()); if (descriptionGroup != null) { servlet.setDescriptionGroup(descriptionGroup); } ServletMappingMetaData servletMapping = new ServletMappingMetaData(); servletMapping.setServletName(servlet.getName()); List<String> urlPatterns = new ArrayList<String>(); AnnotationValue urlPatternsValue = annotation.value("urlPatterns"); if (urlPatternsValue != null) { for (String urlPattern : urlPatternsValue.asStringArray()) { urlPatterns.add(urlPattern); } } urlPatternsValue = annotation.value(); if (urlPatternsValue != null) { for (String urlPattern : urlPatternsValue.asStringArray()) { urlPatterns.add(urlPattern); } } if (urlPatterns.size() > 0) { servletMapping.setUrlPatterns(urlPatterns); servletMappings.add(servletMapping); } servlets.add(servlet); } metaData.setServlets(servlets); metaData.setServletMappings(servletMappings); } // @WebFilter final Collection<AnnotationInstance> webFilterAnnotations = index.getAnnotations(webFilter); if (webFilterAnnotations != null && webFilterAnnotations.size() > 0) { FiltersMetaData filters = new FiltersMetaData(); List<FilterMappingMetaData> filterMappings = new ArrayList<FilterMappingMetaData>(); for (final AnnotationInstance annotation : webFilterAnnotations) { FilterMetaData filter = new FilterMetaData(); AnnotationTarget target = annotation.target(); ClassInfo classInfo = ClassInfo.class.cast(target); filter.setFilterClass(classInfo.toString()); AnnotationValue nameValue = annotation.value("filterName"); if (nameValue == null || nameValue.asString().isEmpty()) { filter.setName(classInfo.toString()); } else { filter.setName(nameValue.asString()); } AnnotationValue asyncSupported = annotation.value("asyncSupported"); if (asyncSupported != null) { filter.setAsyncSupported(asyncSupported.asBoolean()); } AnnotationValue initParamsValue = annotation.value("initParams"); if (initParamsValue != null) { AnnotationInstance[] initParamsAnnotations = initParamsValue.asNestedArray(); if (initParamsAnnotations != null && initParamsAnnotations.length > 0) { List<ParamValueMetaData> initParams = new ArrayList<ParamValueMetaData>(); for (AnnotationInstance initParamsAnnotation : initParamsAnnotations) { ParamValueMetaData initParam = new ParamValueMetaData(); AnnotationValue initParamName = initParamsAnnotation.value("name"); AnnotationValue initParamValue = initParamsAnnotation.value(); AnnotationValue initParamDescription = initParamsAnnotation.value("description"); initParam.setParamName(initParamName.asString()); initParam.setParamValue(initParamValue.asString()); if (initParamDescription != null) { Descriptions descriptions = getDescription(initParamDescription.asString()); if (descriptions != null) { initParam.setDescriptions(descriptions); } } initParams.add(initParam); } filter.setInitParam(initParams); } } AnnotationValue descriptionValue = annotation.value("description"); AnnotationValue displayNameValue = annotation.value("displayName"); AnnotationValue smallIconValue = annotation.value("smallIcon"); AnnotationValue largeIconValue = annotation.value("largeIcon"); DescriptionGroupMetaData descriptionGroup = getDescriptionGroup((descriptionValue == null) ? "" : descriptionValue.asString(), (displayNameValue == null) ? "" : displayNameValue.asString(), (smallIconValue == null) ? "" : smallIconValue.asString(), (largeIconValue == null) ? "" : largeIconValue.asString()); if (descriptionGroup != null) { filter.setDescriptionGroup(descriptionGroup); } filters.add(filter); FilterMappingMetaData filterMapping = new FilterMappingMetaData(); filterMapping.setFilterName(filter.getName()); List<String> urlPatterns = new ArrayList<String>(); List<String> servletNames = new ArrayList<String>(); List<DispatcherType> dispatchers = new ArrayList<DispatcherType>(); AnnotationValue urlPatternsValue = annotation.value("urlPatterns"); if (urlPatternsValue != null) { for (String urlPattern : urlPatternsValue.asStringArray()) { urlPatterns.add(urlPattern); } } urlPatternsValue = annotation.value(); if (urlPatternsValue != null) { for (String urlPattern : urlPatternsValue.asStringArray()) { urlPatterns.add(urlPattern); } } if (urlPatterns.size() > 0) { filterMapping.setUrlPatterns(urlPatterns); } AnnotationValue servletNamesValue = annotation.value("servletNames"); if (servletNamesValue != null) { for (String servletName : servletNamesValue.asStringArray()) { servletNames.add(servletName); } } if (servletNames.size() > 0) { filterMapping.setServletNames(servletNames); } AnnotationValue dispatcherTypesValue = annotation.value("dispatcherTypes"); if (dispatcherTypesValue != null) { for (String dispatcherValue : dispatcherTypesValue.asEnumArray()) { dispatchers.add(DispatcherType.valueOf(dispatcherValue)); } } if (dispatchers.size() > 0) { filterMapping.setDispatchers(dispatchers); } if (urlPatterns.size() > 0 || servletNames.size() > 0) { filterMappings.add(filterMapping); } } metaData.setFilters(filters); metaData.setFilterMappings(filterMappings); } // @WebListener final Collection<AnnotationInstance> webListenerAnnotations = index.getAnnotations(webListener); if (webListenerAnnotations != null && webListenerAnnotations.size() > 0) { List<ListenerMetaData> listeners = new ArrayList<ListenerMetaData>(); for (final AnnotationInstance annotation : webListenerAnnotations) { ListenerMetaData listener = new ListenerMetaData(); AnnotationTarget target = annotation.target(); ClassInfo classInfo = ClassInfo.class.cast(target); listener.setListenerClass(classInfo.toString()); AnnotationValue descriptionValue = annotation.value(); if (descriptionValue != null) { DescriptionGroupMetaData descriptionGroup = getDescriptionGroup(descriptionValue.asString()); if (descriptionGroup != null) { listener.setDescriptionGroup(descriptionGroup); } } listeners.add(listener); } metaData.setListeners(listeners); } // @RunAs final Collection<AnnotationInstance> runAsAnnotations = index.getAnnotations(runAs); if (runAsAnnotations != null && runAsAnnotations.size() > 0) { AnnotationsMetaData annotations = metaData.getAnnotations(); if (annotations == null) { annotations = new AnnotationsMetaData(); metaData.setAnnotations(annotations); } for (final AnnotationInstance annotation : runAsAnnotations) { AnnotationTarget target = annotation.target(); if (!(target instanceof ClassInfo)) { continue; } ClassInfo classInfo = ClassInfo.class.cast(target); AnnotationMetaData annotationMD = annotations.get(classInfo.toString()); if (annotationMD == null) { annotationMD = new AnnotationMetaData(); annotationMD.setClassName(classInfo.toString()); annotations.add(annotationMD); } RunAsMetaData runAs = new RunAsMetaData(); runAs.setRoleName(annotation.value().asString()); annotationMD.setRunAs(runAs); } } // @DeclareRoles final Collection<AnnotationInstance> declareRolesAnnotations = index.getAnnotations(declareRoles); if (declareRolesAnnotations != null && declareRolesAnnotations.size() > 0) { SecurityRolesMetaData securityRoles = metaData.getSecurityRoles(); if (securityRoles == null) { securityRoles = new SecurityRolesMetaData(); metaData.setSecurityRoles(securityRoles); } for (final AnnotationInstance annotation : declareRolesAnnotations) { for (String role : annotation.value().asStringArray()) { SecurityRoleMetaData sr = new SecurityRoleMetaData(); sr.setRoleName(role); securityRoles.add(sr); } } } // @MultipartConfig final Collection<AnnotationInstance> multipartConfigAnnotations = index.getAnnotations(multipartConfig); if (multipartConfigAnnotations != null && multipartConfigAnnotations.size() > 0) { AnnotationsMetaData annotations = metaData.getAnnotations(); if (annotations == null) { annotations = new AnnotationsMetaData(); metaData.setAnnotations(annotations); } for (final AnnotationInstance annotation : multipartConfigAnnotations) { AnnotationTarget target = annotation.target(); ClassInfo classInfo = ClassInfo.class.cast(target); AnnotationMetaData annotationMD = annotations.get(classInfo.toString()); if (annotationMD == null) { annotationMD = new AnnotationMetaData(); annotationMD.setClassName(classInfo.toString()); annotations.add(annotationMD); } MultipartConfigMetaData multipartConfig = new MultipartConfigMetaData(); AnnotationValue locationValue = annotation.value("location"); if (locationValue != null && locationValue.asString().length() > 0) { multipartConfig.setLocation(locationValue.asString()); } AnnotationValue maxFileSizeValue = annotation.value("maxFileSize"); if (maxFileSizeValue != null && maxFileSizeValue.asLong() != -1L) { multipartConfig.setMaxFileSize(maxFileSizeValue.asLong()); } AnnotationValue maxRequestSizeValue = annotation.value("maxRequestSize"); if (maxRequestSizeValue != null && maxRequestSizeValue.asLong() != -1L) { multipartConfig.setMaxRequestSize(maxRequestSizeValue.asLong()); } AnnotationValue fileSizeThresholdValue = annotation.value("fileSizeThreshold"); if (fileSizeThresholdValue != null && fileSizeThresholdValue.asInt() != 0) { multipartConfig.setFileSizeThreshold(fileSizeThresholdValue.asInt()); } annotationMD.setMultipartConfig(multipartConfig); } } // @ServletSecurity final Collection<AnnotationInstance> servletSecurityAnnotations = index.getAnnotations(servletSecurity); if (servletSecurityAnnotations != null && servletSecurityAnnotations.size() > 0) { AnnotationsMetaData annotations = metaData.getAnnotations(); if (annotations == null) { annotations = new AnnotationsMetaData(); metaData.setAnnotations(annotations); } for (final AnnotationInstance annotation : servletSecurityAnnotations) { AnnotationTarget target = annotation.target(); ClassInfo classInfo = ClassInfo.class.cast(target); AnnotationMetaData annotationMD = annotations.get(classInfo.toString()); if (annotationMD == null) { annotationMD = new AnnotationMetaData(); annotationMD.setClassName(classInfo.toString()); annotations.add(annotationMD); } ServletSecurityMetaData servletSecurity = new ServletSecurityMetaData(); AnnotationValue httpConstraintValue = annotation.value(); List<String> rolesAllowed = new ArrayList<String>(); if (httpConstraintValue != null) { AnnotationInstance httpConstraint = httpConstraintValue.asNested(); AnnotationValue httpConstraintERSValue = httpConstraint.value(); if (httpConstraintERSValue != null) { servletSecurity.setEmptyRoleSemantic(EmptyRoleSemanticType.valueOf(httpConstraintERSValue.asEnum())); } AnnotationValue httpConstraintTGValue = httpConstraint.value("transportGuarantee"); if (httpConstraintTGValue != null) { servletSecurity.setTransportGuarantee(TransportGuaranteeType.valueOf(httpConstraintTGValue.asEnum())); } AnnotationValue rolesAllowedValue = httpConstraint.value("rolesAllowed"); if (rolesAllowedValue != null) { for (String role : rolesAllowedValue.asStringArray()) { rolesAllowed.add(role); } } } servletSecurity.setRolesAllowed(rolesAllowed); AnnotationValue httpMethodConstraintsValue = annotation.value("httpMethodConstraints"); if (httpMethodConstraintsValue != null) { AnnotationInstance[] httpMethodConstraints = httpMethodConstraintsValue.asNestedArray(); if (httpMethodConstraints.length > 0) { List<HttpMethodConstraintMetaData> methodConstraints = new ArrayList<HttpMethodConstraintMetaData>(); for (AnnotationInstance httpMethodConstraint : httpMethodConstraints) { HttpMethodConstraintMetaData methodConstraint = new HttpMethodConstraintMetaData(); AnnotationValue httpMethodConstraintValue = httpMethodConstraint.value(); if (httpMethodConstraintValue != null) { methodConstraint.setMethod(httpMethodConstraintValue.asString()); } AnnotationValue httpMethodConstraintERSValue = httpMethodConstraint.value("emptyRoleSemantic"); if (httpMethodConstraintERSValue != null) { methodConstraint.setEmptyRoleSemantic(EmptyRoleSemanticType.valueOf(httpMethodConstraintERSValue.asEnum())); } AnnotationValue httpMethodConstraintTGValue = httpMethodConstraint.value("transportGuarantee"); if (httpMethodConstraintTGValue != null) { methodConstraint.setTransportGuarantee(TransportGuaranteeType.valueOf(httpMethodConstraintTGValue.asEnum())); } AnnotationValue rolesAllowedValue = httpMethodConstraint.value("rolesAllowed"); rolesAllowed = new ArrayList<String>(); if (rolesAllowedValue != null) { for (String role : rolesAllowedValue.asStringArray()) { rolesAllowed.add(role); } } methodConstraint.setRolesAllowed(rolesAllowed); methodConstraints.add(methodConstraint); } servletSecurity.setHttpMethodConstraints(methodConstraints); } } annotationMD.setServletSecurity(servletSecurity); } } return metaData; } protected Descriptions getDescription(String description) { DescriptionsImpl descriptions = null; if (description.length() > 0) { DescriptionImpl di = new DescriptionImpl(); di.setDescription(description); descriptions = new DescriptionsImpl(); descriptions.add(di); } return descriptions; } protected DisplayNames getDisplayName(String displayName) { DisplayNamesImpl displayNames = null; if (displayName.length() > 0) { DisplayNameImpl dn = new DisplayNameImpl(); dn.setDisplayName(displayName); displayNames = new DisplayNamesImpl(); displayNames.add(dn); } return displayNames; } protected Icons getIcons(String smallIcon, String largeIcon) { IconsImpl icons = null; if (smallIcon.length() > 0 || largeIcon.length() > 0) { IconImpl i = new IconImpl(); i.setSmallIcon(smallIcon); i.setLargeIcon(largeIcon); icons = new IconsImpl(); icons.add(i); } return icons; } protected DescriptionGroupMetaData getDescriptionGroup(String description) { DescriptionGroupMetaData dg = null; if (description.length() > 0) { dg = new DescriptionGroupMetaData(); Descriptions descriptions = getDescription(description); dg.setDescriptions(descriptions); } return dg; } protected DescriptionGroupMetaData getDescriptionGroup(String description, String displayName, String smallIcon, String largeIcon) { DescriptionGroupMetaData dg = null; if (description.length() > 0 || displayName.length() > 0 || smallIcon.length() > 0 || largeIcon.length() > 0) { dg = new DescriptionGroupMetaData(); Descriptions descriptions = getDescription(description); if (descriptions != null) dg.setDescriptions(descriptions); DisplayNames displayNames = getDisplayName(displayName); if (displayNames != null) dg.setDisplayNames(displayNames); Icons icons = getIcons(smallIcon, largeIcon); if (icons != null) dg.setIcons(icons); } return dg; } }
undertow/deployment/src/main/java/org/jboss/shamrock/undertow/ServletResourceProcessor.java
package org.jboss.shamrock.undertow; import static javax.servlet.DispatcherType.REQUEST; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.EventListener; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import javax.annotation.security.DeclareRoles; import javax.annotation.security.RunAs; import javax.inject.Inject; import javax.servlet.Filter; import javax.servlet.Servlet; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.ServletSecurity; import javax.servlet.annotation.WebFilter; import javax.servlet.annotation.WebListener; import javax.servlet.annotation.WebServlet; import org.jboss.annotation.javaee.Descriptions; import org.jboss.annotation.javaee.DisplayNames; import org.jboss.annotation.javaee.Icons; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationTarget; import org.jboss.jandex.AnnotationValue; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.jandex.IndexView; import org.jboss.metadata.javaee.spec.DescriptionGroupMetaData; import org.jboss.metadata.javaee.spec.DescriptionImpl; import org.jboss.metadata.javaee.spec.DescriptionsImpl; import org.jboss.metadata.javaee.spec.DisplayNameImpl; import org.jboss.metadata.javaee.spec.DisplayNamesImpl; import org.jboss.metadata.javaee.spec.IconImpl; import org.jboss.metadata.javaee.spec.IconsImpl; import org.jboss.metadata.javaee.spec.ParamValueMetaData; import org.jboss.metadata.javaee.spec.RunAsMetaData; import org.jboss.metadata.javaee.spec.SecurityRoleMetaData; import org.jboss.metadata.javaee.spec.SecurityRolesMetaData; import org.jboss.metadata.web.spec.AnnotationMetaData; import org.jboss.metadata.web.spec.AnnotationsMetaData; import org.jboss.metadata.web.spec.DispatcherType; import org.jboss.metadata.web.spec.EmptyRoleSemanticType; import org.jboss.metadata.web.spec.FilterMappingMetaData; import org.jboss.metadata.web.spec.FilterMetaData; import org.jboss.metadata.web.spec.FiltersMetaData; import org.jboss.metadata.web.spec.HttpMethodConstraintMetaData; import org.jboss.metadata.web.spec.ListenerMetaData; import org.jboss.metadata.web.spec.MultipartConfigMetaData; import org.jboss.metadata.web.spec.ServletMappingMetaData; import org.jboss.metadata.web.spec.ServletMetaData; import org.jboss.metadata.web.spec.ServletSecurityMetaData; import org.jboss.metadata.web.spec.ServletsMetaData; import org.jboss.metadata.web.spec.TransportGuaranteeType; import org.jboss.metadata.web.spec.WebMetaData; import org.jboss.shamrock.deployment.ArchiveContext; import org.jboss.shamrock.deployment.ProcessorContext; import org.jboss.shamrock.deployment.ResourceProcessor; import org.jboss.shamrock.deployment.RuntimePriority; import org.jboss.shamrock.deployment.ShamrockConfig; import org.jboss.shamrock.deployment.codegen.BytecodeRecorder; import org.jboss.shamrock.runtime.InjectionInstance; import org.jboss.shamrock.undertow.runtime.UndertowDeploymentTemplate; import io.undertow.servlet.api.FilterInfo; import io.undertow.servlet.api.InstanceFactory; import io.undertow.servlet.api.ServletInfo; import io.undertow.servlet.handlers.DefaultServlet; public class ServletResourceProcessor implements ResourceProcessor { private static final DotName webFilter = DotName.createSimple(WebFilter.class.getName()); private static final DotName webListener = DotName.createSimple(WebListener.class.getName()); private static final DotName webServlet = DotName.createSimple(WebServlet.class.getName()); private static final DotName runAs = DotName.createSimple(RunAs.class.getName()); private static final DotName declareRoles = DotName.createSimple(DeclareRoles.class.getName()); private static final DotName multipartConfig = DotName.createSimple(MultipartConfig.class.getName()); private static final DotName servletSecurity = DotName.createSimple(ServletSecurity.class.getName()); @Inject private ShamrockConfig config; @Inject private ServletDeployment deployment; @Override public void process(ArchiveContext archiveContext, ProcessorContext processorContext) throws Exception { processorContext.addReflectiveClass(false, false, DefaultServlet.class.getName()); processorContext.addReflectiveClass(false, false, "io.undertow.server.protocol.http.HttpRequestParser$$generated"); processorContext.addRuntimeInitializedClasses("io.undertow.server.protocol.ajp.AjpServerResponseConduit"); processorContext.addRuntimeInitializedClasses("io.undertow.server.protocol.ajp.AjpServerRequestConduit"); handleResources(archiveContext, processorContext); try (BytecodeRecorder context = processorContext.addStaticInitTask(RuntimePriority.UNDERTOW_CREATE_DEPLOYMENT)) { UndertowDeploymentTemplate template = context.getRecordingProxy(UndertowDeploymentTemplate.class); template.createDeployment("test"); } final IndexView index = archiveContext.getCombinedIndex(); WebMetaData result = processAnnotations(index); try (BytecodeRecorder context = processorContext.addStaticInitTask(RuntimePriority.UNDERTOW_REGISTER_SERVLET)) { UndertowDeploymentTemplate template = context.getRecordingProxy(UndertowDeploymentTemplate.class); //add servlets if (result.getServlets() != null) { for (ServletMetaData servlet : result.getServlets()) { processorContext.addReflectiveClass(false, false, servlet.getServletClass()); InjectionInstance<? extends Servlet> injection = (InjectionInstance<? extends Servlet>) context.newInstanceFactory(servlet.getServletClass()); InstanceFactory<? extends Servlet> factory = template.createInstanceFactory(injection); AtomicReference<ServletInfo> sref = template.registerServlet(null, servlet.getServletName(), context.classProxy(servlet.getServletClass()), servlet.isAsyncSupported(), servlet.getLoadOnStartupInt(), factory); if (servlet.getInitParam() != null) { for (ParamValueMetaData init : servlet.getInitParam()) { template.addServletInitParam(sref, init.getParamName(), init.getParamValue()); } } if(servlet.getMultipartConfig() != null) { template.setMultipartConfig(sref, servlet.getMultipartConfig().getLocation(), servlet.getMultipartConfig().getMaxFileSize(), servlet.getMultipartConfig().getMaxRequestSize(), servlet.getMultipartConfig().getFileSizeThreshold()); } } } //servlet mappings if (result.getServletMappings() != null) { for (ServletMappingMetaData mapping : result.getServletMappings()) { for (String m : mapping.getUrlPatterns()) { template.addServletMapping(null, mapping.getServletName(), m); } } } //filters if (result.getFilters() != null) { for (FilterMetaData filter : result.getFilters()) { processorContext.addReflectiveClass(false, false, filter.getFilterClass()); InjectionInstance<? extends Filter> injection = (InjectionInstance<? extends Filter>) context.newInstanceFactory(filter.getFilterClass()); InstanceFactory<? extends Filter> factory = template.createInstanceFactory(injection); AtomicReference<FilterInfo> sref = template.registerFilter(null, filter.getFilterName(), context.classProxy(filter.getFilterClass()), filter.isAsyncSupported(), factory); if (filter.getInitParam() != null) { for (ParamValueMetaData init : filter.getInitParam()) { template.addFilterInitParam(sref, init.getParamName(), init.getParamValue()); } } } } if (result.getFilterMappings() != null) { for (FilterMappingMetaData mapping : result.getFilterMappings()) { for (String m : mapping.getUrlPatterns()) { if (mapping.getDispatchers() == null || mapping.getDispatchers().isEmpty()) { template.addFilterMapping(null, mapping.getFilterName(), m, REQUEST); } else { for (DispatcherType dispatcher : mapping.getDispatchers()) { template.addFilterMapping(null, mapping.getFilterName(), m, javax.servlet.DispatcherType.valueOf(dispatcher.name())); } } } } } //listeners if (result.getListeners() != null) { for (ListenerMetaData listener : result.getListeners()) { processorContext.addReflectiveClass(false, false, listener.getListenerClass()); InjectionInstance<? extends EventListener> injection = (InjectionInstance<? extends EventListener>) context.newInstanceFactory(listener.getListenerClass()); InstanceFactory<? extends EventListener> factory = template.createInstanceFactory(injection); template.registerListener(null, context.classProxy(listener.getListenerClass()), factory); } } for (ServletData servlet : deployment.getServlets()) { String servletClass = servlet.getServletClass(); InjectionInstance<? extends Servlet> injection = (InjectionInstance<? extends Servlet>) context.newInstanceFactory(servletClass); InstanceFactory<? extends Servlet> factory = template.createInstanceFactory(injection); template.registerServlet(null, servlet.getName(), context.classProxy(servletClass), true, servlet.getLoadOnStartup(), factory); for (String m : servlet.getMapings()) { template.addServletMapping(null, servlet.getName(), m); } } } try (BytecodeRecorder context = processorContext.addStaticInitTask(RuntimePriority.UNDERTOW_DEPLOY)) { UndertowDeploymentTemplate template = context.getRecordingProxy(UndertowDeploymentTemplate.class); template.bootServletContainer(null); } try (BytecodeRecorder context = processorContext.addDeploymentTask(RuntimePriority.UNDERTOW_START)) { UndertowDeploymentTemplate template = context.getRecordingProxy(UndertowDeploymentTemplate.class); template.startUndertow(null, null, config.getConfig("http.port", "8080")); } } private void handleResources(ArchiveContext archiveContext, ProcessorContext processorContext) throws IOException { Path resources = archiveContext.getRootArchive().getChildPath("META-INF/resources"); if(resources != null) { Files.walk(resources).forEach(new Consumer<Path>() { @Override public void accept(Path path) { if(!Files.isDirectory(path)) { processorContext.addResource(archiveContext.getRootArchive().getArchiveRoot().relativize(path).toString()); } } }); } } @Override public int getPriority() { return 100; } /** * Process a single index. * * @param index the annotation index */ protected WebMetaData processAnnotations(IndexView index) { WebMetaData metaData = new WebMetaData(); // @WebServlet final Collection<AnnotationInstance> webServletAnnotations = index.getAnnotations(webServlet); if (webServletAnnotations != null && webServletAnnotations.size() > 0) { ServletsMetaData servlets = new ServletsMetaData(); List<ServletMappingMetaData> servletMappings = new ArrayList<ServletMappingMetaData>(); for (final AnnotationInstance annotation : webServletAnnotations) { ServletMetaData servlet = new ServletMetaData(); AnnotationTarget target = annotation.target(); ClassInfo classInfo = ClassInfo.class.cast(target); servlet.setServletClass(classInfo.toString()); AnnotationValue nameValue = annotation.value("name"); if (nameValue == null || nameValue.asString().isEmpty()) { servlet.setName(classInfo.toString()); } else { servlet.setName(nameValue.asString()); } AnnotationValue loadOnStartup = annotation.value("loadOnStartup"); if (loadOnStartup != null && loadOnStartup.asInt() >= 0) { servlet.setLoadOnStartupInt(loadOnStartup.asInt()); } AnnotationValue asyncSupported = annotation.value("asyncSupported"); if (asyncSupported != null) { servlet.setAsyncSupported(asyncSupported.asBoolean()); } AnnotationValue initParamsValue = annotation.value("initParams"); if (initParamsValue != null) { AnnotationInstance[] initParamsAnnotations = initParamsValue.asNestedArray(); if (initParamsAnnotations != null && initParamsAnnotations.length > 0) { List<ParamValueMetaData> initParams = new ArrayList<ParamValueMetaData>(); for (AnnotationInstance initParamsAnnotation : initParamsAnnotations) { ParamValueMetaData initParam = new ParamValueMetaData(); AnnotationValue initParamName = initParamsAnnotation.value("name"); AnnotationValue initParamValue = initParamsAnnotation.value(); AnnotationValue initParamDescription = initParamsAnnotation.value("description"); initParam.setParamName(initParamName.asString()); initParam.setParamValue(initParamValue.asString()); if (initParamDescription != null) { Descriptions descriptions = getDescription(initParamDescription.asString()); if (descriptions != null) { initParam.setDescriptions(descriptions); } } initParams.add(initParam); } servlet.setInitParam(initParams); } } AnnotationValue descriptionValue = annotation.value("description"); AnnotationValue displayNameValue = annotation.value("displayName"); AnnotationValue smallIconValue = annotation.value("smallIcon"); AnnotationValue largeIconValue = annotation.value("largeIcon"); DescriptionGroupMetaData descriptionGroup = getDescriptionGroup((descriptionValue == null) ? "" : descriptionValue.asString(), (displayNameValue == null) ? "" : displayNameValue.asString(), (smallIconValue == null) ? "" : smallIconValue.asString(), (largeIconValue == null) ? "" : largeIconValue.asString()); if (descriptionGroup != null) { servlet.setDescriptionGroup(descriptionGroup); } ServletMappingMetaData servletMapping = new ServletMappingMetaData(); servletMapping.setServletName(servlet.getName()); List<String> urlPatterns = new ArrayList<String>(); AnnotationValue urlPatternsValue = annotation.value("urlPatterns"); if (urlPatternsValue != null) { for (String urlPattern : urlPatternsValue.asStringArray()) { urlPatterns.add(urlPattern); } } urlPatternsValue = annotation.value(); if (urlPatternsValue != null) { for (String urlPattern : urlPatternsValue.asStringArray()) { urlPatterns.add(urlPattern); } } if (urlPatterns.size() > 0) { servletMapping.setUrlPatterns(urlPatterns); servletMappings.add(servletMapping); } servlets.add(servlet); } metaData.setServlets(servlets); metaData.setServletMappings(servletMappings); } // @WebFilter final Collection<AnnotationInstance> webFilterAnnotations = index.getAnnotations(webFilter); if (webFilterAnnotations != null && webFilterAnnotations.size() > 0) { FiltersMetaData filters = new FiltersMetaData(); List<FilterMappingMetaData> filterMappings = new ArrayList<FilterMappingMetaData>(); for (final AnnotationInstance annotation : webFilterAnnotations) { FilterMetaData filter = new FilterMetaData(); AnnotationTarget target = annotation.target(); ClassInfo classInfo = ClassInfo.class.cast(target); filter.setFilterClass(classInfo.toString()); AnnotationValue nameValue = annotation.value("filterName"); if (nameValue == null || nameValue.asString().isEmpty()) { filter.setName(classInfo.toString()); } else { filter.setName(nameValue.asString()); } AnnotationValue asyncSupported = annotation.value("asyncSupported"); if (asyncSupported != null) { filter.setAsyncSupported(asyncSupported.asBoolean()); } AnnotationValue initParamsValue = annotation.value("initParams"); if (initParamsValue != null) { AnnotationInstance[] initParamsAnnotations = initParamsValue.asNestedArray(); if (initParamsAnnotations != null && initParamsAnnotations.length > 0) { List<ParamValueMetaData> initParams = new ArrayList<ParamValueMetaData>(); for (AnnotationInstance initParamsAnnotation : initParamsAnnotations) { ParamValueMetaData initParam = new ParamValueMetaData(); AnnotationValue initParamName = initParamsAnnotation.value("name"); AnnotationValue initParamValue = initParamsAnnotation.value(); AnnotationValue initParamDescription = initParamsAnnotation.value("description"); initParam.setParamName(initParamName.asString()); initParam.setParamValue(initParamValue.asString()); if (initParamDescription != null) { Descriptions descriptions = getDescription(initParamDescription.asString()); if (descriptions != null) { initParam.setDescriptions(descriptions); } } initParams.add(initParam); } filter.setInitParam(initParams); } } AnnotationValue descriptionValue = annotation.value("description"); AnnotationValue displayNameValue = annotation.value("displayName"); AnnotationValue smallIconValue = annotation.value("smallIcon"); AnnotationValue largeIconValue = annotation.value("largeIcon"); DescriptionGroupMetaData descriptionGroup = getDescriptionGroup((descriptionValue == null) ? "" : descriptionValue.asString(), (displayNameValue == null) ? "" : displayNameValue.asString(), (smallIconValue == null) ? "" : smallIconValue.asString(), (largeIconValue == null) ? "" : largeIconValue.asString()); if (descriptionGroup != null) { filter.setDescriptionGroup(descriptionGroup); } filters.add(filter); FilterMappingMetaData filterMapping = new FilterMappingMetaData(); filterMapping.setFilterName(filter.getName()); List<String> urlPatterns = new ArrayList<String>(); List<String> servletNames = new ArrayList<String>(); List<DispatcherType> dispatchers = new ArrayList<DispatcherType>(); AnnotationValue urlPatternsValue = annotation.value("urlPatterns"); if (urlPatternsValue != null) { for (String urlPattern : urlPatternsValue.asStringArray()) { urlPatterns.add(urlPattern); } } urlPatternsValue = annotation.value(); if (urlPatternsValue != null) { for (String urlPattern : urlPatternsValue.asStringArray()) { urlPatterns.add(urlPattern); } } if (urlPatterns.size() > 0) { filterMapping.setUrlPatterns(urlPatterns); } AnnotationValue servletNamesValue = annotation.value("servletNames"); if (servletNamesValue != null) { for (String servletName : servletNamesValue.asStringArray()) { servletNames.add(servletName); } } if (servletNames.size() > 0) { filterMapping.setServletNames(servletNames); } AnnotationValue dispatcherTypesValue = annotation.value("dispatcherTypes"); if (dispatcherTypesValue != null) { for (String dispatcherValue : dispatcherTypesValue.asEnumArray()) { dispatchers.add(DispatcherType.valueOf(dispatcherValue)); } } if (dispatchers.size() > 0) { filterMapping.setDispatchers(dispatchers); } if (urlPatterns.size() > 0 || servletNames.size() > 0) { filterMappings.add(filterMapping); } } metaData.setFilters(filters); metaData.setFilterMappings(filterMappings); } // @WebListener final Collection<AnnotationInstance> webListenerAnnotations = index.getAnnotations(webListener); if (webListenerAnnotations != null && webListenerAnnotations.size() > 0) { List<ListenerMetaData> listeners = new ArrayList<ListenerMetaData>(); for (final AnnotationInstance annotation : webListenerAnnotations) { ListenerMetaData listener = new ListenerMetaData(); AnnotationTarget target = annotation.target(); ClassInfo classInfo = ClassInfo.class.cast(target); listener.setListenerClass(classInfo.toString()); AnnotationValue descriptionValue = annotation.value(); if (descriptionValue != null) { DescriptionGroupMetaData descriptionGroup = getDescriptionGroup(descriptionValue.asString()); if (descriptionGroup != null) { listener.setDescriptionGroup(descriptionGroup); } } listeners.add(listener); } metaData.setListeners(listeners); } // @RunAs final Collection<AnnotationInstance> runAsAnnotations = index.getAnnotations(runAs); if (runAsAnnotations != null && runAsAnnotations.size() > 0) { AnnotationsMetaData annotations = metaData.getAnnotations(); if (annotations == null) { annotations = new AnnotationsMetaData(); metaData.setAnnotations(annotations); } for (final AnnotationInstance annotation : runAsAnnotations) { AnnotationTarget target = annotation.target(); if (!(target instanceof ClassInfo)) { continue; } ClassInfo classInfo = ClassInfo.class.cast(target); AnnotationMetaData annotationMD = annotations.get(classInfo.toString()); if (annotationMD == null) { annotationMD = new AnnotationMetaData(); annotationMD.setClassName(classInfo.toString()); annotations.add(annotationMD); } RunAsMetaData runAs = new RunAsMetaData(); runAs.setRoleName(annotation.value().asString()); annotationMD.setRunAs(runAs); } } // @DeclareRoles final Collection<AnnotationInstance> declareRolesAnnotations = index.getAnnotations(declareRoles); if (declareRolesAnnotations != null && declareRolesAnnotations.size() > 0) { SecurityRolesMetaData securityRoles = metaData.getSecurityRoles(); if (securityRoles == null) { securityRoles = new SecurityRolesMetaData(); metaData.setSecurityRoles(securityRoles); } for (final AnnotationInstance annotation : declareRolesAnnotations) { for (String role : annotation.value().asStringArray()) { SecurityRoleMetaData sr = new SecurityRoleMetaData(); sr.setRoleName(role); securityRoles.add(sr); } } } // @MultipartConfig final Collection<AnnotationInstance> multipartConfigAnnotations = index.getAnnotations(multipartConfig); if (multipartConfigAnnotations != null && multipartConfigAnnotations.size() > 0) { AnnotationsMetaData annotations = metaData.getAnnotations(); if (annotations == null) { annotations = new AnnotationsMetaData(); metaData.setAnnotations(annotations); } for (final AnnotationInstance annotation : multipartConfigAnnotations) { AnnotationTarget target = annotation.target(); ClassInfo classInfo = ClassInfo.class.cast(target); AnnotationMetaData annotationMD = annotations.get(classInfo.toString()); if (annotationMD == null) { annotationMD = new AnnotationMetaData(); annotationMD.setClassName(classInfo.toString()); annotations.add(annotationMD); } MultipartConfigMetaData multipartConfig = new MultipartConfigMetaData(); AnnotationValue locationValue = annotation.value("location"); if (locationValue != null && locationValue.asString().length() > 0) { multipartConfig.setLocation(locationValue.asString()); } AnnotationValue maxFileSizeValue = annotation.value("maxFileSize"); if (maxFileSizeValue != null && maxFileSizeValue.asLong() != -1L) { multipartConfig.setMaxFileSize(maxFileSizeValue.asLong()); } AnnotationValue maxRequestSizeValue = annotation.value("maxRequestSize"); if (maxRequestSizeValue != null && maxRequestSizeValue.asLong() != -1L) { multipartConfig.setMaxRequestSize(maxRequestSizeValue.asLong()); } AnnotationValue fileSizeThresholdValue = annotation.value("fileSizeThreshold"); if (fileSizeThresholdValue != null && fileSizeThresholdValue.asInt() != 0) { multipartConfig.setFileSizeThreshold(fileSizeThresholdValue.asInt()); } annotationMD.setMultipartConfig(multipartConfig); } } // @ServletSecurity final Collection<AnnotationInstance> servletSecurityAnnotations = index.getAnnotations(servletSecurity); if (servletSecurityAnnotations != null && servletSecurityAnnotations.size() > 0) { AnnotationsMetaData annotations = metaData.getAnnotations(); if (annotations == null) { annotations = new AnnotationsMetaData(); metaData.setAnnotations(annotations); } for (final AnnotationInstance annotation : servletSecurityAnnotations) { AnnotationTarget target = annotation.target(); ClassInfo classInfo = ClassInfo.class.cast(target); AnnotationMetaData annotationMD = annotations.get(classInfo.toString()); if (annotationMD == null) { annotationMD = new AnnotationMetaData(); annotationMD.setClassName(classInfo.toString()); annotations.add(annotationMD); } ServletSecurityMetaData servletSecurity = new ServletSecurityMetaData(); AnnotationValue httpConstraintValue = annotation.value(); List<String> rolesAllowed = new ArrayList<String>(); if (httpConstraintValue != null) { AnnotationInstance httpConstraint = httpConstraintValue.asNested(); AnnotationValue httpConstraintERSValue = httpConstraint.value(); if (httpConstraintERSValue != null) { servletSecurity.setEmptyRoleSemantic(EmptyRoleSemanticType.valueOf(httpConstraintERSValue.asEnum())); } AnnotationValue httpConstraintTGValue = httpConstraint.value("transportGuarantee"); if (httpConstraintTGValue != null) { servletSecurity.setTransportGuarantee(TransportGuaranteeType.valueOf(httpConstraintTGValue.asEnum())); } AnnotationValue rolesAllowedValue = httpConstraint.value("rolesAllowed"); if (rolesAllowedValue != null) { for (String role : rolesAllowedValue.asStringArray()) { rolesAllowed.add(role); } } } servletSecurity.setRolesAllowed(rolesAllowed); AnnotationValue httpMethodConstraintsValue = annotation.value("httpMethodConstraints"); if (httpMethodConstraintsValue != null) { AnnotationInstance[] httpMethodConstraints = httpMethodConstraintsValue.asNestedArray(); if (httpMethodConstraints.length > 0) { List<HttpMethodConstraintMetaData> methodConstraints = new ArrayList<HttpMethodConstraintMetaData>(); for (AnnotationInstance httpMethodConstraint : httpMethodConstraints) { HttpMethodConstraintMetaData methodConstraint = new HttpMethodConstraintMetaData(); AnnotationValue httpMethodConstraintValue = httpMethodConstraint.value(); if (httpMethodConstraintValue != null) { methodConstraint.setMethod(httpMethodConstraintValue.asString()); } AnnotationValue httpMethodConstraintERSValue = httpMethodConstraint.value("emptyRoleSemantic"); if (httpMethodConstraintERSValue != null) { methodConstraint.setEmptyRoleSemantic(EmptyRoleSemanticType.valueOf(httpMethodConstraintERSValue.asEnum())); } AnnotationValue httpMethodConstraintTGValue = httpMethodConstraint.value("transportGuarantee"); if (httpMethodConstraintTGValue != null) { methodConstraint.setTransportGuarantee(TransportGuaranteeType.valueOf(httpMethodConstraintTGValue.asEnum())); } AnnotationValue rolesAllowedValue = httpMethodConstraint.value("rolesAllowed"); rolesAllowed = new ArrayList<String>(); if (rolesAllowedValue != null) { for (String role : rolesAllowedValue.asStringArray()) { rolesAllowed.add(role); } } methodConstraint.setRolesAllowed(rolesAllowed); methodConstraints.add(methodConstraint); } servletSecurity.setHttpMethodConstraints(methodConstraints); } } annotationMD.setServletSecurity(servletSecurity); } } return metaData; } protected Descriptions getDescription(String description) { DescriptionsImpl descriptions = null; if (description.length() > 0) { DescriptionImpl di = new DescriptionImpl(); di.setDescription(description); descriptions = new DescriptionsImpl(); descriptions.add(di); } return descriptions; } protected DisplayNames getDisplayName(String displayName) { DisplayNamesImpl displayNames = null; if (displayName.length() > 0) { DisplayNameImpl dn = new DisplayNameImpl(); dn.setDisplayName(displayName); displayNames = new DisplayNamesImpl(); displayNames.add(dn); } return displayNames; } protected Icons getIcons(String smallIcon, String largeIcon) { IconsImpl icons = null; if (smallIcon.length() > 0 || largeIcon.length() > 0) { IconImpl i = new IconImpl(); i.setSmallIcon(smallIcon); i.setLargeIcon(largeIcon); icons = new IconsImpl(); icons.add(i); } return icons; } protected DescriptionGroupMetaData getDescriptionGroup(String description) { DescriptionGroupMetaData dg = null; if (description.length() > 0) { dg = new DescriptionGroupMetaData(); Descriptions descriptions = getDescription(description); dg.setDescriptions(descriptions); } return dg; } protected DescriptionGroupMetaData getDescriptionGroup(String description, String displayName, String smallIcon, String largeIcon) { DescriptionGroupMetaData dg = null; if (description.length() > 0 || displayName.length() > 0 || smallIcon.length() > 0 || largeIcon.length() > 0) { dg = new DescriptionGroupMetaData(); Descriptions descriptions = getDescription(description); if (descriptions != null) dg.setDescriptions(descriptions); DisplayNames displayNames = getDisplayName(displayName); if (displayNames != null) dg.setDisplayNames(displayNames); Icons icons = getIcons(smallIcon, largeIcon); if (icons != null) dg.setIcons(icons); } return dg; } }
Init OpenSSL at runtime
undertow/deployment/src/main/java/org/jboss/shamrock/undertow/ServletResourceProcessor.java
Init OpenSSL at runtime
<ide><path>ndertow/deployment/src/main/java/org/jboss/shamrock/undertow/ServletResourceProcessor.java <ide> processorContext.addRuntimeInitializedClasses("io.undertow.server.protocol.ajp.AjpServerResponseConduit"); <ide> processorContext.addRuntimeInitializedClasses("io.undertow.server.protocol.ajp.AjpServerRequestConduit"); <ide> <add> //TODO: this should be somewhere else, as SSL is not specific to Undertow <add> processorContext.addRuntimeInitializedClasses("org.wildfly.openssl.OpenSSLEngine"); <add> <ide> handleResources(archiveContext, processorContext); <ide> <ide> try (BytecodeRecorder context = processorContext.addStaticInitTask(RuntimePriority.UNDERTOW_CREATE_DEPLOYMENT)) {
Java
apache-2.0
a97c7b4343b86647a64f212d8f44e4c3c9d8b4e7
0
datastax/java-driver,datastax/java-driver
/* * Copyright DataStax, Inc. * * 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.datastax.oss.driver.core.type.codec; import com.datastax.oss.driver.api.core.type.codec.MappingCodec; import com.datastax.oss.driver.api.core.type.codec.TypeCodecs; import com.datastax.oss.driver.api.core.type.reflect.GenericType; import edu.umd.cs.findbugs.annotations.Nullable; /** * A sample user codec implementation that we use in our tests. * * <p>It maps a CQL string to a Java string containing its textual representation. */ public class CqlIntToStringCodec extends MappingCodec<Integer, String> { public CqlIntToStringCodec() { super(TypeCodecs.INT, GenericType.STRING); } @Nullable @Override protected String innerToOuter(@Nullable Integer value) { return value == null ? null : value.toString(); } @Nullable @Override protected Integer outerToInner(@Nullable String value) { return value == null ? null : Integer.parseInt(value); } }
integration-tests/src/test/java/com/datastax/oss/driver/core/type/codec/CqlIntToStringCodec.java
/* * Copyright DataStax, Inc. * * 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.datastax.oss.driver.core.type.codec; import com.datastax.oss.driver.api.core.ProtocolVersion; import com.datastax.oss.driver.api.core.type.DataType; import com.datastax.oss.driver.api.core.type.DataTypes; import com.datastax.oss.driver.api.core.type.codec.TypeCodec; import com.datastax.oss.driver.api.core.type.codec.TypeCodecs; import com.datastax.oss.driver.api.core.type.reflect.GenericType; import edu.umd.cs.findbugs.annotations.NonNull; import java.nio.ByteBuffer; /** * A sample user codec implementation that we use in our tests. * * <p>It maps a CQL string to a Java string containing its textual representation. */ public class CqlIntToStringCodec implements TypeCodec<String> { @NonNull @Override public GenericType<String> getJavaType() { return GenericType.STRING; } @NonNull @Override public DataType getCqlType() { return DataTypes.INT; } @Override public ByteBuffer encode(String value, @NonNull ProtocolVersion protocolVersion) { if (value == null) { return null; } else { return TypeCodecs.INT.encode(Integer.parseInt(value), protocolVersion); } } @Override public String decode(ByteBuffer bytes, @NonNull ProtocolVersion protocolVersion) { return TypeCodecs.INT.decode(bytes, protocolVersion).toString(); } @NonNull @Override public String format(String value) { throw new UnsupportedOperationException("Not implemented for this test"); } @Override public String parse(String value) { throw new UnsupportedOperationException("Not implemented for this test"); } }
Make CqlIntToStringCodec extend MappingCodec
integration-tests/src/test/java/com/datastax/oss/driver/core/type/codec/CqlIntToStringCodec.java
Make CqlIntToStringCodec extend MappingCodec
<ide><path>ntegration-tests/src/test/java/com/datastax/oss/driver/core/type/codec/CqlIntToStringCodec.java <ide> */ <ide> package com.datastax.oss.driver.core.type.codec; <ide> <del>import com.datastax.oss.driver.api.core.ProtocolVersion; <del>import com.datastax.oss.driver.api.core.type.DataType; <del>import com.datastax.oss.driver.api.core.type.DataTypes; <del>import com.datastax.oss.driver.api.core.type.codec.TypeCodec; <add>import com.datastax.oss.driver.api.core.type.codec.MappingCodec; <ide> import com.datastax.oss.driver.api.core.type.codec.TypeCodecs; <ide> import com.datastax.oss.driver.api.core.type.reflect.GenericType; <del>import edu.umd.cs.findbugs.annotations.NonNull; <del>import java.nio.ByteBuffer; <add>import edu.umd.cs.findbugs.annotations.Nullable; <ide> <ide> /** <ide> * A sample user codec implementation that we use in our tests. <ide> * <ide> * <p>It maps a CQL string to a Java string containing its textual representation. <ide> */ <del>public class CqlIntToStringCodec implements TypeCodec<String> { <add>public class CqlIntToStringCodec extends MappingCodec<Integer, String> { <ide> <del> @NonNull <del> @Override <del> public GenericType<String> getJavaType() { <del> return GenericType.STRING; <add> public CqlIntToStringCodec() { <add> super(TypeCodecs.INT, GenericType.STRING); <ide> } <ide> <del> @NonNull <add> @Nullable <ide> @Override <del> public DataType getCqlType() { <del> return DataTypes.INT; <add> protected String innerToOuter(@Nullable Integer value) { <add> return value == null ? null : value.toString(); <ide> } <ide> <add> @Nullable <ide> @Override <del> public ByteBuffer encode(String value, @NonNull ProtocolVersion protocolVersion) { <del> if (value == null) { <del> return null; <del> } else { <del> return TypeCodecs.INT.encode(Integer.parseInt(value), protocolVersion); <del> } <del> } <del> <del> @Override <del> public String decode(ByteBuffer bytes, @NonNull ProtocolVersion protocolVersion) { <del> return TypeCodecs.INT.decode(bytes, protocolVersion).toString(); <del> } <del> <del> @NonNull <del> @Override <del> public String format(String value) { <del> throw new UnsupportedOperationException("Not implemented for this test"); <del> } <del> <del> @Override <del> public String parse(String value) { <del> throw new UnsupportedOperationException("Not implemented for this test"); <add> protected Integer outerToInner(@Nullable String value) { <add> return value == null ? null : Integer.parseInt(value); <ide> } <ide> }
JavaScript
apache-2.0
9d536b5958442228f91f143b8aec1bac199fbb5e
0
appbaseio/reactivesearch,appbaseio/reactivesearch,appbaseio/reactivesearch,appbaseio/reactivesearch
import Appbase from 'appbase-js'; import valueReducer from '@appbaseio/reactivecore/lib/reducers/valueReducer'; import queryReducer from '@appbaseio/reactivecore/lib/reducers/queryReducer'; import queryOptionsReducer from '@appbaseio/reactivecore/lib/reducers/queryOptionsReducer'; import dependencyTreeReducer from '@appbaseio/reactivecore/lib/reducers/dependencyTreeReducer'; import { buildQuery, pushToAndClause } from '@appbaseio/reactivecore/lib/utils/helper'; import fetchGraphQL from '@appbaseio/reactivecore/lib/utils/graphQL'; import { componentTypes, validProps } from '@appbaseio/reactivecore/lib/utils/constants'; import { getRSQuery, extractPropsFromState, getDependentQueries, } from '@appbaseio/reactivecore/lib/utils/transform'; import { isPropertyDefined } from '@appbaseio/reactivecore/lib/actions/utils'; const componentsWithHighlightQuery = [componentTypes.dataSearch, componentTypes.categorySearch]; const componentsWithOptions = [ componentTypes.reactiveList, componentTypes.reactiveMap, componentTypes.singleList, componentTypes.multiList, componentTypes.tagCloud, ...componentsWithHighlightQuery, ]; const componentsWithoutFilters = [componentTypes.numberBox, componentTypes.ratingsFilter]; const resultComponents = [componentTypes.reactiveList, componentTypes.reactiveMap]; function getValue(state, id, defaultValue) { if (!state) return defaultValue; if (state[id]) { try { // parsing for next.js - since it uses extra set of quotes to wrap params const parsedValue = JSON.parse(state[id]); return parsedValue; } catch (error) { // using react-dom-server for ssr return state[id] || defaultValue; } } return defaultValue; } function parseValue(value, component) { if (component.source && component.source.parseValue) { return component.source.parseValue(value, component); } return value; } function getQuery(component, value, componentType) { // get default query of result components if (resultComponents.includes(componentType)) { return component.defaultQuery ? component.defaultQuery() : {}; } // get custom or default query of sensor components const currentValue = parseValue(value, component); if (component.customQuery) { const customQuery = component.customQuery(currentValue, component); return customQuery && customQuery.query; } return component.source.defaultQuery ? component.source.defaultQuery(currentValue, component) : {}; } export default function initReactivesearch(componentCollection, searchState, settings) { return new Promise((resolve, reject) => { const credentials = settings.url && settings.url.trim() !== '' && !settings.credentials ? null : settings.credentials; const config = { url: settings.url && settings.url.trim() !== '' ? settings.url : 'https://scalr.api.appbase.io', app: settings.app, credentials, transformRequest: settings.transformRequest || null, type: settings.type ? settings.type : '*', transformResponse: settings.transformResponse || null, graphQLUrl: settings.graphQLUrl || '', headers: settings.headers || {}, analyticsConfig: settings.appbaseConfig || null, }; const appbaseRef = Appbase(config); let components = []; let selectedValues = {}; const internalValues = {}; let queryList = {}; let queryLog = {}; let queryOptions = {}; let dependencyTree = {}; let finalQuery = []; let appbaseQuery = {}; // Use object to prevent duplicate query added by react prop let orderOfQueries = []; let hits = {}; let aggregations = {}; let state = {}; const customQueries = {}; const defaultQueries = {}; const componentProps = {}; componentCollection.forEach((component) => { const { componentType } = component.source; components = [...components, component.componentId]; // Set component props const compProps = {}; Object.keys(component).forEach((key) => { if (validProps.includes(key)) { compProps[key] = component[key]; } }); let isInternalComponentPresent = false; // Set custom and default queries if (component.customQuery && typeof component.customQuery === 'function') { customQueries[component.componentId] = component.customQuery(component.value, compProps); } if (component.defaultQuery && typeof component.defaultQuery === 'function') { defaultQueries[component.componentId] = component.defaultQuery(component.value, compProps); } const isResultComponent = resultComponents.includes(componentType); const internalComponent = `${component.componentId}__internal`; const label = component.filterLabel || component.componentId; const value = getValue( searchState, component.componentId, component.value || component.defaultValue, ); // [1] set selected values let showFilter = component.showFilter !== undefined ? component.showFilter : true; if (componentsWithoutFilters.includes(componentType)) { showFilter = false; } selectedValues = valueReducer(selectedValues, { type: 'SET_VALUE', component: component.componentId, label, value, showFilter, URLParams: component.URLParams || false, }); // [2] set query options - main component query (valid for result components) if (componentsWithOptions.includes(componentType)) { const options = component.source.generateQueryOptions ? component.source.generateQueryOptions(component) : null; let highlightQuery = {}; if (componentsWithHighlightQuery.includes(componentType) && component.highlight) { highlightQuery = component.source.highlightQuery(component); } if ( (options && Object.keys(options).length) || (highlightQuery && Object.keys(highlightQuery).length) ) { // eslint-disable-next-line let { aggs, size, ...otherQueryOptions } = options || {}; if (aggs && Object.keys(aggs).length) { isInternalComponentPresent = true; // query should be applied on the internal component // to enable feeding the data to parent component queryOptions = queryOptionsReducer(queryOptions, { type: 'SET_QUERY_OPTIONS', component: internalComponent, options: { aggs, size: typeof size === 'undefined' ? 100 : size }, }); } // sort, highlight, size, from - query should be applied on the main component if ( (otherQueryOptions && Object.keys(otherQueryOptions).length) || (highlightQuery && Object.keys(highlightQuery).length) ) { if (!otherQueryOptions) otherQueryOptions = {}; if (!highlightQuery) highlightQuery = {}; let mainQueryOptions = { ...otherQueryOptions, ...highlightQuery, size }; if (isInternalComponentPresent) { mainQueryOptions = { ...otherQueryOptions, ...highlightQuery }; } if (isResultComponent) { let currentPage = component.currentPage ? component.currentPage - 1 : 0; if ( selectedValues[component.componentId] && selectedValues[component.componentId].value ) { currentPage = selectedValues[component.componentId].value - 1 || 0; } const resultSize = component.size || 10; const from = currentPage * resultSize; // Update props for RS API compProps.from = from; mainQueryOptions = { ...mainQueryOptions, ...highlightQuery, size: resultSize, from, }; } queryOptions = queryOptionsReducer(queryOptions, { type: 'SET_QUERY_OPTIONS', component: component.componentId, options: { ...mainQueryOptions }, }); } } } // [3] set dependency tree if (component.react || isInternalComponentPresent || isResultComponent) { let { react } = component; if (isInternalComponentPresent || isResultComponent) { react = pushToAndClause(react, internalComponent); } dependencyTree = dependencyTreeReducer(dependencyTree, { type: 'WATCH_COMPONENT', component: component.componentId, react, }); } // [4] set query list if (isResultComponent) { const { query } = getQuery(component, null, componentType); queryList = queryReducer(queryList, { type: 'SET_QUERY', component: internalComponent, query, }); } else { queryList = queryReducer(queryList, { type: 'SET_QUERY', component: component.componentId, query: getQuery(component, value, componentType), }); } // Set component type in component props compProps.componentType = componentType; componentProps[component.componentId] = compProps; }); state = { components, dependencyTree, queryList, queryOptions, selectedValues, internalValues, props: componentProps, customQueries, defaultQueries, }; // [5] Generate finalQuery for search componentCollection.forEach((component) => { // eslint-disable-next-line let { queryObj, options } = buildQuery( component.componentId, dependencyTree, queryList, queryOptions, ); const validOptions = ['aggs', 'from', 'sort']; // check if query or options are valid - non-empty if ( (queryObj && !!Object.keys(queryObj).length) || (options && Object.keys(options).some(item => validOptions.includes(item))) ) { if (!queryObj || (queryObj && !Object.keys(queryObj).length)) { queryObj = { match_all: {} }; } orderOfQueries = [...orderOfQueries, component.componentId]; const currentQuery = { query: { ...queryObj }, ...options, ...queryOptions[component.componentId], }; queryLog = { ...queryLog, [component.componentId]: currentQuery, }; if (settings.enableAppbase) { const query = getRSQuery( component.componentId, extractPropsFromState( state, component.componentId, queryOptions && queryOptions[component.componentId] ? { from: queryOptions[component.componentId].from } : null, ), ); if (query) { // Apply dependent queries appbaseQuery = { ...appbaseQuery, ...{ [component.componentId]: query }, ...getDependentQueries(state, component.componentId, orderOfQueries), }; } } else { finalQuery = [ ...finalQuery, { preference: component.componentId, }, currentQuery, ]; } } }); state.queryLog = queryLog; const handleTransformResponse = (res, component) => { if (config.transformResponse && typeof config.transformResponse === 'function') { return config.transformResponse(res, component); } return new Promise(resolveTransformResponse => resolveTransformResponse(res)); }; const handleResponse = (res) => { const allPromises = orderOfQueries.map( (component, index) => new Promise((responseResolve, responseReject) => { handleTransformResponse(res.responses[index], component) .then((response) => { if (response.aggregations) { aggregations = { ...aggregations, [component]: response.aggregations, }; } hits = { ...hits, [component]: { hits: response.hits.hits, total: typeof response.hits.total === 'object' ? response.hits.total.value : response.hits.total, time: response.took, }, }; responseResolve(); }) .catch(err => responseReject(err)); }), ); Promise.all(allPromises).then(() => { state = { ...state, hits, aggregations, }; resolve(state); }); }; const handleRSResponse = (res) => { const promotedResults = {}; const rawData = {}; const customData = {}; const allPromises = orderOfQueries.map( component => new Promise((responseResolve, responseReject) => { handleTransformResponse(res[component], component) .then((response) => { if (response) { if (response.promoted) { promotedResults[component] = response.promoted.map( promoted => ({ ...promoted.doc, _position: promoted.position, }), ); } rawData[component] = response; // Update custom data if (response.customData) { customData[component] = response.customData; } if (response.aggregations) { aggregations = { ...aggregations, [component]: response.aggregations, }; } hits = { ...hits, [component]: { hits: response.hits.hits, total: typeof response.hits.total === 'object' ? response.hits.total.value : response.hits.total, time: response.took, }, }; responseResolve(); } }) .catch(err => responseReject(err)); }), ); Promise.all(allPromises).then(() => { state = { ...state, hits, aggregations, promotedResults, customData, rawData, }; resolve(state); }); }; if (config.graphQLUrl) { const handleTransformRequest = (res) => { if (config.transformRequest && typeof config.transformRequest === 'function') { const transformRequestPromise = config.transformRequest(res); return transformRequestPromise instanceof Promise ? transformRequestPromise : Promise.resolve(transformRequestPromise); } return Promise.resolve(res); }; handleTransformRequest(finalQuery) .then((requestQuery) => { fetchGraphQL( config.graphQLUrl, config.url, config.credentials, config.app, requestQuery, ) .then((res) => { handleResponse(res); }) .catch(err => reject(err)); }) .catch(err => reject(err)); } else if (settings.enableAppbase && Object.keys(appbaseQuery).length) { finalQuery = Object.keys(appbaseQuery).map(c => appbaseQuery[c]); // Call RS API const rsAPISettings = {}; if (config.analyticsConfig) { rsAPISettings.recordAnalytics = isPropertyDefined(config.analyticsConfig.recordAnalytics) ? config.analyticsConfig.recordAnalytics : undefined; rsAPISettings.userId = isPropertyDefined(config.analyticsConfig.userId) ? config.analyticsConfig.userId : undefined; rsAPISettings.enableQueryRules = isPropertyDefined(config.analyticsConfig.enableQueryRules) ? config.analyticsConfig.enableQueryRules : undefined; rsAPISettings.customEvents = isPropertyDefined(config.analyticsConfig.customEvents) ? config.analyticsConfig.customEvents : undefined; } appbaseRef .reactiveSearchv3(finalQuery, rsAPISettings) .then((res) => { handleRSResponse(res); }) .catch(err => reject(err)); } else { appbaseRef .msearch({ type: config.type === '*' ? '' : config.type, body: finalQuery, }) .then((res) => { handleResponse(res); }) .catch(err => reject(err)); } }); }
packages/web/src/server/index.js
import Appbase from 'appbase-js'; import valueReducer from '@appbaseio/reactivecore/lib/reducers/valueReducer'; import queryReducer from '@appbaseio/reactivecore/lib/reducers/queryReducer'; import queryOptionsReducer from '@appbaseio/reactivecore/lib/reducers/queryOptionsReducer'; import dependencyTreeReducer from '@appbaseio/reactivecore/lib/reducers/dependencyTreeReducer'; import { buildQuery, pushToAndClause } from '@appbaseio/reactivecore/lib/utils/helper'; import fetchGraphQL from '@appbaseio/reactivecore/lib/utils/graphQL'; import { componentTypes, validProps } from '@appbaseio/reactivecore/lib/utils/constants'; import { getRSQuery, extractPropsFromState, getDependentQueries, } from '@appbaseio/reactivecore/lib/utils/transform'; import { isPropertyDefined } from '@appbaseio/reactivecore/lib/actions/utils'; const componentsWithHighlightQuery = [componentTypes.dataSearch, componentTypes.categorySearch]; const componentsWithOptions = [ componentTypes.reactiveList, componentTypes.reactiveMap, componentTypes.singleList, componentTypes.multiList, componentTypes.tagCloud, ...componentsWithHighlightQuery, ]; const componentsWithoutFilters = [componentTypes.numberBox, componentTypes.ratingsFilter]; const resultComponents = [componentTypes.reactiveList, componentTypes.reactiveMap]; function getValue(state, id, defaultValue) { if (!state) return defaultValue; if (state[id]) { try { // parsing for next.js - since it uses extra set of quotes to wrap params const parsedValue = JSON.parse(state[id]); return parsedValue; } catch (error) { // using react-dom-server for ssr return state[id] || defaultValue; } } return defaultValue; } function parseValue(value, component) { if (component.source && component.source.parseValue) { return component.source.parseValue(value, component); } return value; } function getQuery(component, value, componentType) { // get default query of result components if (resultComponents.includes(componentType)) { return component.defaultQuery ? component.defaultQuery() : {}; } // get custom or default query of sensor components const currentValue = parseValue(value, component); if (component.customQuery) { const customQuery = component.customQuery(currentValue, component); return customQuery && customQuery.query; } return component.source.defaultQuery ? component.source.defaultQuery(currentValue, component) : {}; } export default function initReactivesearch(componentCollection, searchState, settings) { return new Promise((resolve, reject) => { const credentials = settings.url && settings.url.trim() !== '' && !settings.credentials ? null : settings.credentials; const config = { url: settings.url && settings.url.trim() !== '' ? settings.url : 'https://scalr.api.appbase.io', app: settings.app, credentials, transformRequest: settings.transformRequest || null, type: settings.type ? settings.type : '*', transformResponse: settings.transformResponse || null, graphQLUrl: settings.graphQLUrl || '', headers: settings.headers || {}, analyticsConfig: settings.appbaseConfig || null, }; const appbaseRef = Appbase(config); let components = []; let selectedValues = {}; const internalValues = {}; let queryList = {}; let queryLog = {}; let queryOptions = {}; let dependencyTree = {}; let finalQuery = []; let appbaseQuery = {}; // Use object to prevent duplicate query added by react prop let orderOfQueries = []; let hits = {}; let aggregations = {}; let state = {}; const customQueries = {}; const defaultQueries = {}; const componentProps = {}; componentCollection.forEach((component) => { const componentType = component.source.componentType; components = [...components, component.componentId]; // Set component props const compProps = {}; Object.keys(component).forEach((key) => { if (validProps.includes(key)) { compProps[key] = component[key]; } }); // Set component type in component props compProps.componentType = componentType; componentProps[component.componentId] = compProps; let isInternalComponentPresent = false; // Set custom and default queries if (component.customQuery && typeof component.customQuery === 'function') { customQueries[component.componentId] = component.customQuery(component.value, compProps); } if (component.defaultQuery && typeof component.defaultQuery === 'function') { defaultQueries[component.componentId] = component.defaultQuery(component.value, compProps); } const isResultComponent = resultComponents.includes(componentType); const internalComponent = `${component.componentId}__internal`; const label = component.filterLabel || component.componentId; const value = getValue( searchState, component.componentId, component.value || component.defaultValue, ); // [1] set selected values let showFilter = component.showFilter !== undefined ? component.showFilter : true; if (componentsWithoutFilters.includes(componentType)) { showFilter = false; } selectedValues = valueReducer(selectedValues, { type: 'SET_VALUE', component: component.componentId, label, value, showFilter, URLParams: component.URLParams || false, }); // [2] set query options - main component query (valid for result components) if (componentsWithOptions.includes(componentType)) { const options = component.source.generateQueryOptions ? component.source.generateQueryOptions(component) : null; let highlightQuery = {}; if (componentsWithHighlightQuery.includes(componentType) && component.highlight) { highlightQuery = component.source.highlightQuery(component); } if ( (options && Object.keys(options).length) || (highlightQuery && Object.keys(highlightQuery).length) ) { // eslint-disable-next-line let { aggs, size, ...otherQueryOptions } = options || {}; if (aggs && Object.keys(aggs).length) { isInternalComponentPresent = true; // query should be applied on the internal component // to enable feeding the data to parent component queryOptions = queryOptionsReducer(queryOptions, { type: 'SET_QUERY_OPTIONS', component: internalComponent, options: { aggs, size: typeof size === 'undefined' ? 100 : size }, }); } // sort, highlight, size, from - query should be applied on the main component if ( (otherQueryOptions && Object.keys(otherQueryOptions).length) || (highlightQuery && Object.keys(highlightQuery).length) ) { if (!otherQueryOptions) otherQueryOptions = {}; if (!highlightQuery) highlightQuery = {}; let mainQueryOptions = { ...otherQueryOptions, ...highlightQuery, size }; if (isInternalComponentPresent) { mainQueryOptions = { ...otherQueryOptions, ...highlightQuery }; } if (isResultComponent) { let currentPage = component.currentPage ? component.currentPage - 1 : 0; if ( selectedValues[component.componentId] && selectedValues[component.componentId].value ) { currentPage = selectedValues[component.componentId].value - 1 || 0; } const resultSize = component.size || 10; mainQueryOptions = { ...mainQueryOptions, ...highlightQuery, size: resultSize, from: currentPage * resultSize, }; } queryOptions = queryOptionsReducer(queryOptions, { type: 'SET_QUERY_OPTIONS', component: component.componentId, options: { ...mainQueryOptions }, }); } } } // [3] set dependency tree if (component.react || isInternalComponentPresent || isResultComponent) { let { react } = component; if (isInternalComponentPresent || isResultComponent) { react = pushToAndClause(react, internalComponent); } dependencyTree = dependencyTreeReducer(dependencyTree, { type: 'WATCH_COMPONENT', component: component.componentId, react, }); } // [4] set query list if (isResultComponent) { const { query } = getQuery(component, null, componentType); queryList = queryReducer(queryList, { type: 'SET_QUERY', component: internalComponent, query, }); } else { queryList = queryReducer(queryList, { type: 'SET_QUERY', component: component.componentId, query: getQuery(component, value, componentType), }); } }); state = { components, dependencyTree, queryList, queryOptions, selectedValues, internalValues, props: componentProps, customQueries, defaultQueries, }; // [5] Generate finalQuery for search componentCollection.forEach((component) => { // eslint-disable-next-line let { queryObj, options } = buildQuery( component.componentId, dependencyTree, queryList, queryOptions, ); const validOptions = ['aggs', 'from', 'sort']; // check if query or options are valid - non-empty if ( (queryObj && !!Object.keys(queryObj).length) || (options && Object.keys(options).some(item => validOptions.includes(item))) ) { if (!queryObj || (queryObj && !Object.keys(queryObj).length)) { queryObj = { match_all: {} }; } orderOfQueries = [...orderOfQueries, component.componentId]; const currentQuery = { query: { ...queryObj }, ...options, ...queryOptions[component.componentId], }; queryLog = { ...queryLog, [component.componentId]: currentQuery, }; if (settings.enableAppbase) { const query = getRSQuery( component.componentId, extractPropsFromState( state, component.componentId, queryOptions && queryOptions[component.componentId] ? { from: queryOptions[component.componentId].from } : null, ), ); if (query) { // Apply dependent queries appbaseQuery = { ...appbaseQuery, ...{ [component.componentId]: query }, ...getDependentQueries(state, component.componentId, orderOfQueries), }; } } else { finalQuery = [ ...finalQuery, { preference: component.componentId, }, currentQuery, ]; } } }); state.queryLog = queryLog; const handleTransformResponse = (res, component) => { if (config.transformResponse && typeof config.transformResponse === 'function') { return config.transformResponse(res, component); } return new Promise(resolveTransformResponse => resolveTransformResponse(res)); }; const handleResponse = (res) => { const allPromises = orderOfQueries.map( (component, index) => new Promise((responseResolve, responseReject) => { handleTransformResponse(res.responses[index], component) .then((response) => { if (response.aggregations) { aggregations = { ...aggregations, [component]: response.aggregations, }; } hits = { ...hits, [component]: { hits: response.hits.hits, total: typeof response.hits.total === 'object' ? response.hits.total.value : response.hits.total, time: response.took, }, }; responseResolve(); }) .catch(err => responseReject(err)); }), ); Promise.all(allPromises).then(() => { state = { ...state, hits, aggregations, }; resolve(state); }); }; const handleRSResponse = (res) => { const promotedResults = {}; const rawData = {}; const customData = {}; const allPromises = orderOfQueries.map( component => new Promise((responseResolve, responseReject) => { handleTransformResponse(res[component], component) .then((response) => { if (response) { if (response.promoted) { promotedResults[component] = response.promoted.map( promoted => ({ ...promoted.doc, _position: promoted.position, }), ); } rawData[component] = response; // Update custom data if (response.customData) { customData[component] = response.customData; } if (response.aggregations) { aggregations = { ...aggregations, [component]: response.aggregations, }; } hits = { ...hits, [component]: { hits: response.hits.hits, total: typeof response.hits.total === 'object' ? response.hits.total.value : response.hits.total, time: response.took, }, }; responseResolve(); } }) .catch(err => responseReject(err)); }), ); Promise.all(allPromises).then(() => { state = { ...state, hits, aggregations, promotedResults, customData, rawData, }; resolve(state); }); }; if (config.graphQLUrl) { const handleTransformRequest = (res) => { if (config.transformRequest && typeof config.transformRequest === 'function') { const transformRequestPromise = config.transformRequest(res); return transformRequestPromise instanceof Promise ? transformRequestPromise : Promise.resolve(transformRequestPromise); } return Promise.resolve(res); }; handleTransformRequest(finalQuery) .then((requestQuery) => { fetchGraphQL( config.graphQLUrl, config.url, config.credentials, config.app, requestQuery, ) .then((res) => { handleResponse(res); }) .catch(err => reject(err)); }) .catch(err => reject(err)); } else if (settings.enableAppbase && Object.keys(appbaseQuery).length) { finalQuery = Object.keys(appbaseQuery).map(c => appbaseQuery[c]); // Call RS API const rsAPISettings = {}; if (config.analyticsConfig) { rsAPISettings.recordAnalytics = isPropertyDefined(config.analyticsConfig.recordAnalytics) ? config.analyticsConfig.recordAnalytics : undefined; rsAPISettings.userId = isPropertyDefined(config.analyticsConfig.userId) ? config.analyticsConfig.userId : undefined; rsAPISettings.enableQueryRules = isPropertyDefined(config.analyticsConfig.enableQueryRules) ? config.analyticsConfig.enableQueryRules : undefined; rsAPISettings.customEvents = isPropertyDefined(config.analyticsConfig.customEvents) ? config.analyticsConfig.customEvents : undefined; } appbaseRef .reactiveSearchv3(finalQuery, rsAPISettings) .then((res) => { handleRSResponse(res); }) .catch(err => reject(err)); } else { appbaseRef .msearch({ type: config.type === '*' ? '' : config.type, body: finalQuery, }) .then((res) => { handleResponse(res); }) .catch(err => reject(err)); } }); }
fix(web): currentPage prop in RL with RS API
packages/web/src/server/index.js
fix(web): currentPage prop in RL with RS API
<ide><path>ackages/web/src/server/index.js <ide> const componentProps = {}; <ide> <ide> componentCollection.forEach((component) => { <del> const componentType = component.source.componentType; <add> const { componentType } = component.source; <ide> components = [...components, component.componentId]; <ide> // Set component props <ide> const compProps = {}; <ide> compProps[key] = component[key]; <ide> } <ide> }); <del> // Set component type in component props <del> compProps.componentType = componentType; <del> componentProps[component.componentId] = compProps; <ide> let isInternalComponentPresent = false; <ide> // Set custom and default queries <ide> if (component.customQuery && typeof component.customQuery === 'function') { <ide> currentPage = selectedValues[component.componentId].value - 1 || 0; <ide> } <ide> const resultSize = component.size || 10; <add> const from = currentPage * resultSize; <add> // Update props for RS API <add> compProps.from = from; <ide> mainQueryOptions = { <ide> ...mainQueryOptions, <ide> ...highlightQuery, <ide> size: resultSize, <del> from: currentPage * resultSize, <add> from, <ide> }; <ide> } <ide> queryOptions = queryOptionsReducer(queryOptions, { <ide> query: getQuery(component, value, componentType), <ide> }); <ide> } <add> // Set component type in component props <add> compProps.componentType = componentType; <add> componentProps[component.componentId] = compProps; <ide> }); <ide> <ide> state = {
JavaScript
bsd-3-clause
error: pathspec 'jquery.porthole.min.js' did not match any file(s) known to git
f9574862093628444ecefb9c8b5c2be4b61b9f32
1
DmitryFillo/jquery.porthole
/* Simple Viewport Plugin Version: 1.0.0 It is licensed under BSD Licence. The license text can be found at https://github.com/DmitryPhilimonov/jquery.porthole/blob/master/LICENSE Author: Mr. Fillo fillo at fillo dot me Website: http://plugins.jquery.com/porthole/ */ (function(a){a.fn.porthole=function(e){function h(b,c){this.maxPos=[a(b).width()-a(c).width(),a(b).height()-a(c).height()];this.curPos=this.getPos(c)}if(void 0==a.portholeStatus)a.portholeStatus=!0;else return!1;e=a.extend({start:[0,0],callback:void 0},e);e.start=e.start.map(function(a){return-a});var f=a(this).attr("id")+"-porthole-wrapper";h.prototype={maxPos:[],curPos:[],getPos:function(b){b=[a(b).css("left"),a(b).css("top")].map(function(a){return a.replace(/px/g,"")});return[parseInt(b[0]),parseInt(b[1])]}, setPos:function(b,c,d){c=0<c?0:c;d=0<d?0:d;c=c<this.maxPos[0]?this.maxPos[0]:c;d=d<this.maxPos[1]?this.maxPos[1]:d;a(b).css({left:c+"px",top:d+"px"})}};var g=!1;a(this).mousedown(function(b){g=!0;var c=b.pageX,d=b.pageY;b=function(b){a.portholeWrapper.setPos("#"+f,b.pageX-c+a.portholeWrapper.curPos[0],b.pageY-d+a.portholeWrapper.curPos[1])};a.throttle?a(document).mousemove(a.throttle(20,!0,b)):a(document).mousemove(b)});a(document).mouseup(function(){if(!0==g)g=!1,a(document).unbind("mousemove"), a.portholeWrapper.curPos=a.portholeWrapper.getPos("#"+f);else return!1});a(this).css({display:"none",overflow:"hidden"}).html('<div id="'+f+'" style="display: inline-block; position: relative; left: '+e.start[0]+"px; top: "+e.start[1]+'px;">'+a(this).html()+"</div>").show(0,function(){a.portholeWrapper=new h(this,"#"+f);void 0!=e.callback&&e.callback()})}})(jQuery);
jquery.porthole.min.js
minified by closure added
jquery.porthole.min.js
minified by closure added
<ide><path>query.porthole.min.js <add>/* <add> Simple Viewport Plugin <add> Version: 1.0.0 <add> <add> It is licensed under BSD Licence. <add> The license text can be found at https://github.com/DmitryPhilimonov/jquery.porthole/blob/master/LICENSE <add> <add> Author: Mr. Fillo <add> fillo at fillo dot me <add> <add> Website: http://plugins.jquery.com/porthole/ <add>*/ <add>(function(a){a.fn.porthole=function(e){function h(b,c){this.maxPos=[a(b).width()-a(c).width(),a(b).height()-a(c).height()];this.curPos=this.getPos(c)}if(void 0==a.portholeStatus)a.portholeStatus=!0;else return!1;e=a.extend({start:[0,0],callback:void 0},e);e.start=e.start.map(function(a){return-a});var f=a(this).attr("id")+"-porthole-wrapper";h.prototype={maxPos:[],curPos:[],getPos:function(b){b=[a(b).css("left"),a(b).css("top")].map(function(a){return a.replace(/px/g,"")});return[parseInt(b[0]),parseInt(b[1])]}, <add>setPos:function(b,c,d){c=0<c?0:c;d=0<d?0:d;c=c<this.maxPos[0]?this.maxPos[0]:c;d=d<this.maxPos[1]?this.maxPos[1]:d;a(b).css({left:c+"px",top:d+"px"})}};var g=!1;a(this).mousedown(function(b){g=!0;var c=b.pageX,d=b.pageY;b=function(b){a.portholeWrapper.setPos("#"+f,b.pageX-c+a.portholeWrapper.curPos[0],b.pageY-d+a.portholeWrapper.curPos[1])};a.throttle?a(document).mousemove(a.throttle(20,!0,b)):a(document).mousemove(b)});a(document).mouseup(function(){if(!0==g)g=!1,a(document).unbind("mousemove"), <add>a.portholeWrapper.curPos=a.portholeWrapper.getPos("#"+f);else return!1});a(this).css({display:"none",overflow:"hidden"}).html('<div id="'+f+'" style="display: inline-block; position: relative; left: '+e.start[0]+"px; top: "+e.start[1]+'px;">'+a(this).html()+"</div>").show(0,function(){a.portholeWrapper=new h(this,"#"+f);void 0!=e.callback&&e.callback()})}})(jQuery);
Java
apache-2.0
f000c6b67948af11a94b56cb01b9df232e397b03
0
peq/WurstScript,wurstscript/WurstScript,Cokemonkey11/WurstScript,wurstscript/WurstScript,peq/WurstScript,Cokemonkey11/WurstScript,wurstscript/WurstScript,Cokemonkey11/WurstScript,Cokemonkey11/WurstScript,Cokemonkey11/WurstScript,peq/WurstScript,peq/WurstScript
package de.peeeq.wurstio.languageserver.requests; import com.google.common.collect.Lists; import com.google.common.io.Files; import de.peeeq.wurstio.gui.WurstGuiImpl; import de.peeeq.wurstio.languageserver.ModelManager; import de.peeeq.wurstio.languageserver.WFile; import de.peeeq.wurstio.mpq.MpqEditor; import de.peeeq.wurstio.mpq.MpqEditorFactory; import de.peeeq.wurstio.utils.W3Utils; import de.peeeq.wurstscript.RunArgs; import de.peeeq.wurstscript.WLogger; import de.peeeq.wurstscript.ast.CompilationUnit; import de.peeeq.wurstscript.ast.WurstModel; import de.peeeq.wurstscript.attributes.CompileError; import de.peeeq.wurstscript.gui.WurstGui; import net.moonlightflower.wc3libs.bin.GameExe; import org.eclipse.lsp4j.MessageType; import javax.swing.filechooser.FileSystemView; import java.io.File; import java.io.IOException; import java.util.List; import java.util.stream.Stream; import static net.moonlightflower.wc3libs.bin.GameExe.VERSION_1_29; /** * Created by peter on 16.05.16. */ public class RunMap extends MapRequest { private final String wc3Path; /** * makes the compilation slower, but more safe by discarding results from the editor and working on a copy of the model */ private SafetyLevel safeCompilation = SafetyLevel.KindOfSafe; /** * The patch version as Version object, e.g. 1.27, 1.28 */ private GameExe.Version patchVersion; private File customTarget = null; enum SafetyLevel { QuickAndDirty, KindOfSafe } public RunMap(WFile workspaceRoot, String wc3Path, File map, List<String> compileArgs) { super(map, compileArgs, workspaceRoot); this.wc3Path = wc3Path; } @Override public Object execute(ModelManager modelManager) { if (modelManager.hasErrors()) { throw new RequestFailedException(MessageType.Error, "Fix errors in your code before running."); } // TODO use normal compiler for this, avoid code duplication WLogger.info("runMap " + map.getAbsolutePath() + " " + compileArgs); WurstGui gui = new WurstGuiImpl(workspaceRoot.getFile().getAbsolutePath()); try { if (wc3Path != null) { W3Utils.parsePatchVersion(new File(wc3Path)); patchVersion = W3Utils.getWc3PatchVersion(); } File gameExe = findGameExecutable(); if (!map.exists()) { throw new RequestFailedException(MessageType.Error, map.getAbsolutePath() + " does not exist."); } gui.sendProgress("Copying map"); // first we copy in same location to ensure validity File buildDir = getBuildDir(); File testMap = new File(buildDir, "WurstRunMap.w3x"); if (testMap.exists()) { boolean deleteOk = testMap.delete(); if (!deleteOk) { throw new RequestFailedException(MessageType.Error, "Could not delete old mapfile: " + testMap); } } Files.copy(map, testMap); // first compile the script: File compiledScript = compileScript(gui, modelManager, compileArgs, testMap, map); WurstModel model = modelManager.getModel(); if (model == null || model.stream().noneMatch((CompilationUnit cu) -> cu.getFile().endsWith("war3map.j"))) { println("No 'war3map.j' file could be found inside the map nor inside the wurst folder"); println("If you compile the map with WurstPack once, this file should be in your wurst-folder. "); println("We will try to start the map now, but it will probably fail. "); } gui.sendProgress("preparing testmap ... "); // then inject the script into the map gui.sendProgress("Injecting mapscript"); try (MpqEditor mpqEditor = MpqEditorFactory.getEditor(testMap)) { mpqEditor.deleteFile("war3map.j"); mpqEditor.insertFile("war3map.j", compiledScript); } String testMapName2 = copyToWarcraftMapDir(testMap); WLogger.info("Starting wc3 ... "); String path = customTarget != null ? new File(customTarget, testMapName2).getAbsolutePath() : "Maps\\Test\\" + testMapName2; // now start the map List<String> cmd = Lists.newArrayList(gameExe.getAbsolutePath(), "-window", "-loadfile", path); if (!System.getProperty("os.name").startsWith("Windows")) { // run with wine cmd.add(0, "wine"); } gui.sendProgress("running " + cmd); Process p = Runtime.getRuntime().exec(cmd.toArray(new String[0])); } catch (CompileError e) { throw new RequestFailedException(MessageType.Error, "There was an error when compiling the map: " + e.getMessage()); } catch (RuntimeException e) { throw e; } catch (final Exception e) { throw new RuntimeException(e); } finally { if (gui.getErrorCount() == 0) { gui.sendFinished(); } } return "ok"; // TODO } /** * Returns the executable for Warcraft III for starting maps * since it changed with 1.28.3 */ private File findGameExecutable() { return (W3Utils.getWc3PatchVersion().compareTo(VERSION_1_29) < 0 ? Stream.of("war3.exe", "War3.exe", "WAR3.EXE", "Warcraft III.exe", "Frozen Throne.exe") : Stream.of("Warcraft III.exe", "Frozen Throne.exe")) .map(exe -> new File(wc3Path, exe)) .filter(File::exists) .findFirst() .orElseThrow(() -> new RuntimeException("No warcraft executatble found in path '" + wc3Path + "'. \n" + "Please check your configuration.")); } /** * Copies the map to the wc3 map directory * <p> * This directory depends on warcraft version and whether we are on windows or wine is used. */ private String copyToWarcraftMapDir(File testMap) throws IOException { String testMapName = "WurstTestMap.w3x"; for (String arg : compileArgs) { if (arg.startsWith("-runmapTarget")) { String path = arg.substring(arg.indexOf(" ") + 1); // copy the map to the specified directory customTarget = new File(path); if (customTarget.exists() && customTarget.isDirectory()) { File testMap2 = new File(customTarget, testMapName); Files.copy(testMap, testMap2); } else { WLogger.severe("Directory specified via -runmapTarget does not exists or is not a directory"); } return testMapName; } } File myDocumentsFolder = FileSystemView.getFileSystemView().getDefaultDirectory(); String documentPath = myDocumentsFolder.getAbsolutePath() + File.separator + "Warcraft III"; if (!new File(documentPath).exists()) { WLogger.info("Warcraft folder " + documentPath + " does not exist."); // Try wine default: documentPath = System.getProperty("user.home") + "/.wine/drive_c/users/" + System.getProperty("user.name") + "/" + myDocumentsFolder.getName() + "/Warcraft III"; if (!new File(documentPath).exists()) { WLogger.severe("Severe: Wine Warcraft folder " + documentPath + " does not exist."); } } if (patchVersion.compareTo(new GameExe.Version("1.27")) <= 0) { // 1.27 and lower compat WLogger.info("Version 1.27 or lower detected, changing file location"); documentPath = wc3Path; } else { // For 1.28+ the wc3/maps/test folder must not contain a map of the same name File oldFile = new File(wc3Path, "Maps" + File.separator + "Test" + File.separator + testMapName); if (oldFile.exists()) { if (!oldFile.delete()) { WLogger.severe("Cannot delete old Wurst Test Map"); } } } // copy the map to the appropriate directory File testFolder = new File(documentPath, "Maps" + File.separator + "Test"); if (testFolder.mkdirs() || testFolder.exists()) { File testMap2 = new File(testFolder, testMapName); Files.copy(testMap, testMap2); } else { WLogger.severe("Could not create Test folder"); } return testMapName; } private File compileScript(WurstGui gui, ModelManager modelManager, List<String> compileArgs, File mapCopy, File origMap) throws Exception { RunArgs runArgs = new RunArgs(compileArgs); print("Compile Script : "); for (File dep : modelManager.getDependencyWurstFiles()) { WLogger.info("dep: " + dep.getPath()); } print("Dependencies done."); processMapScript(runArgs, gui, modelManager, mapCopy); print("Processed mapscript"); if (safeCompilation != SafetyLevel.QuickAndDirty) { // it is safer to rebuild the project, instead of taking the current editor state gui.sendProgress("Cleaning project"); modelManager.clean(); gui.sendProgress("Building project"); modelManager.buildProject(); } if (modelManager.hasErrors()) { for (CompileError compileError : modelManager.getParseErrors()) { gui.sendError(compileError); } throw new RequestFailedException(MessageType.Warning, "Cannot run code with syntax errors."); } WurstModel model = modelManager.getModel(); if (safeCompilation != SafetyLevel.QuickAndDirty) { // compilation will alter the model (e.g. remove unused imports), // so it is safer to create a copy model = ModelManager.copy(model); } return compileMap(gui, mapCopy, origMap, runArgs, model); } }
de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/RunMap.java
package de.peeeq.wurstio.languageserver.requests; import com.google.common.collect.Lists; import com.google.common.io.Files; import de.peeeq.wurstio.gui.WurstGuiImpl; import de.peeeq.wurstio.languageserver.ModelManager; import de.peeeq.wurstio.languageserver.WFile; import de.peeeq.wurstio.mpq.MpqEditor; import de.peeeq.wurstio.mpq.MpqEditorFactory; import de.peeeq.wurstio.utils.W3Utils; import de.peeeq.wurstscript.RunArgs; import de.peeeq.wurstscript.WLogger; import de.peeeq.wurstscript.ast.CompilationUnit; import de.peeeq.wurstscript.ast.WurstModel; import de.peeeq.wurstscript.attributes.CompileError; import de.peeeq.wurstscript.gui.WurstGui; import net.moonlightflower.wc3libs.bin.GameExe; import org.eclipse.lsp4j.MessageType; import javax.swing.filechooser.FileSystemView; import java.io.File; import java.io.IOException; import java.util.List; import java.util.stream.Stream; import static net.moonlightflower.wc3libs.bin.GameExe.VERSION_1_29; /** * Created by peter on 16.05.16. */ public class RunMap extends MapRequest { private final String wc3Path; /** * makes the compilation slower, but more safe by discarding results from the editor and working on a copy of the model */ private SafetyLevel safeCompilation = SafetyLevel.KindOfSafe; /** * The patch version as Version object, e.g. 1.27, 1.28 */ private GameExe.Version patchVersion; private File customTarget = null; enum SafetyLevel { QuickAndDirty, KindOfSafe } public RunMap(WFile workspaceRoot, String wc3Path, File map, List<String> compileArgs) { super(map, compileArgs, workspaceRoot); this.wc3Path = wc3Path; } @Override public Object execute(ModelManager modelManager) { if (modelManager.hasErrors()) { throw new RequestFailedException(MessageType.Error, "Fix errors in your code before running."); } // TODO use normal compiler for this, avoid code duplication WLogger.info("runMap " + map.getAbsolutePath() + " " + compileArgs); WurstGui gui = new WurstGuiImpl(workspaceRoot.getFile().getAbsolutePath()); try { if (wc3Path != null) { W3Utils.parsePatchVersion(new File(wc3Path)); patchVersion = W3Utils.getWc3PatchVersion(); } File gameExe = findGameExecutable(); if (!map.exists()) { throw new RequestFailedException(MessageType.Error, map.getAbsolutePath() + " does not exist."); } gui.sendProgress("Copying map"); // first we copy in same location to ensure validity File buildDir = getBuildDir(); File testMap = new File(buildDir, "WurstRunMap.w3x"); if (testMap.exists()) { boolean deleteOk = testMap.delete(); if (!deleteOk) { throw new RequestFailedException(MessageType.Error, "Could not delete old mapfile: " + testMap); } } Files.copy(map, testMap); // first compile the script: File compiledScript = compileScript(gui, modelManager, compileArgs, testMap, map); WurstModel model = modelManager.getModel(); if (model == null || model.stream().noneMatch((CompilationUnit cu) -> cu.getFile().endsWith("war3map.j"))) { println("No 'war3map.j' file could be found inside the map nor inside the wurst folder"); println("If you compile the map with WurstPack once, this file should be in your wurst-folder. "); println("We will try to start the map now, but it will probably fail. "); } gui.sendProgress("preparing testmap ... "); // then inject the script into the map gui.sendProgress("Injecting mapscript"); try (MpqEditor mpqEditor = MpqEditorFactory.getEditor(testMap)) { mpqEditor.deleteFile("war3map.j"); mpqEditor.insertFile("war3map.j", compiledScript); } String testMapName2 = copyToWarcraftMapDir(testMap); WLogger.info("Starting wc3 ... "); String path = customTarget != null ? new File(customTarget, testMapName2).getAbsolutePath() : "Maps\\Test\\" + testMapName2; // now start the map List<String> cmd = Lists.newArrayList(gameExe.getAbsolutePath(), "-window", "-loadfile", path); if (!System.getProperty("os.name").startsWith("Windows")) { // run with wine cmd.add(0, "wine"); } gui.sendProgress("running " + cmd); Process p = Runtime.getRuntime().exec(cmd.toArray(new String[0])); } catch (CompileError e) { throw new RequestFailedException(MessageType.Error, "There was an error when compiling the map: " + e.getMessage()); } catch (RuntimeException e) { throw e; } catch (final Exception e) { throw new RuntimeException(e); } finally { if (gui.getErrorCount() == 0) { gui.sendFinished(); } } return "ok"; // TODO } /** * Returns the executable for Warcraft III for starting maps * since it changed with 1.28.3 */ private File findGameExecutable() { return (W3Utils.getWc3PatchVersion().compareTo(VERSION_1_29) < 0 ? Stream.of("war3.exe", "War3.exe", "WAR3.EXE", "Warcraft III.exe", "Frozen Throne.exe") : Stream.of("Warcraft III.exe", "Frozen Throne.exe")) .map(exe -> new File(wc3Path, exe)) .filter(File::exists) .findFirst() .orElseThrow(() -> new RuntimeException("No warcraft executatble found in path '" + wc3Path + "'. \n" + "Please check your configuration.")); } /** * Copies the map to the wc3 map directory * <p> * This directory depends on warcraft version and whether we are on windows or wine is used. */ private String copyToWarcraftMapDir(File testMap) throws IOException { String testMapName = "WurstTestMap.w3x"; for (String arg : compileArgs) { if (arg.startsWith("-runmapTarget")) { String path = arg.substring(arg.indexOf(" ") + 1); // copy the map to the specified directory customTarget = new File(path); if (customTarget.exists() && customTarget.isDirectory()) { File testMap2 = new File(customTarget, testMapName); Files.copy(testMap, testMap2); } else { WLogger.severe("Directory specified via -runmapTarget does not exists or is not a directory"); } return testMapName; } } String documentPath = FileSystemView.getFileSystemView().getDefaultDirectory().getPath() + File.separator + "Warcraft III"; if (!new File(documentPath).exists()) { WLogger.info("Warcraft folder " + documentPath + " does not exist."); // Try wine default: documentPath = System.getProperty("user.home") + "/.wine/drive_c/users/" + System.getProperty("user.name") + "/My Documents/Warcraft III"; if (!new File(documentPath).exists()) { WLogger.severe("Wine Warcraft folder " + documentPath + " does not exist."); } } if (patchVersion.compareTo(new GameExe.Version("1.27")) <= 0) { // 1.27 and lower compat print("Version 1.27 or lower detected, changing file location"); documentPath = wc3Path; } else { // For 1.28+ the wc3/maps/test folder must not contain a map of the same name File oldFile = new File(wc3Path, "Maps" + File.separator + "Test" + File.separator + testMapName); if (oldFile.exists()) { if (!oldFile.delete()) { WLogger.severe("Cannot delete old Wurst Test Map"); } } } // copy the map to the appropriate directory File testFolder = new File(documentPath, "Maps" + File.separator + "Test"); if (testFolder.mkdirs() || testFolder.exists()) { File testMap2 = new File(testFolder, testMapName); Files.copy(testMap, testMap2); } else { WLogger.severe("Could not create Test folder"); } return testMapName; } private File compileScript(WurstGui gui, ModelManager modelManager, List<String> compileArgs, File mapCopy, File origMap) throws Exception { RunArgs runArgs = new RunArgs(compileArgs); print("Compile Script : "); for (File dep : modelManager.getDependencyWurstFiles()) { WLogger.info("dep: " + dep.getPath()); } print("Dependencies done."); processMapScript(runArgs, gui, modelManager, mapCopy); print("Processed mapscript"); if (safeCompilation != SafetyLevel.QuickAndDirty) { // it is safer to rebuild the project, instead of taking the current editor state gui.sendProgress("Cleaning project"); modelManager.clean(); gui.sendProgress("Building project"); modelManager.buildProject(); } if (modelManager.hasErrors()) { for (CompileError compileError : modelManager.getParseErrors()) { gui.sendError(compileError); } throw new RequestFailedException(MessageType.Warning, "Cannot run code with syntax errors."); } WurstModel model = modelManager.getModel(); if (safeCompilation != SafetyLevel.QuickAndDirty) { // compilation will alter the model (e.g. remove unused imports), // so it is safer to create a copy model = ModelManager.copy(model); } return compileMap(gui, mapCopy, origMap, runArgs, model); } }
localize wine runmap handling
de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/RunMap.java
localize wine runmap handling
<ide><path>e.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/RunMap.java <ide> return testMapName; <ide> } <ide> } <del> String documentPath = FileSystemView.getFileSystemView().getDefaultDirectory().getPath() + File.separator + "Warcraft III"; <add> File myDocumentsFolder = FileSystemView.getFileSystemView().getDefaultDirectory(); <add> String documentPath = myDocumentsFolder.getAbsolutePath() + File.separator + "Warcraft III"; <ide> if (!new File(documentPath).exists()) { <ide> WLogger.info("Warcraft folder " + documentPath + " does not exist."); <ide> // Try wine default: <ide> documentPath = System.getProperty("user.home") <del> + "/.wine/drive_c/users/" + System.getProperty("user.name") + "/My Documents/Warcraft III"; <add> + "/.wine/drive_c/users/" + System.getProperty("user.name") + "/" + myDocumentsFolder.getName() + "/Warcraft III"; <ide> if (!new File(documentPath).exists()) { <del> WLogger.severe("Wine Warcraft folder " + documentPath + " does not exist."); <add> WLogger.severe("Severe: Wine Warcraft folder " + documentPath + " does not exist."); <ide> } <ide> } <ide> <ide> <ide> if (patchVersion.compareTo(new GameExe.Version("1.27")) <= 0) { <ide> // 1.27 and lower compat <del> print("Version 1.27 or lower detected, changing file location"); <add> WLogger.info("Version 1.27 or lower detected, changing file location"); <ide> documentPath = wc3Path; <ide> } else { <ide> // For 1.28+ the wc3/maps/test folder must not contain a map of the same name
Java
apache-2.0
5ae218e177c07659b9758be54382fa68414bd0ef
0
applango/jongo,bguerout/jongo,ctrimble/jongo,bguerout/jongo,edaubert/jongo,applango/jongo,edaubert/jongo,ctrimble/jongo
/* * Copyright (C) 2011 Benoit GUEROUT <bguerout at gmail dot com> and Yves AMSELLEM <amsellem dot yves at gmail dot com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jongo.query; import com.mongodb.BasicDBList; import com.mongodb.DBObject; import com.mongodb.util.JSON; import com.mongodb.util.JSONCallback; import org.bson.BSON; import org.bson.BSONObject; import org.jongo.bson.Bson; import org.jongo.bson.BsonDocument; import org.jongo.marshall.Marshaller; import org.jongo.marshall.MarshallingException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; public class BsonQueryFactory implements QueryFactory { private static final String DEFAULT_TOKEN = "#"; private static final String MARSHALL_OPERATOR = "$marshall"; private final String token; private final Marshaller marshaller; private static class BsonQuery implements Query { private final DBObject dbo; public BsonQuery(DBObject dbo) { this.dbo = dbo; } public DBObject toDBObject() { return dbo; } } public BsonQueryFactory(Marshaller marshaller) { this(marshaller, DEFAULT_TOKEN); } public BsonQueryFactory(Marshaller marshaller, String token) { this.token = token; this.marshaller = marshaller; } public Query createQuery(final String query, Object... parameters) { if (query == null) { return new BsonQuery((DBObject) JSON.parse(query)); } if (parameters == null) { parameters = new Object[]{null}; } // We have two different cases: // // - tokens as property names "{scores.#: 1}": they must be expanded before going // through the JSON parser, and their toString() is inserted in the query // // - tokens as property values "{id: #}": they are resolved by the JSON parser and // therefore marshalled as DBObjects (actually LazyDBObjects). StringBuilder sb = new StringBuilder(); int paramIncrement = 0; // how many params must be skipped by the next value param int paramPos = 0; // current position in the parameter list int start = 0; // start of the current string segment int pos; // position of the last token found while ((pos = query.indexOf(token, start)) != -1) { if (paramPos >= parameters.length) { throw new IllegalArgumentException("Not enough parameters passed to query: " + query); } // Insert chars before the token sb.append(query, start, pos); // Check if the character preceding the token is one that separates values. // Otherwise, it's a property name substitution if (isValueToken(query, pos)) { // Will be resolved by the JSON parser below sb.append("{\"").append(MARSHALL_OPERATOR).append("\":").append(paramIncrement).append("}"); paramIncrement = 0; } else { // Resolve it now sb.append(parameters[paramPos]); paramIncrement++; } paramPos++; start = pos + token.length(); } // Add remaining chars sb.append(query, start, query.length()); if (paramPos < parameters.length) { throw new IllegalArgumentException("Too many parameters passed to query: " + query); } final Object[] params = parameters; // Parse the query with a callback that will weave in marshalled parameters DBObject dbo; try { dbo = (DBObject) JSON.parse(sb.toString(), new JSONCallback() { int paramPos = 0; @Override public Object objectDone() { String name = curName(); Object o = super.objectDone(); if (o instanceof BSONObject && !(o instanceof List<?>)) { BSONObject dbo = (BSONObject) o; Object marshallValue = dbo.get(MARSHALL_OPERATOR); if (marshallValue != null) { paramPos += ((Number) marshallValue).intValue(); if (paramPos >= params.length) { throw new IllegalArgumentException("Not enough parameters passed to query: " + query); } o = marshallParameter(params[paramPos++]); // Replace value set by super.objectDone() if (!isStackEmpty()) { _put(name, o); } else { o = !BSON.hasDecodeHooks() ? o : BSON.applyDecodingHooks(o); setRoot(o); } } } if (isStackEmpty()) { // End of object } return o; } }); } catch (Exception e) { throw new IllegalArgumentException("Cannot parse query: " + query, e); } return new BsonQuery(dbo); } private boolean isValueToken(String query, int tokenIndex) { for (int pos = tokenIndex; pos >= 0; pos--) { char c = query.charAt(pos); if (c == ':') { return true; } else if (c == '{' || c == '.') { return false; } else if (c == ',') { return !isPropertyName(query, pos - 1); } } return true; } private boolean isPropertyName(String query, int tokenIndex) { for (int pos = tokenIndex; pos >= 0; pos--) { char c = query.charAt(pos); if (c == '[') { return false; } else if (c == '{') { return true; } } return false; } private Object marshallParameter(Object parameter) { try { if (parameter == null || Bson.isPrimitive(parameter)) { return parameter; } if (parameter instanceof Collection) { return marshallCollection((Collection<?>) parameter); } if (parameter instanceof Object[]) { return marshallArray((Object[]) parameter); } return marshallDocument(parameter); } catch (Exception e) { String message = String.format("Unable to marshall parameter: %s", parameter); throw new MarshallingException(message, e); } } private DBObject marshallArray(Object[] parameters) { BasicDBList list = new BasicDBList(); for (final Object parameter : parameters) { list.add(marshallParameter(parameter)); } return list; } private DBObject marshallCollection(Collection<?> parameters) { BasicDBList list = new BasicDBList(); for (Object param : parameters) { list.add(marshallParameter(param)); } return list; } private Object marshallDocument(Object parameter) { if (parameter instanceof Enum) { return marshallParameterAsPrimitive(parameter); } else { BsonDocument document = marshaller.marshall(parameter); if (hasBeenSerializedAsPrimitive(document)) { return marshallParameterAsPrimitive(parameter); } else { return document.toDBObject(); } } } private boolean hasBeenSerializedAsPrimitive(BsonDocument document) { byte[] bytes = document.toByteArray(); if (bytes.length > 4) { return bytes.length != document.getSize(); } return true; } /** * The object may have been serialized to a primitive type with a * custom serializer, so try again after wrapping as an object property. * We do this trick only as a falllback since it causes Jackson to consider the parameter * as "Object" and thus ignore any annotations that may exist on its actual class. */ private Object marshallParameterAsPrimitive(Object parameter) { Map<String, Object> primitiveWrapper = Collections.singletonMap("wrapped", parameter); BsonDocument document = marshaller.marshall(primitiveWrapper); return document.toDBObject().get("wrapped"); } }
src/main/java/org/jongo/query/BsonQueryFactory.java
/* * Copyright (C) 2011 Benoit GUEROUT <bguerout at gmail dot com> and Yves AMSELLEM <amsellem dot yves at gmail dot com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jongo.query; import com.mongodb.BasicDBList; import com.mongodb.DBObject; import com.mongodb.util.JSON; import com.mongodb.util.JSONCallback; import org.bson.BSON; import org.bson.BSONObject; import org.jongo.bson.Bson; import org.jongo.bson.BsonDocument; import org.jongo.marshall.Marshaller; import org.jongo.marshall.MarshallingException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; public class BsonQueryFactory implements QueryFactory { private static final String DEFAULT_TOKEN = "#"; private static final String MARSHALL_OPERATOR = "$marshall"; private final String token; private final Marshaller marshaller; private static class BsonQuery implements Query { private final DBObject dbo; public BsonQuery(DBObject dbo) { this.dbo = dbo; } public DBObject toDBObject() { return dbo; } } public BsonQueryFactory(Marshaller marshaller) { this(marshaller, DEFAULT_TOKEN); } public BsonQueryFactory(Marshaller marshaller, String token) { this.token = token; this.marshaller = marshaller; } public Query createQuery(final String query, Object... parameters) { if (query == null) { return new BsonQuery((DBObject) JSON.parse(query)); } if (parameters == null) { parameters = new Object[]{null}; } // We have two different cases: // // - tokens as property names "{scores.#: 1}": they must be expanded before going // through the JSON parser, and their toString() is inserted in the query // // - tokens as property values "{id: #}": they are resolved by the JSON parser and // therefore marshalled as DBObjects (actually LazyDBObjects). StringBuilder sb = new StringBuilder(); int paramIncrement = 0; // how many params must be skipped by the next value param int paramPos = 0; // current position in the parameter list int start = 0; // start of the current string segment int pos; // position of the last token found while ((pos = query.indexOf(token, start)) != -1) { if (paramPos >= parameters.length) { throw new IllegalArgumentException("Not enough parameters passed to query: " + query); } // Insert chars before the token sb.append(query, start, pos); // Check if the character preceding the token is one that separates values. // Otherwise, it's a property name substitution if (isValueToken(query, pos)) { // Will be resolved by the JSON parser below sb.append("{\"").append(MARSHALL_OPERATOR).append("\":").append(paramIncrement).append("}"); paramIncrement = 0; } else { // Resolve it now sb.append(parameters[paramPos]); paramIncrement++; } paramPos++; start = pos + token.length(); } // Add remaining chars sb.append(query, start, query.length()); if (paramPos < parameters.length) { throw new IllegalArgumentException("Too many parameters passed to query: " + query); } final Object[] params = parameters; // Parse the query with a callback that will weave in marshalled parameters DBObject dbo; try { dbo = (DBObject) JSON.parse(sb.toString(), new JSONCallback() { int paramPos = 0; @Override public Object objectDone() { String name = curName(); Object o = super.objectDone(); if (o instanceof BSONObject && !(o instanceof List<?>)) { BSONObject dbo = (BSONObject) o; Object marshallValue = dbo.get(MARSHALL_OPERATOR); if (marshallValue != null) { paramPos += ((Number) marshallValue).intValue(); if (paramPos >= params.length) { throw new IllegalArgumentException("Not enough parameters passed to query: " + query); } o = marshallParameter(params[paramPos++]); // Replace value set by super.objectDone() if (!isStackEmpty()) { _put(name, o); } else { o = !BSON.hasDecodeHooks() ? o : BSON.applyDecodingHooks(o); setRoot(o); } } } if (isStackEmpty()) { // End of object } return o; } }); } catch (Exception e) { throw new IllegalArgumentException("Cannot parse query: " + query, e); } return new BsonQuery(dbo); } private boolean isValueToken(String query, int tokenIndex) { for (int pos = tokenIndex; pos >= 0; pos--) { char c = query.charAt(pos); if (c == ':') { return true; } else if (c == '{' || c == '.') { return false; } else if (c == ',') { return !isPropertyName(query, pos - 1); } } return true; } private boolean isPropertyName(String query, int tokenIndex) { for (int pos = tokenIndex; pos >= 0; pos--) { char c = query.charAt(pos); if (c == '[') { return false; } else if (c == '{') { return true; } } return false; } private Object marshallParameter(Object parameter) { try { if (parameter == null || Bson.isPrimitive(parameter)) { return parameter; } if (parameter instanceof Collection) { return marshallCollection((Collection<?>) parameter); } if (parameter instanceof Object[]) { return marshallArray((Object[]) parameter); } return marshallDocument(parameter); } catch (Exception e) { String message = String.format("Unable to marshall parameter: %s", parameter); throw new MarshallingException(message, e); } } private DBObject marshallArray(Object[] parameters) { BasicDBList list = new BasicDBList(); for (int i = 0; i < parameters.length; i++) { list.add(marshallParameter(parameters[i])); } return list; } private DBObject marshallCollection(Collection<?> parameters) { BasicDBList list = new BasicDBList(); for (Object param : parameters) { list.add(marshallParameter(param)); } return list; } private Object marshallDocument(Object parameter) { if (parameter instanceof Enum) { return marshallParameterAsPrimitive(parameter); } else { BsonDocument document = marshaller.marshall(parameter); if (hasBeenSerializedAsPrimitive(document)) { return marshallParameterAsPrimitive(parameter); } else { return document.toDBObject(); } } } private boolean hasBeenSerializedAsPrimitive(BsonDocument document) { byte[] bytes = document.toByteArray(); if (bytes.length > 4) { return bytes.length != document.getSize(); } return true; } /** * The object may have been serialized to a primitive type with a * custom serializer, so try again after wrapping as an object property. * We do this trick only as a falllback since it causes Jackson to consider the parameter * as "Object" and thus ignore any annotations that may exist on its actual class. */ private Object marshallParameterAsPrimitive(Object parameter) { Map<String, Object> primitiveWrapper = Collections.singletonMap("wrapped", parameter); BsonDocument document = marshaller.marshall(primitiveWrapper); return document.toDBObject().get("wrapped"); } }
Convert for into foreach
src/main/java/org/jongo/query/BsonQueryFactory.java
Convert for into foreach
<ide><path>rc/main/java/org/jongo/query/BsonQueryFactory.java <ide> <ide> private DBObject marshallArray(Object[] parameters) { <ide> BasicDBList list = new BasicDBList(); <del> for (int i = 0; i < parameters.length; i++) { <del> list.add(marshallParameter(parameters[i])); <add> for (final Object parameter : parameters) { <add> list.add(marshallParameter(parameter)); <ide> } <ide> return list; <ide> }
Java
epl-1.0
b76162c1bf82cc368dbb78cbebca3d50e30eb5b8
0
tx1103mark/controller,Johnson-Chou/test,tx1103mark/controller,Sushma7785/OpenDayLight-Load-Balancer,mandeepdhami/controller,inocybe/odl-controller,inocybe/odl-controller,mandeepdhami/controller,tx1103mark/controller,Johnson-Chou/test,tx1103mark/controller,522986491/controller,opendaylight/controller,Sushma7785/OpenDayLight-Load-Balancer,522986491/controller,mandeepdhami/controller,mandeepdhami/controller
/* * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.md.sal.dom.broker.impl; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import com.google.common.collect.ImmutableSet; import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import javax.annotation.concurrent.GuardedBy; import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener; import org.opendaylight.controller.md.sal.dom.api.DOMRpcException; import org.opendaylight.controller.md.sal.dom.api.DOMRpcIdentifier; import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementation; import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationRegistration; import org.opendaylight.controller.md.sal.dom.api.DOMRpcProviderService; import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult; import org.opendaylight.controller.md.sal.dom.api.DOMRpcService; import org.opendaylight.controller.md.sal.dom.spi.AbstractDOMRpcImplementationRegistration; import org.opendaylight.yangtools.concepts.AbstractListenerRegistration; import org.opendaylight.yangtools.concepts.ListenerRegistration; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.model.api.SchemaContextListener; import org.opendaylight.yangtools.yang.model.api.SchemaPath; public final class DOMRpcRouter implements AutoCloseable, DOMRpcService, DOMRpcProviderService, SchemaContextListener { private static final ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder().setNameFormat("DOMRpcRouter-listener-%s").setDaemon(true).build(); private final ExecutorService listenerNotifier = Executors.newSingleThreadExecutor(THREAD_FACTORY); @GuardedBy("this") private Collection<ListenerRegistration<? extends DOMRpcAvailabilityListener>> listeners = Collections.emptyList(); private volatile DOMRpcRoutingTable routingTable = DOMRpcRoutingTable.EMPTY; @Override public <T extends DOMRpcImplementation> DOMRpcImplementationRegistration<T> registerRpcImplementation(final T implementation, final DOMRpcIdentifier... rpcs) { return registerRpcImplementation(implementation, ImmutableSet.copyOf(rpcs)); } private static Collection<DOMRpcIdentifier> notPresentRpcs(final DOMRpcRoutingTable table, final Collection<DOMRpcIdentifier> candidates) { return ImmutableSet.copyOf(Collections2.filter(candidates, new Predicate<DOMRpcIdentifier>() { @Override public boolean apply(final DOMRpcIdentifier input) { return !table.contains(input); } })); } private synchronized void removeRpcImplementation(final DOMRpcImplementation implementation, final Set<DOMRpcIdentifier> rpcs) { final DOMRpcRoutingTable oldTable = routingTable; final DOMRpcRoutingTable newTable = oldTable.remove(implementation, rpcs); final Collection<DOMRpcIdentifier> removedRpcs = notPresentRpcs(newTable, rpcs); routingTable = newTable; if(!removedRpcs.isEmpty()) { final Collection<ListenerRegistration<? extends DOMRpcAvailabilityListener>> capturedListeners = listeners; listenerNotifier.execute(new Runnable() { @Override public void run() { for (final ListenerRegistration<? extends DOMRpcAvailabilityListener> l : capturedListeners) { // Need to ensure removed listeners do not get notified synchronized (DOMRpcRouter.this) { if (listeners.contains(l)) { l.getInstance().onRpcUnavailable(removedRpcs); } } } } }); } } @Override public synchronized <T extends DOMRpcImplementation> DOMRpcImplementationRegistration<T> registerRpcImplementation(final T implementation, final Set<DOMRpcIdentifier> rpcs) { final DOMRpcRoutingTable oldTable = routingTable; final DOMRpcRoutingTable newTable = oldTable.add(implementation, rpcs); final Collection<DOMRpcIdentifier> addedRpcs = notPresentRpcs(oldTable, rpcs); routingTable = newTable; if(!addedRpcs.isEmpty()) { final Collection<ListenerRegistration<? extends DOMRpcAvailabilityListener>> capturedListeners = listeners; listenerNotifier.execute(new Runnable() { @Override public void run() { for (final ListenerRegistration<? extends DOMRpcAvailabilityListener> l : capturedListeners) { // Need to ensure removed listeners do not get notified synchronized (DOMRpcRouter.this) { if (listeners.contains(l)) { l.getInstance().onRpcAvailable(addedRpcs); } } } } }); } return new AbstractDOMRpcImplementationRegistration<T>(implementation) { @Override protected void removeRegistration() { removeRpcImplementation(getInstance(), rpcs); } }; } @Override public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(final SchemaPath type, final NormalizedNode<?, ?> input) { return routingTable.invokeRpc(type, input); } private synchronized void removeListener(final ListenerRegistration<? extends DOMRpcAvailabilityListener> reg) { listeners = ImmutableList.copyOf(Collections2.filter(listeners, new Predicate<Object>() { @Override public boolean apply(final Object input) { return !reg.equals(input); } })); } @Override public synchronized <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(final T listener) { final ListenerRegistration<T> ret = new AbstractListenerRegistration<T>(listener) { @Override protected void removeRegistration() { removeListener(this); } }; final Builder<ListenerRegistration<? extends DOMRpcAvailabilityListener>> b = ImmutableList.builder(); b.addAll(listeners); b.add(ret); listeners = b.build(); final Map<SchemaPath, Set<YangInstanceIdentifier>> capturedRpcs = routingTable.getRpcs(); listenerNotifier.execute(new Runnable() { @Override public void run() { for (final Entry<SchemaPath, Set<YangInstanceIdentifier>> e : capturedRpcs.entrySet()) { listener.onRpcAvailable(Collections2.transform(e.getValue(), new Function<YangInstanceIdentifier, DOMRpcIdentifier>() { @Override public DOMRpcIdentifier apply(final YangInstanceIdentifier input) { return DOMRpcIdentifier.create(e.getKey(), input); } })); } } }); return ret; } @Override public synchronized void onGlobalContextUpdated(final SchemaContext context) { final DOMRpcRoutingTable oldTable = routingTable; final DOMRpcRoutingTable newTable = oldTable.setSchemaContext(context); routingTable = newTable; } @Override public void close() { listenerNotifier.shutdown(); } }
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMRpcRouter.java
/* * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.md.sal.dom.broker.impl; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import com.google.common.collect.ImmutableSet; import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import javax.annotation.concurrent.GuardedBy; import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener; import org.opendaylight.controller.md.sal.dom.api.DOMRpcException; import org.opendaylight.controller.md.sal.dom.api.DOMRpcIdentifier; import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementation; import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationRegistration; import org.opendaylight.controller.md.sal.dom.api.DOMRpcProviderService; import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult; import org.opendaylight.controller.md.sal.dom.api.DOMRpcService; import org.opendaylight.controller.md.sal.dom.spi.AbstractDOMRpcImplementationRegistration; import org.opendaylight.yangtools.concepts.AbstractListenerRegistration; import org.opendaylight.yangtools.concepts.ListenerRegistration; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.model.api.SchemaContextListener; import org.opendaylight.yangtools.yang.model.api.SchemaPath; public final class DOMRpcRouter implements AutoCloseable, DOMRpcService, DOMRpcProviderService, SchemaContextListener { private static final ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder().setNameFormat("DOMRpcRouter-listener-%s").setDaemon(true).build(); private final ExecutorService listenerNotifier = Executors.newSingleThreadExecutor(THREAD_FACTORY); @GuardedBy("this") private Collection<ListenerRegistration<? extends DOMRpcAvailabilityListener>> listeners = Collections.emptyList(); private volatile DOMRpcRoutingTable routingTable = DOMRpcRoutingTable.EMPTY; @Override public <T extends DOMRpcImplementation> DOMRpcImplementationRegistration<T> registerRpcImplementation(final T implementation, final DOMRpcIdentifier... rpcs) { return registerRpcImplementation(implementation, ImmutableSet.copyOf(rpcs)); } private static Collection<DOMRpcIdentifier> notPresentRpcs(final DOMRpcRoutingTable table, final Collection<DOMRpcIdentifier> candidates) { return ImmutableSet.copyOf(Collections2.filter(candidates, new Predicate<DOMRpcIdentifier>() { @Override public boolean apply(final DOMRpcIdentifier input) { return !table.contains(input); } })); } private synchronized void removeRpcImplementation(final DOMRpcImplementation implementation, final Set<DOMRpcIdentifier> rpcs) { final DOMRpcRoutingTable oldTable = routingTable; final DOMRpcRoutingTable newTable = oldTable.remove(implementation, rpcs); final Collection<DOMRpcIdentifier> removedRpcs = notPresentRpcs(newTable, rpcs); final Collection<ListenerRegistration<? extends DOMRpcAvailabilityListener>> capturedListeners = listeners; routingTable = newTable; listenerNotifier.execute(new Runnable() { @Override public void run() { for (ListenerRegistration<? extends DOMRpcAvailabilityListener> l : capturedListeners) { // Need to ensure removed listeners do not get notified synchronized (DOMRpcRouter.this) { if (listeners.contains(l)) { l.getInstance().onRpcUnavailable(removedRpcs); } } } } }); } @Override public synchronized <T extends DOMRpcImplementation> DOMRpcImplementationRegistration<T> registerRpcImplementation(final T implementation, final Set<DOMRpcIdentifier> rpcs) { final DOMRpcRoutingTable oldTable = routingTable; final DOMRpcRoutingTable newTable = oldTable.add(implementation, rpcs); final Collection<DOMRpcIdentifier> addedRpcs = notPresentRpcs(oldTable, rpcs); final Collection<ListenerRegistration<? extends DOMRpcAvailabilityListener>> capturedListeners = listeners; routingTable = newTable; listenerNotifier.execute(new Runnable() { @Override public void run() { for (ListenerRegistration<? extends DOMRpcAvailabilityListener> l : capturedListeners) { // Need to ensure removed listeners do not get notified synchronized (DOMRpcRouter.this) { if (listeners.contains(l)) { l.getInstance().onRpcAvailable(addedRpcs); } } } } }); return new AbstractDOMRpcImplementationRegistration<T>(implementation) { @Override protected void removeRegistration() { removeRpcImplementation(getInstance(), rpcs); } }; } @Override public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(final SchemaPath type, final NormalizedNode<?, ?> input) { return routingTable.invokeRpc(type, input); } private synchronized void removeListener(final ListenerRegistration<? extends DOMRpcAvailabilityListener> reg) { listeners = ImmutableList.copyOf(Collections2.filter(listeners, new Predicate<Object>() { @Override public boolean apply(final Object input) { return !reg.equals(input); } })); } @Override public synchronized <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(final T listener) { final ListenerRegistration<T> ret = new AbstractListenerRegistration<T>(listener) { @Override protected void removeRegistration() { removeListener(this); } }; final Builder<ListenerRegistration<? extends DOMRpcAvailabilityListener>> b = ImmutableList.builder(); b.addAll(listeners); b.add(ret); listeners = b.build(); final Map<SchemaPath, Set<YangInstanceIdentifier>> capturedRpcs = routingTable.getRpcs(); listenerNotifier.execute(new Runnable() { @Override public void run() { for (final Entry<SchemaPath, Set<YangInstanceIdentifier>> e : capturedRpcs.entrySet()) { listener.onRpcAvailable(Collections2.transform(e.getValue(), new Function<YangInstanceIdentifier, DOMRpcIdentifier>() { @Override public DOMRpcIdentifier apply(final YangInstanceIdentifier input) { return DOMRpcIdentifier.create(e.getKey(), input); } })); } } }); return ret; } @Override public synchronized void onGlobalContextUpdated(final SchemaContext context) { final DOMRpcRoutingTable oldTable = routingTable; final DOMRpcRoutingTable newTable = oldTable.setSchemaContext(context); routingTable = newTable; } @Override public void close() { listenerNotifier.shutdown(); } }
Bug 3234: Do not notify empty Rpc implementation change. DOMRpcBroker was sending notifications with empty set of RPC added or removed. This is possible if registration for RPC already exists and another one was registered. Change-Id: Iab92d6f1e5c76a050dc00dee802e1698ca26eccc Signed-off-by: Tony Tkacik <[email protected]> (cherry picked from commit 2b2ee780fded7fca2d2a3e4695e3aec7f6c1bcc2)
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMRpcRouter.java
Bug 3234: Do not notify empty Rpc implementation change.
<ide><path>pendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMRpcRouter.java <ide> final DOMRpcRoutingTable newTable = oldTable.remove(implementation, rpcs); <ide> <ide> final Collection<DOMRpcIdentifier> removedRpcs = notPresentRpcs(newTable, rpcs); <del> final Collection<ListenerRegistration<? extends DOMRpcAvailabilityListener>> capturedListeners = listeners; <ide> routingTable = newTable; <del> <del> listenerNotifier.execute(new Runnable() { <del> @Override <del> public void run() { <del> for (ListenerRegistration<? extends DOMRpcAvailabilityListener> l : capturedListeners) { <del> // Need to ensure removed listeners do not get notified <del> synchronized (DOMRpcRouter.this) { <del> if (listeners.contains(l)) { <del> l.getInstance().onRpcUnavailable(removedRpcs); <add> if(!removedRpcs.isEmpty()) { <add> final Collection<ListenerRegistration<? extends DOMRpcAvailabilityListener>> capturedListeners = listeners; <add> listenerNotifier.execute(new Runnable() { <add> @Override <add> public void run() { <add> for (final ListenerRegistration<? extends DOMRpcAvailabilityListener> l : capturedListeners) { <add> // Need to ensure removed listeners do not get notified <add> synchronized (DOMRpcRouter.this) { <add> if (listeners.contains(l)) { <add> l.getInstance().onRpcUnavailable(removedRpcs); <add> } <ide> } <ide> } <ide> } <del> } <del> }); <add> }); <add> } <ide> } <ide> <ide> @Override <ide> final DOMRpcRoutingTable newTable = oldTable.add(implementation, rpcs); <ide> <ide> final Collection<DOMRpcIdentifier> addedRpcs = notPresentRpcs(oldTable, rpcs); <del> final Collection<ListenerRegistration<? extends DOMRpcAvailabilityListener>> capturedListeners = listeners; <ide> routingTable = newTable; <ide> <del> listenerNotifier.execute(new Runnable() { <del> @Override <del> public void run() { <del> for (ListenerRegistration<? extends DOMRpcAvailabilityListener> l : capturedListeners) { <del> // Need to ensure removed listeners do not get notified <del> synchronized (DOMRpcRouter.this) { <del> if (listeners.contains(l)) { <del> l.getInstance().onRpcAvailable(addedRpcs); <add> if(!addedRpcs.isEmpty()) { <add> final Collection<ListenerRegistration<? extends DOMRpcAvailabilityListener>> capturedListeners = listeners; <add> listenerNotifier.execute(new Runnable() { <add> @Override <add> public void run() { <add> for (final ListenerRegistration<? extends DOMRpcAvailabilityListener> l : capturedListeners) { <add> // Need to ensure removed listeners do not get notified <add> synchronized (DOMRpcRouter.this) { <add> if (listeners.contains(l)) { <add> l.getInstance().onRpcAvailable(addedRpcs); <add> } <ide> } <ide> } <ide> } <del> } <del> }); <add> }); <add> } <ide> <ide> return new AbstractDOMRpcImplementationRegistration<T>(implementation) { <ide> @Override
Java
apache-2.0
9203c8ca0339371d82c34bb1f9091e7c583f48f2
0
juanavelez/crabzilla,juanavelez/crabzilla,crabzilla/crabzilla
crabzilla-vertx/src/main/java/io/github/crabzilla/vertx/entity/EntityCommandHttpRpcVerticle.java
package io.github.crabzilla.vertx.entity; import io.github.crabzilla.core.entity.EntityCommand; import io.github.crabzilla.core.entity.EntityUnitOfWork; import io.vertx.core.AbstractVerticle; import io.vertx.core.Future; import io.vertx.core.eventbus.DeliveryOptions; import io.vertx.core.http.CaseInsensitiveHeaders; import io.vertx.core.http.HttpServerResponse; import io.vertx.core.json.Json; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.BodyHandler; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import lombok.val; import java.util.UUID; import static io.github.crabzilla.vertx.helpers.StringHelper.*; @Slf4j public class EntityCommandHttpRpcVerticle<E> extends AbstractVerticle { private final Class<E> aggregateRootClass; private final JsonObject config; private final EntityUnitOfWorkRepository entityUowRepo; public EntityCommandHttpRpcVerticle(@NonNull Class<E> aggregateRootClass, @NonNull JsonObject config, @NonNull EntityUnitOfWorkRepository entityUowRepo) { this.aggregateRootClass = aggregateRootClass; this.config = config; this.entityUowRepo = entityUowRepo; } @Override public void start() throws Exception { val router = Router.router(vertx); router.route().handler(BodyHandler.create()); router.post("/" + aggregateId(aggregateRootClass) + "/commands") .handler(this::postCommandHandler); router.get("/" + aggregateId(aggregateRootClass) + "/commands/:cmdID") .handler(this::getUowByCmdId); val server = vertx.createHttpServer(); server.requestHandler(router::accept) .listen(config.getInteger("http.port")); } void postCommandHandler(RoutingContext routingContext) { final HttpServerResponse httpResp = routingContext.response(); final String commandStr = routingContext.getBodyAsString(); log.info("command=:\n" + commandStr); final EntityCommand command = Json.decodeValue(commandStr, EntityCommand.class); if (command == null) { sendError(400, httpResp); return ; } final String cmdID = command.getCommandId().toString(); final Future<EntityUnitOfWork> uowFuture = Future.future(); entityUowRepo.getUowByCmdId(UUID.fromString(cmdID), uowFuture); uowFuture.setHandler(uowResult -> { if (uowResult.failed()) { sendError(500, httpResp); return; } if (uowResult.result() != null) { httpResp.setStatusCode(201); val location = routingContext.request().absoluteURI() + "/" + uowResult.result().getCommand().getCommandId().toString(); httpResp.headers().add("Location", location); val resultAsJson = Json.encode(uowResult.result()); httpResp.headers().add("Content-Type", "application/json"); httpResp.end(resultAsJson); return ; } val options = new DeliveryOptions().setCodecName(EntityCommand.class.getSimpleName()); vertx.<EntityCommandExecution>eventBus().send(commandHandlerId(aggregateRootClass), command, options, response -> { if (!response.succeeded()) { log.error("eventbus.handleCommand", response.cause()); httpResp.setStatusCode(500); httpResp.end(response.cause().getMessage()); return; } val result = (EntityCommandExecution) response.result().body(); log.info("result = {}", result); if (result.getUnitOfWork() != null && result.getUowSequence() != null) { val headers = new CaseInsensitiveHeaders().add("uowSequence", result.getUowSequence()+""); val optionsUow = new DeliveryOptions().setCodecName(EntityUnitOfWork.class.getSimpleName()) .setHeaders(headers); vertx.<String>eventBus().publish(eventsHandlerId("example1"), result.getUnitOfWork(), optionsUow); httpResp.setStatusCode(201); val location = routingContext.request().absoluteURI() + "/" + result.getUnitOfWork() .getCommand().getCommandId().toString(); httpResp.headers().add("Location", location); } else { httpResp.setStatusCode(400); // TODO } httpResp.end(); }); }); } void getUowByCmdId(RoutingContext routingContext) { final HttpServerResponse httpResp = routingContext.response(); final String cmdID = routingContext.request().getParam("cmdID"); if (cmdID == null) { sendError(400, httpResp); return ; } final Future<EntityUnitOfWork> uowFuture = Future.future(); entityUowRepo.getUowByCmdId(UUID.fromString(cmdID), uowFuture); uowFuture.setHandler(uowResult -> { if (uowResult.failed()) { sendError(500, httpResp); } if (uowResult.result() == null) { sendError(404, httpResp); } else { val resultAsJson = Json.encode(uowResult.result()); httpResp.headers().add("Content-Type", "application/json"); httpResp.end(resultAsJson); } }); } private void sendError(int statusCode, HttpServerResponse response) { response.setStatusCode(statusCode).end(); } }
introducing crabzilla-vertx-web module
crabzilla-vertx/src/main/java/io/github/crabzilla/vertx/entity/EntityCommandHttpRpcVerticle.java
introducing crabzilla-vertx-web module
<ide><path>rabzilla-vertx/src/main/java/io/github/crabzilla/vertx/entity/EntityCommandHttpRpcVerticle.java <del>package io.github.crabzilla.vertx.entity; <del> <del>import io.github.crabzilla.core.entity.EntityCommand; <del>import io.github.crabzilla.core.entity.EntityUnitOfWork; <del>import io.vertx.core.AbstractVerticle; <del>import io.vertx.core.Future; <del>import io.vertx.core.eventbus.DeliveryOptions; <del>import io.vertx.core.http.CaseInsensitiveHeaders; <del>import io.vertx.core.http.HttpServerResponse; <del>import io.vertx.core.json.Json; <del>import io.vertx.core.json.JsonObject; <del>import io.vertx.ext.web.Router; <del>import io.vertx.ext.web.RoutingContext; <del>import io.vertx.ext.web.handler.BodyHandler; <del>import lombok.NonNull; <del>import lombok.extern.slf4j.Slf4j; <del>import lombok.val; <del> <del>import java.util.UUID; <del> <del>import static io.github.crabzilla.vertx.helpers.StringHelper.*; <del> <del> <del>@Slf4j <del>public class EntityCommandHttpRpcVerticle<E> extends AbstractVerticle { <del> <del> private final Class<E> aggregateRootClass; <del> private final JsonObject config; <del> private final EntityUnitOfWorkRepository entityUowRepo; <del> <del> public EntityCommandHttpRpcVerticle(@NonNull Class<E> aggregateRootClass, <del> @NonNull JsonObject config, <del> @NonNull EntityUnitOfWorkRepository entityUowRepo) { <del> this.aggregateRootClass = aggregateRootClass; <del> this.config = config; <del> this.entityUowRepo = entityUowRepo; <del> } <del> <del> @Override <del> public void start() throws Exception { <del> <del> val router = Router.router(vertx); <del> <del> router.route().handler(BodyHandler.create()); <del> <del> router.post("/" + aggregateId(aggregateRootClass) + "/commands") <del> .handler(this::postCommandHandler); <del> <del> router.get("/" + aggregateId(aggregateRootClass) + "/commands/:cmdID") <del> .handler(this::getUowByCmdId); <del> <del> val server = vertx.createHttpServer(); <del> <del> server.requestHandler(router::accept) <del> .listen(config.getInteger("http.port")); <del> <del> } <del> <del> void postCommandHandler(RoutingContext routingContext) { <del> <del> final HttpServerResponse httpResp = routingContext.response(); <del> final String commandStr = routingContext.getBodyAsString(); <del> <del> log.info("command=:\n" + commandStr); <del> <del> final EntityCommand command = Json.decodeValue(commandStr, EntityCommand.class); <del> <del> if (command == null) { <del> sendError(400, httpResp); <del> return ; <del> } <del> <del> final String cmdID = command.getCommandId().toString(); <del> <del> final Future<EntityUnitOfWork> uowFuture = Future.future(); <del> entityUowRepo.getUowByCmdId(UUID.fromString(cmdID), uowFuture); <del> <del> uowFuture.setHandler(uowResult -> { <del> if (uowResult.failed()) { <del> sendError(500, httpResp); <del> return; <del> } <del> <del> if (uowResult.result() != null) { <del> httpResp.setStatusCode(201); <del> val location = routingContext.request().absoluteURI() + "/" <del> + uowResult.result().getCommand().getCommandId().toString(); <del> httpResp.headers().add("Location", location); <del> val resultAsJson = Json.encode(uowResult.result()); <del> httpResp.headers().add("Content-Type", "application/json"); <del> httpResp.end(resultAsJson); <del> return ; <del> } <del> <del> val options = new DeliveryOptions().setCodecName(EntityCommand.class.getSimpleName()); <del> <del> vertx.<EntityCommandExecution>eventBus().send(commandHandlerId(aggregateRootClass), command, options, response -> { <del> if (!response.succeeded()) { <del> log.error("eventbus.handleCommand", response.cause()); <del> httpResp.setStatusCode(500); <del> httpResp.end(response.cause().getMessage()); <del> return; <del> } <del> <del> val result = (EntityCommandExecution) response.result().body(); <del> log.info("result = {}", result); <del> <del> if (result.getUnitOfWork() != null && result.getUowSequence() != null) { <del> val headers = new CaseInsensitiveHeaders().add("uowSequence", result.getUowSequence()+""); <del> val optionsUow = new DeliveryOptions().setCodecName(EntityUnitOfWork.class.getSimpleName()) <del> .setHeaders(headers); <del> vertx.<String>eventBus().publish(eventsHandlerId("example1"), result.getUnitOfWork(), optionsUow); <del> httpResp.setStatusCode(201); <del> val location = routingContext.request().absoluteURI() + "/" + result.getUnitOfWork() <del> .getCommand().getCommandId().toString(); <del> httpResp.headers().add("Location", location); <del> } else { <del> httpResp.setStatusCode(400); // TODO <del> } <del> httpResp.end(); <del> }); <del> <del> }); <del> <del> } <del> <del> void getUowByCmdId(RoutingContext routingContext) { <del> <del> final HttpServerResponse httpResp = routingContext.response(); <del> final String cmdID = routingContext.request().getParam("cmdID"); <del> <del> if (cmdID == null) { <del> sendError(400, httpResp); <del> return ; <del> } <del> <del> final Future<EntityUnitOfWork> uowFuture = Future.future(); <del> entityUowRepo.getUowByCmdId(UUID.fromString(cmdID), uowFuture); <del> <del> uowFuture.setHandler(uowResult -> { <del> if (uowResult.failed()) { <del> sendError(500, httpResp); <del> } <del> <del> if (uowResult.result() == null) { <del> sendError(404, httpResp); <del> } else { <del> val resultAsJson = Json.encode(uowResult.result()); <del> httpResp.headers().add("Content-Type", "application/json"); <del> httpResp.end(resultAsJson); <del> } <del> <del> }); <del> <del> } <del> <del> private void sendError(int statusCode, HttpServerResponse response) { <del> response.setStatusCode(statusCode).end(); <del> } <del> <del>}
JavaScript
bsd-3-clause
6bc08780430765e23e6b4ea38ab6918cd6e917c4
0
nyimbi/tilemill,fxtentacle/tilemill,nyimbi/tilemill,mbrukman/tilemill,florianf/tileoven,mbrukman/tilemill,mbrukman/tilemill,Zhao-Qi/tilemill,tizzybec/tilemill,tizzybec/tilemill,Teino1978-Corp/Teino1978-Corp-tilemill,nyimbi/tilemill,MappingKat/tilemill,nyimbi/tilemill,isaacs/tilemill,isaacs/tilemill,tizzybec/tilemill,Teino1978-Corp/Teino1978-Corp-tilemill,Zhao-Qi/tilemill,paulovieira/tilemill-clima,tilemill-project/tilemill,fxtentacle/tilemill,makinacorpus/tilemill,tizzybec/tilemill,florianf/tileoven,Zhao-Qi/tilemill,paulovieira/tilemill-clima,Zhao-Qi/tilemill,makinacorpus/tilemill,MappingKat/tilemill,isaacs/tilemill,Teino1978-Corp/Teino1978-Corp-tilemill,fxtentacle/tilemill,MappingKat/tilemill,tizzybec/tilemill,mbrukman/tilemill,paulovieira/tilemill-clima,florianf/tileoven,MappingKat/tilemill,Zhao-Qi/tilemill,nyimbi/tilemill,tilemill-project/tilemill,paulovieira/tilemill-clima,MappingKat/tilemill,Teino1978-Corp/Teino1978-Corp-tilemill,fxtentacle/tilemill,paulovieira/tilemill-clima,mbrukman/tilemill,fxtentacle/tilemill,Teino1978-Corp/Teino1978-Corp-tilemill,tilemill-project/tilemill
var TileMill = TileMill || { settings:{}, page:0, uniq: (new Date().getTime()), editor: {}, basic: { stylesheet: '' } }; $.fn.reverse = [].reverse; TileMill.save = function() { // No need to save MML, it's always the same. TileMill.basic.stylesheet = "/* { 'label': '" + TileMill.basic.label + "', 'visualizationType': '" + TileMill.basic.visualizationType + "', 'visualizationField': '" + TileMill.basic.visualizationField + "' } */\n"; TileMill.basic.stylesheet += "Map {\n map-bgcolor: #fff;\n}\n#world {\n polygon-fill: #eee;\n line-color: #ccc;\n line-width: 0.5;\n}\n#inspect {\n polygon-fill: #83bc69;\n line-color: #333;\n line-width: 0.5;\n}"; if (TileMill.basic.label) { TileMill.basic.stylesheet += "\n#inspect " + TileMill.basic.label + "{\n text-face-name: \"DejaVu Sans Book\";\n text-fill: #333;\n text-size: 9;\n}"; } if (TileMill.basic.visualizationType == 'choropleth' || TileMill.basic.visualizationType == 'unique') { var field = TileMill.basic.visualizationField; if (TileMill.inspector.valueCache[field]) { TileMill.basic[TileMill.basic.visualizationType](TileMill.inspector.valueCache[field]); TileMill._save(); } else { TileMill.inspector.values(field, 'inspect', 'TileMill.basic.' + TileMill.basic.visualizationType, (TileMill.basic.visualizationType == 'unique' ? 50 : false)); } } else { TileMill._save(); } } TileMill._save = function() { // Todo: implement chloropleth, unique value. TileMill.stylesheet.save(TileMill.settings.project_id, TileMill.basic.stylesheet); TileMill.uniq = (new Date().getTime()); TileMill.map.reload(); } TileMill.basic.choropleth = function(data) { var range = Math.abs(data.max - data.min), split = TileMill.settings.choroplethSplit ? TileMill.settings.choroplethSplit : 3, individual = range / split, colors = { 2: [], 3: ['#edaeae', '#e86363', '#f60000'], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [] }; for (i = 0; i < split; i++) { TileMill.basic.stylesheet += "\n#inspect[" + TileMill.basic.visualizationField + ">=" + data.min + (individual * i) + "] {\n polygon-fill: " + colors[split][i] + ";\n}"; } TileMill._save(); } TileMill.basic.unique = function(data) { var colors = [ '#edaeae', '#e86363', '#f60000' ], processed = []; for (i = 0; i < data.values.length; i++) { var pass = false; for (j = 0; j < processed.length; j++) { if (processed[j] == data.values[i]) { pass = true; continue; } } if (!pass) { TileMill.basic.stylesheet += "\n#inspect[" + TileMill.basic.visualizationField + "='" + data.values[i] + "'] {\n polygon-fill: " + colors[i % colors.length] + ";\n}"; processed.push(data.values[i]); } } TileMill._save(); } $(function() { $('div#header a.save').click(function() { TileMill.save(); return false; }); $('div#header a.info').click(function() { $('#popup-info input#tilelive-url').val(TileMill.settings.tilelive + 'tile/' + TileMill.mml.url({ timestamp: false, encode: true })); $('#popup-info input#project-mml-url').val(TileMill.mml.url({ timestamp: false, encode: false })); TileMill.popup.show({content: $('#popup-info'), title: 'Info'}); return false; }); TileMill.inspector.loadCallback = function(data) { $('.layer-inspect-loading').removeClass('layer-inspect-loading').addClass('layer-inspect'); for (field in data['inspect']) { (function(field, data) { var li = $('<li>') .attr('id', 'field-' + field) .append($('<a class="inspect-unique" href="#inspect-unique">Unique Value</a>').click(function() { if ($(this).is('.active')) { delete TileMill.basic.visualizationField; delete TileMill.basic.visualizationType; $(this).removeClass('active'); } else { TileMill.basic.visualizationField = field; TileMill.basic.visualizationType = 'unique'; $('#inspector a.inspect-choropleth, #inspector a.inspect-unique').removeClass('active'); $(this).addClass('active'); } TileMill.save(); return false; })) .append($('<a class="inspect-values" href="#inspect-values">See values</a>').click(function() { TileMill.inspector.values(field, 'inspect'); return false; })) .append($('<a class="inspect-label" href="#inspect-label">Label</a>').click(function() { if ($(this).is('.active')) { delete TileMill.basic.label; $(this).removeClass('active'); } else { TileMill.basic.label = field; $('#inspector a.inspect-label').removeClass('active'); $(this).addClass('active'); } TileMill.save(); return false; })); // Only show choropleth for int and float fields. if (data['inspect'][field] == 'int' || data['inspect'][field] == 'float') { li.append($('<a class="inspect-choropleth" href="#inspect-choropleth">Choropleth</a>').click(function() { if ($(this).is('.active')) { delete TileMill.basic.visualizationField; delete TileMill.basic.visualizationType; $(this).removeClass('active'); } else { TileMill.basic.visualizationField = field; TileMill.basic.visualizationType = 'choropleth'; $('#inspector a.inspect-choropleth, #inspector a.inspect-unique').removeClass('active'); $(this).addClass('active'); } TileMill.save(); return false; })); } li.append('<strong>' + field + '</strong>') .append('<em>' + data['inspect'][field].replace('int', 'integer').replace('str', 'string') + '</em>') .appendTo($('#inspector ul.sidebar-content')); })(field, data); } var src = $('Stylesheet:first', TileMill.settings.mml).attr('src'); // If there is no / character, assume this is a single filename. if (src.split('/').length === 1) { src = TileMill.settings.server + 'projects/mss?id='+ TileMill.settings.project_id +'&filename='+ filename; } $.get(src, function(data) { var settings = eval('(' + data.match(/(.+)/)[0].replace('/*', '').replace('*/', '') + ')'); if (settings.label != 'undefined') { TileMill.basic.label = settings.label; $('#field-' + settings.label).find('.inspect-label').addClass('active'); } if (settings.visualizationField != 'undefined') { TileMill.basic.visualizationField = settings.visualizationField; TileMill.basic.visualizationType = settings.visualizationType; $('#field-' + settings.visualizationField).find('.inspect-' + settings.visualizationType).addClass('active'); } }); }; TileMill.inspector.load(); $('#layers').hide(); });
tilemill/static/js/basic.js
var TileMill = TileMill || { settings:{}, page:0, uniq: (new Date().getTime()), editor: {}, basic: { stylesheet: '' } }; $.fn.reverse = [].reverse; TileMill.save = function() { // No need to save MML, it's always the same. TileMill.basic.stylesheet = "/* { 'label': '" + TileMill.basic.label + "', 'visualizationType': '" + TileMill.basic.visualizationType + "', 'visualizationField': '" + TileMill.basic.visualizationField + "' } */\n"; TileMill.basic.stylesheet += "Map {\n map-bgcolor: #fff;\n}\n#world {\n polygon-fill: #eee;\n line-color: #ccc;\n line-width: 0.5;\n}\n#inspect {\n polygon-fill: #83bc69;\n line-color: #333;\n line-width: 0.5;\n}"; if (TileMill.basic.label) { TileMill.basic.stylesheet += "\n#inspect " + TileMill.basic.label + "{\n text-face-name: \"DejaVu Sans Book\";\n text-fill: #333;\n text-size: 9;\n}"; } if (TileMill.basic.visualizationType == 'choropleth' || TileMill.basic.visualizationType == 'unique') { var field = TileMill.basic.visualizationField; if (TileMill.inspector.valueCache[field]) { TileMill.basic[TileMill.basic.visualizationType](TileMill.inspector.valueCache[field]); TileMill._save(); } else { TileMill.inspector.values(field, 'inspect', 'TileMill.basic.' + TileMill.basic.visualizationType, (TileMill.basic.visualizationType == 'unique' ? 50 : false)); } } else { TileMill._save(); } } TileMill._save = function() { // Todo: implement chloropleth, unique value. TileMill.stylesheet.save(TileMill.settings.project_id, TileMill.basic.stylesheet); TileMill.uniq = (new Date().getTime()); TileMill.map.reload(); } TileMill.basic.choropleth = function(data) { var range = Math.abs(data.max - data.min), split = TileMill.settings.choroplethSplit ? TileMill.settings.choroplethSplit : 3, individual = range / split, colors = { 2: [], 3: ['#edaeae', '#e86363', '#f60000'], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [] }; for (i = 0; i < split; i++) { TileMill.basic.stylesheet += "\n#inspect[" + TileMill.basic.visualizationField + ">=" + data.min + (individual * i) + "] {\n polygon-fill: " + colors[split][i] + ";\n}"; } TileMill._save(); } TileMill.basic.unique = function(data) { var colors = [ '#edaeae', '#e86363', '#f60000' ], processed = []; for (i = 0; i < data.values.length; i++) { var pass = false; for (j = 0; j < processed.length; j++) { if (processed[j] == data.values[i]) { pass = true; continue; } } if (!pass) { TileMill.basic.stylesheet += "\n#inspect[" + TileMill.basic.visualizationField + "='" + data.values[i] + "'] {\n polygon-fill: " + colors[i % colors.length] + ";\n}"; processed.push(data.values[i]); } } TileMill._save(); } $(function() { $('div#header a.save').click(function() { TileMill.save(); return false; }); $('div#header a.info').click(function() { $('#popup-info input#tilelive-url').val(TileMill.settings.tilelive + 'tile/' + TileMill.mml.url({ timestamp: false, encode: true })); $('#popup-info input#project-mml-url').val(TileMill.mml.url({ timestamp: false, encode: false })); TileMill.popup.show({content: $('#popup-info'), title: 'Info'}); return false; }); TileMill.inspector.loadCallback = function(data) { $('.layer-inspect-loading').removeClass('layer-inspect-loading').addClass('layer-inspect'); for (field in data['inspect']) { (function(field, data) { var li = $('<li>') .attr('id', 'field-' + field) .append($('<a class="inspect-unique" href="#inspect-unique">Unique Value</a>').click(function() { $('#inspector a.inspect-choropleth, #inspector a.inspect-unique').removeClass('active'); $(this).addClass('active'); TileMill.basic.visualizationField = field; TileMill.basic.visualizationType = 'unique'; TileMill.save(); return false; })) .append($('<a class="inspect-values" href="#inspect-values">See values</a>').click(function() { TileMill.inspector.values(field, 'inspect'); return false; })) .append($('<a class="inspect-label" href="#inspect-label">Label</a>').click(function() { $('#inspector a.inspect-label').removeClass('active'); $(this).addClass('active'); TileMill.basic.label = field; TileMill.save(); return false; })); // Only show choropleth for int and float fields. if (data['inspect'][field] == 'int' || data['inspect'][field] == 'float') { li.append($('<a class="inspect-choropleth" href="#inspect-choropleth">Choropleth</a>').click(function() { $('#inspector a.inspect-choropleth, #inspector a.inspect-unique').removeClass('active'); $(this).addClass('active'); TileMill.basic.visualizationField = field; TileMill.basic.visualizationType = 'choropleth'; TileMill.save(); return false; })); } li.append('<strong>' + field + '</strong>') .append('<em>' + data['inspect'][field].replace('int', 'integer').replace('str', 'string') + '</em>') .appendTo($('#inspector ul.sidebar-content')); })(field, data); } var src = $('Stylesheet:first', TileMill.settings.mml).attr('src'); // If there is no / character, assume this is a single filename. if (src.split('/').length === 1) { src = TileMill.settings.server + 'projects/mss?id='+ TileMill.settings.project_id +'&filename='+ filename; } $.get(src, function(data) { var settings = eval('(' + data.match(/(.+)/)[0].replace('/*', '').replace('*/', '') + ')'); if (settings.label != 'undefined') { TileMill.basic.label = settings.label; $('#field-' + settings.label).find('.inspect-label').addClass('active'); } if (settings.visualizationField != 'undefined') { TileMill.basic.visualizationField = settings.visualizationField; TileMill.basic.visualizationType = settings.visualizationType; $('#field-' + settings.visualizationField).find('.inspect-' + settings.visualizationType).addClass('active'); } }); }; TileMill.inspector.load(); $('#layers').hide(); });
Toggling of visualization types.
tilemill/static/js/basic.js
Toggling of visualization types.
<ide><path>ilemill/static/js/basic.js <ide> var li = $('<li>') <ide> .attr('id', 'field-' + field) <ide> .append($('<a class="inspect-unique" href="#inspect-unique">Unique Value</a>').click(function() { <del> $('#inspector a.inspect-choropleth, #inspector a.inspect-unique').removeClass('active'); <del> $(this).addClass('active'); <del> TileMill.basic.visualizationField = field; <del> TileMill.basic.visualizationType = 'unique'; <add> if ($(this).is('.active')) { <add> delete TileMill.basic.visualizationField; <add> delete TileMill.basic.visualizationType; <add> $(this).removeClass('active'); <add> } <add> else { <add> TileMill.basic.visualizationField = field; <add> TileMill.basic.visualizationType = 'unique'; <add> $('#inspector a.inspect-choropleth, #inspector a.inspect-unique').removeClass('active'); <add> $(this).addClass('active'); <add> } <ide> TileMill.save(); <ide> return false; <ide> })) <ide> return false; <ide> })) <ide> .append($('<a class="inspect-label" href="#inspect-label">Label</a>').click(function() { <del> $('#inspector a.inspect-label').removeClass('active'); <del> $(this).addClass('active'); <del> TileMill.basic.label = field; <add> if ($(this).is('.active')) { <add> delete TileMill.basic.label; <add> $(this).removeClass('active'); <add> } <add> else { <add> TileMill.basic.label = field; <add> $('#inspector a.inspect-label').removeClass('active'); <add> $(this).addClass('active'); <add> } <ide> TileMill.save(); <ide> return false; <ide> })); <ide> // Only show choropleth for int and float fields. <ide> if (data['inspect'][field] == 'int' || data['inspect'][field] == 'float') { <ide> li.append($('<a class="inspect-choropleth" href="#inspect-choropleth">Choropleth</a>').click(function() { <del> $('#inspector a.inspect-choropleth, #inspector a.inspect-unique').removeClass('active'); <del> $(this).addClass('active'); <del> TileMill.basic.visualizationField = field; <del> TileMill.basic.visualizationType = 'choropleth'; <add> if ($(this).is('.active')) { <add> delete TileMill.basic.visualizationField; <add> delete TileMill.basic.visualizationType; <add> $(this).removeClass('active'); <add> } <add> else { <add> TileMill.basic.visualizationField = field; <add> TileMill.basic.visualizationType = 'choropleth'; <add> $('#inspector a.inspect-choropleth, #inspector a.inspect-unique').removeClass('active'); <add> $(this).addClass('active'); <add> } <ide> TileMill.save(); <ide> return false; <ide> }));
JavaScript
agpl-3.0
019d99b5f7c9b331f4ed370b3c0a611af124636b
0
mapic/mile,mapic/mile
// dependencies var _ = require('lodash'); var fs = require('fs-extra'); var kue = require('kue'); var path = require('path'); var zlib = require('zlib'); var uuid = require('uuid'); var async = require('async'); var redis = require('redis'); var carto = require('carto'); var mapnik = require('mapnik'); var colors = require('colors'); var cluster = require('cluster'); var numCPUs = require('os').cpus().length; var mongoose = require('mongoose'); var request = require('request'); var exec = require('child_process').exec; var pg = require('pg'); var gm = require('gm'); var sanitize = require("sanitize-filename"); // modules var server = require('./server'); var config = require('../config/pile-config'); var store = require('./store'); var proxy = require('./proxy'); // mercator var mercator = require('./sphericalmercator'); var geojsonArea = require('geojson-area'); // register mapnik plugions mapnik.register_default_fonts(); mapnik.register_default_input_plugins(); // global paths (todo: move to config) var VECTORPATH = '/data/vector_tiles/'; var RASTERPATH = '/data/raster_tiles/'; var GRIDPATH = '/data/grid_tiles/'; var PROXYPATH = '/data/proxy_tiles/'; var pgsql_options = { dbhost: 'postgis', dbuser: process.env.SYSTEMAPIC_PGSQL_USERNAME || 'docker', dbpass: process.env.SYSTEMAPIC_PGSQL_PASSWORD || 'docker' }; module.exports = pile = { headers : { jpeg : 'image/jpeg', png : 'image/png', pbf : 'application/x-protobuf', grid : 'application/json' }, proxyProviders : ['google', 'norkart'], // getTile : function (req, res) { if (pile.tileIsProxy(req)) return pile.serveProxyTile(req, res); if (pile.tileIsPostgis(req)) return pile.serveTile(req, res); res.end(); // todo: error handling }, tileIsProxy : function (req) { var params = req.params[0].split('/'); var provider = params[0]; var isProxy = _.contains(pile.proxyProviders, provider); return isProxy; }, tileIsPostgis : function (req) { var params = req.params[0].split('/'); var layer_id = params[0]; var isPostgis = _.contains(layer_id, 'layer_id-'); return isPostgis; }, // decide whether postgis or overlay_raster... todo: refactor with rasters in postgis (no more overlays) serveTile : function (req, res) { // parse url into layerUuid, zxy, type var ops = []; var parsed = req._parsedUrl.pathname.split('/'); var params = { layerUuid : parsed[3], z : parseInt(parsed[4]), x : parseInt(parsed[5]), y : parseInt(parsed[6].split('.')[0]), type : parsed[6].split('.')[1], }; return pile._getTile(req, res); }, _getTile : function (req, res) { // parse url into layerUuid, zxy, type var ops = []; var parsed = req._parsedUrl.pathname.split('/'); var params = { layerUuid : parsed[3], z : parseInt(parsed[4]), x : parseInt(parsed[5]), y : parseInt(parsed[6].split('.')[0]), type : parsed[6].split('.')[1], }; var map; var layer; var postgis; var bbox; var type = params.type; var ops = []; var start_time = new Date().getTime(); // add access token to params params.access_token = req.query.access_token || req.body.access_token; // get stored layer store.layers.get(params.layerUuid, function (err, storedLayerJSON) { if (err) return pile._getTileErrorHandler(res, err); if (!storedLayerJSON) return pile._getTileErrorHandler(res, 'No stored layer.'); var storedLayer = JSON.parse(storedLayerJSON); console.log('storedLayer: ', storedLayer); // get tiles if (type == 'pbf') ops.push(function (callback) { pile.getVectorTile(params, storedLayer, callback); }); if (type == 'png') ops.push(function (callback) { pile.getRasterTile(params, storedLayer, callback); }); if (type == 'grid') ops.push(function (callback) { pile.getGridTile(params, storedLayer, callback); }); // run ops async.series(ops, function (err, data) { if (err) { console.error({ err_id : 2, err_msg : 'render vector', error : err }); // return res.end(); if (type == 'png') return pile.serveEmptyTile(res); return res.json({}); } // timer var end_time = new Date().getTime(); var create_tile_time = end_time - start_time; // log tile request console.tile({ z : params.z, x : params.x, y : params.y, format : type, layer_id : params.layerUuid, render_time : create_tile_time }); // send to client res.writeHead(200, {'Content-Type': pile.headers[type]}); res.end(data[0]); }); }); }, // todo: REFACTOR with proper postgis raster instead getOverlayTile : function (req, res) { // parse url into layerUuid, zxy, type var ops = [], parsed = req._parsedUrl.pathname.split('/'), params = { layerUuid : parsed[3], z : parseInt(parsed[4]), x : parseInt(parsed[5]), y : parseInt(parsed[6].split('.')[0]), type : parsed[6].split('.')[1], }; var map, layer, postgis, bbox; var type = params.type; var ops = []; console.log('overlaye params', params); // get stored layer store.layers.get(params.layerUuid, function (err, storedLayerJSON) { if (err) return pile._getTileErrorHandler(res, err); if (!storedLayerJSON) return pile._getTileErrorHandler(res, 'No stored layer.'); var storedLayer = JSON.parse(storedLayerJSON); var cutColor = storedLayer.options.cutColor; if (cutColor) { var colorName = sanitize(cutColor); // get file etc. var file_id = storedLayer.options.file_id; var originalPath = '/data/raster_tiles/' + file_id + '/raster/' + params.z + '/' + params.x + '/' + params.y + '.png'; var path = originalPath + '.cut-' + colorName; fs.readFile(path, function (err, buffer) { // not created yet, do it! if (err || !buffer) { // cut white; todo: all colors (with threshold) if (colorName == 'white') { pile._cutWhite({ path : path, originalPath : originalPath, returnBuffer : true }, function (err, buffer) { // send to client res.writeHead(200, {'Content-Type': pile.headers[type]}); res.end(buffer); }); // cut black: todo: https://github.com/systemapic/wu/issues/256 } else if (colorName == 'black') { pile._cutBlack({ path : path, originalPath : originalPath, returnBuffer : true }, function (err, buffer) { // send to client res.writeHead(200, {'Content-Type': pile.headers[type]}); res.end(buffer); }); // no cut } else { console.log('no cut raster! probably something wrong...') // send to client res.writeHead(200, {'Content-Type': pile.headers[type]}); res.end(buffer); } } else { // send to client res.writeHead(200, {'Content-Type': pile.headers[type]}); res.end(buffer); } }); } else { // get file etc. var file_id = storedLayer.options.file_id; var path = '/data/raster_tiles/' + file_id + '/raster/' + params.z + '/' + params.x + '/' + params.y + '.png'; fs.readFile(path, function (err, buffer) { // send to client res.writeHead(200, {'Content-Type': pile.headers[type]}); res.end(buffer); }); } }); }, serveProxyTile : function (req, res) { // parse url var params = req.params[0].split('/'); // set options var options = { provider : params[0], type : params[1], z : params[2], x : params[3], y : params[4].split('.')[0], format : params[4].split('.')[1] } // create proxy tile job var job = jobs.create('proxy_tile', { options : options, }).priority('high').attempts(5).save(); // proxy tile job done job.on('complete', function (result) { // serve proxy tile proxy.serveTile(res, options); }); }, fetchData : function (req, res) { var options = req.body, column = options.column, // gid row = options.row, // eg. 282844 layer_id = options.layer_id, ops = []; ops.push(function (callback) { // retrieve layer and return it to client store.layers.get(layer_id, function (err, layer) { if (err || !layer) return callback(err || 'no layer'); callback(null, JSON.parse(layer)); }); }); ops.push(function (layer, callback) { var table = layer.options.table_name; var database = layer.options.database_name; // do sql query on postgis var GET_DATA_SCRIPT_PATH = 'src/get_data_by_column.sh'; // st_extent script var command = [ GET_DATA_SCRIPT_PATH, // script layer.options.database_name, // database name layer.options.table_name, // table name column, row ].join(' '); // create database in postgis exec(command, {maxBuffer: 1024 * 1024 * 1000}, function (err, stdout, stdin) { if (err) return callback(err); // parse results var json = stdout.split('\n')[2]; var data = JSON.parse(json); // remove geom columns data.geom = null; data.the_geom_3857 = null; data.the_geom_4326 = null; // callback callback(null, data); }); }); async.waterfall(ops, function (err, data) { if (err) console.error({ err_id : 51, err_msg : 'fetch data script', error : err }); res.json(data); }); }, fetchDataArea : function (req, res) { var options = req.body, geojson = options.geojson, access_token = options.access_token, layer_id = options.layer_id; var ops = []; // error handling if (!geojson) return pile.error.missingInformation(res, 'Please provide an area.') ops.push(function (callback) { // retrieve layer and return it to client store.layers.get(layer_id, function (err, layer) { if (err || !layer) return callback(err || 'no layer'); callback(null, JSON.parse(layer)); }); }); ops.push(function (layer, callback) { var table = layer.options.table_name; var database = layer.options.database_name; var polygon = "'" + JSON.stringify(geojson.geometry) + "'"; var sql = '"' + layer.options.sql + '"'; // do sql query on postgis var GET_DATA_AREA_SCRIPT_PATH = 'src/get_data_by_area.sh'; // st_extent script var command = [ GET_DATA_AREA_SCRIPT_PATH, // script layer.options.database_name, // database name sql, polygon ].join(' '); // do postgis script exec(command, {maxBuffer: 1024 * 50000}, function (err, stdout, stdin) { if (err) return callback(err); var arr = stdout.split('\n'), result = []; arr.forEach(function (arrr) { try { var item = JSON.parse(arrr); result.push(item); } catch (e) {}; }); var points = []; result.forEach(function (point) { // delete geoms delete point.geom; delete point.the_geom_3857; delete point.the_geom_4326; // push points.push(point); }); // calculate averages, totals var average = pile._calculateAverages(points); var total_points = points.length; // only return 100 points if (points.length > 100) { points = points.slice(0, 100); } // return results var resultObject = { all : points, average : average, total_points : total_points, area : geojsonArea.geometry(geojson.geometry), layer_id : layer_id } // callback callback(null, resultObject); }); }); async.waterfall(ops, function (err, data) { if (err) console.error({ err_id : 52, err_msg : 'fetch data area script', error : err }); res.json(data); }); }, fetchHistogram : function (req, res) { var options = req.body, column = options.column, access_token = options.access_token, layer_id = options.layer_id, num_buckets = options.num_buckets || 20; var ops = []; ops.push(function (callback) { // retrieve layer and return it to client store.layers.get(layer_id, function (err, layer) { if (err || !layer) return callback(err || 'no layer'); callback(null, JSON.parse(layer)); }); }); ops.push(function (layer, callback) { var table = layer.options.table_name; var database = layer.options.database_name; // do sql query on postgis var GET_HISTOGRAM_SCRIPT = 'src/get_histogram.sh'; // st_extent script var command = [ GET_HISTOGRAM_SCRIPT, // script database, // database name table, column, num_buckets ].join(' '); // do postgis script exec(command, {maxBuffer: 1024 * 50000}, function (err, stdout, stdin) { if (err) return callback(err); var arr = stdout.split('\n'), result = []; arr.forEach(function (arrr) { try { var item = JSON.parse(arrr); result.push(item); } catch (e) {}; }); callback(null, result); }); }); async.waterfall(ops, function (err, data) { if (err) console.error({ err_id : 53, err_msg : 'fetch histogram script', error : err }); res.json(data); }); }, _calculateAverages : function (points) { var keys = {}; // get keys for (var key in points[0]) { keys[key] = []; } // sum values points.forEach(function (p) { for (var key in p) { keys[key].push(p[key]); } }); // calc avg var averages = {}; for (var k in keys) { averages[k] = (_.sum(keys[k]) / keys[k].length) } return averages; }, // this layer is only a postgis layer. a Wu Layer Model must be created by client after receiving this postgis layer createLayer : function (req, res) { var options = req.body, file_id = options.file_id, sql = options.sql, cartocss = options.cartocss, cartocss_version = options.cartocss_version, geom_column = options.geom_column, geom_type = options.geom_type, raster_band = options.raster_band, srid = options.srid, affected_tables = options.affected_tables, interactivity = options.interactivity, attributes = options.attributes, access_token = req.body.access_token; // log to file console.log({ type : 'createLayer', options : options }); // verify query if (!file_id) return pile.error.missingInformation(res, 'Please provide a file_id.') var ops = []; ops.push(function (callback) { // get upload status object from wu pile.request.get('/api/import/status', { // todo: write more pluggable file_id : file_id, access_token : access_token }, callback); }); ops.push(function (upload_status, callback) { if (!upload_status) return callback('No such upload_status.'); var upload_status = JSON.parse(upload_status); // check that done importing to postgis if (!upload_status.upload_success) return callback('The data was not uploaded correctly. Please check your data and error messages, and try again.') // todo: errors // check that done importing to postgis if (!upload_status.processing_success) return callback('The data is not done processing yet. Please try again in a little while.') // create postgis layer for rasters and vector layers if (upload_status.data_type == 'vector' || upload_status.data_type == 'raster') { return pile._createPostGISLayer({ upload_status : upload_status, options : options }, callback); } // error callback('Invalid data_type: ' + upload_status.data_type); }) async.waterfall(ops, function (err, layerObject) { if (err) { console.error({ err_id : 30, err_msg : 'create layer', error : err }); return res.json({error : err}); } // return layer to client res.json(layerObject); }); }, vectorizeLayer : function (req, res) { // vectorize raster (create postgis layer) return pile.vectorizeRaster({ options : options, upload_status : upload_status }, callback); var options = req.body, file_id = options.file_id, sql = options.sql, cartocss = options.cartocss, cartocss_version = options.cartocss_version, geom_column = options.geom_column, geom_type = options.geom_type, raster_band = options.raster_band, srid = options.srid, affected_tables = options.affected_tables, interactivity = options.interactivity, attributes = options.attributes, access_token = req.body.access_token; // log to file console.log({ type : 'createLayer', options : options }); // verify query if (!file_id) return pile.error.missingInformation(res, 'Please provide a file_id.') var ops = []; ops.push(function (callback) { // // get upload status object from wu // pile.request.get('/api/import/status', { // todo: write more pluggable // file_id : file_id, // access_token : access_token // }, callback); callback() }); ops.push(function (upload_status, callback) { if (!upload_status) return callback('No such upload_status.'); var upload_status = JSON.parse(upload_status); // check that done importing to postgis if (!upload_status.upload_success) return callback('The data was not uploaded correctly. Please check your data and error messages, and try again.') // todo: errors // check that done importing to postgis if (!upload_status.processing_success) return callback('The data is not done processing yet. Please try again in a little while.') // create postgis layer for rasters and vector layers if (upload_status.data_type == 'vector' || upload_status.data_type == 'raster') { return pile._createPostGISLayer({ upload_status : upload_status, options : options }, callback); } // error callback('Invalid data_type: ' + upload_status.data_type); }) async.waterfall(ops, function (err, layerObject) { if (err) { console.error({ err_id : 30, err_msg : 'create layer', error : err }); return res.json({error : err}); } // return layer to client res.json(layerObject); }); }, vectorizeRaster : function (data, done) { // create vector table from raster // create postgislayer (vector) from new table // return layer var status = data.upload_status; var options = data.options; var vectorized_raster_file_id; var layerJSON; var ops = []; ops.push(function (callback) { var VECTORIZE_SCRIPT_PATH = 'src/vectorize_raster.sh'; vectorized_raster_file_id = 'vectorized_raster_' + pile.getRandomChars(20); // st_extent script var command = [ VECTORIZE_SCRIPT_PATH, // script status.database_name, // database name vectorized_raster_file_id, status.table_name, // table name ].join(' '); // console.log('command: ', command); // create database in postgis exec(command, {maxBuffer: 1024 * 50000}, function (err, stdout, stdin) { // console.log('err, stdout, stdin', err, stdout, stdin); options.sql = "(SELECT * FROM " + vectorized_raster_file_id + ") as sub"; options.table_name = vectorized_raster_file_id; // callback callback(err); }); }); ops.push(function (callback) { pile._primeTableWithGeometries({ file_id : vectorized_raster_file_id, postgis_db : status.database_name, }, callback); }); ops.push(function (callback) { return pile._createPostGISLayer({ upload_status : status, options : options }, function (err, layer) { layerJSON = layer; callback(err); }); }); // ops.push(function (callback) { // }); async.series(ops, function (err) { done(err, layerJSON); }); }, _primeTableWithGeometries : function (options, done) { var file_id = options.file_id, postgis_db = options.postgis_db, ops = []; // console.log('_primeTableWithGeometries', options); // get geometry type ops.push(function (callback) { pile.pgquery({ postgis_db : postgis_db, query : 'SELECT ST_GeometryType(geom) from "' + file_id + '" limit 1' }, function (err, results) { if (err) return callback(err); if (!results || !results.rows || !results.rows.length) return callback('The dataset contains no valid geodata.'); var geometry_type = results.rows[0].st_geometrytype.split('ST_')[1]; callback(null, geometry_type); }) }); // create geometry 3857 ops.push(function (geometry_type, callback) { var column = ' the_geom_3857'; var geometry = ' geometry(' + geometry_type + ', 3857)'; var query = 'ALTER TABLE ' + file_id + ' ADD COLUMN' + column + geometry; pile.pgquery({ postgis_db : postgis_db, query : query }, function (err, results) { if (err) return callback(err); callback(null, geometry_type); }); }); // create geometry 4326 ops.push(function (geometry_type, callback) { var column = ' the_geom_4326'; var geometry = ' geometry(' + geometry_type + ', 4326)'; var query = 'ALTER TABLE ' + file_id + ' ADD COLUMN' + column + geometry; pile.pgquery({ postgis_db : postgis_db, query : query }, function (err, results) { if (err) return callback(err); callback(err, geometry_type); }); }); // populate geometry ops.push(function (geometry_type, callback) { var query = 'ALTER TABLE ' + file_id + ' ALTER COLUMN the_geom_3857 TYPE Geometry(' + geometry_type + ', 3857) USING ST_Transform(geom, 3857)' pile.pgquery({ postgis_db : postgis_db, query : query }, function (err, results) { if (err) return callback(err); callback(err, geometry_type); }); }); // populate geometry ops.push(function (geometry_type, callback) { var query = 'ALTER TABLE ' + file_id + ' ALTER COLUMN the_geom_4326 TYPE Geometry(' + geometry_type + ', 4326) USING ST_Transform(geom, 4326)' pile.pgquery({ postgis_db : postgis_db, query : query }, function (err, results) { if (err) return callback(err); callback(err); }); }); // create index for 3857 ops.push(function (callback) { var idx = file_id + '_the_geom_4326_idx'; var query = 'CREATE INDEX ' + idx + ' ON ' + file_id + ' USING GIST(the_geom_4326)' pile.pgquery({ postgis_db : postgis_db, query : query }, function (err, results) { if (err) return callback(err); callback(null); }); }); // create index for 4326 ops.push(function (callback) { var idx = file_id + '_the_geom_3857_idx'; var query = 'CREATE INDEX ' + idx + ' ON ' + file_id + ' USING GIST(the_geom_3857)' pile.pgquery({ postgis_db : postgis_db, query : query }, function (err, results) { if (err) return callback(err); callback(null, 'ok'); }); }); async.waterfall(ops, function (err, results) { done(err); }); }, pgquery : function (options, callback) { var postgis_db = options.postgis_db, variables = options.variables, query = options.query; var dbhost = pgsql_options.dbhost; var dbuser = pgsql_options.dbuser; var dbpass = pgsql_options.dbpass; var conString = 'postgres://'+dbuser+':'+dbpass+'@'+dbhost+'/' + postgis_db; pg.connect(conString, function(err, client, pgcb) { if (err) return callback(err); // do query client.query(query, variables, function(err, result) { // clean up after pg pgcb(); // client.end(); if (err) return callback(err); // return result callback(null, result); }); }); }, _createPostGISLayer : function (opts, done) { var ops = [], options = opts.upload_status, file_id = opts.options.file_id, sql = opts.options.sql, cartocss = opts.options.cartocss, cartocss_version = opts.options.cartocss_version, geom_column = opts.options.geom_column, geom_type = opts.options.geom_type, raster_band = opts.options.raster_band, srid = opts.options.srid, affected_tables = opts.options.affected_tables, interactivity = opts.options.interactivity, attributes = opts.options.attributes, access_token = opts.options.access_token; if (!sql) return done('Please provide a SQL statement.') if (!cartocss) return done('Please provide CartoCSS.') ops.push(function (callback) { // inject table name into sql var done_sql = sql.replace('table', options.table_name); // create layer object var layerUuid = 'layer_id-' + uuid.v4(); var layer = { layerUuid : layerUuid, options : { // required sql : done_sql, cartocss : cartocss, file_id : file_id, database_name : options.database_name, table_name : options.table_name, metadata : options.metadata, layer_id : layerUuid, wicked : 'thing', data_type : options.data_type || opts.options.data_type || 'vector', // optional // defaults cartocss_version : cartocss_version || '2.0.1', geom_column : geom_column || 'geom', geom_type : geom_type || 'geometry', raster_band : raster_band || 0, srid : srid || 3857, } } callback(null, layer); }); // get extent of file (todo: put in file object) ops.push(function (layer, callback) { var GET_EXTENT_SCRIPT_PATH = 'src/get_st_extent.sh'; // st_extent script var command = [ GET_EXTENT_SCRIPT_PATH, // script layer.options.database_name, // database name layer.options.table_name, // table name ].join(' '); // create database in postgis exec(command, {maxBuffer: 1024 * 50000}, function (err, stdout, stdin) { // parse stdout try { var extent = stdout.split('(')[1].split(')')[0]; } catch (e) { return callback(e); } // set extent layer.options.extent = extent; // callback callback(null, layer); }); }); // save layer to store.redis ops.push(function (layer, callback) { // save layer to store.redis store.layers.set(layer.layerUuid, JSON.stringify(layer), function (err) { if (err) console.error({ err_id : 1, err_msg : 'create postgis layer', error : err }); callback(err, layer); }); }); // layer created, return async.waterfall(ops, done); }, _createRasterLayer : function (opts, done) { var ops = [], options = opts.upload_status, file_id = opts.options.file_id, srid = opts.options.srid, srid = options.srid, access_token = opts.options.access_token; // console.log('_createRasterLayer', opts); var cutColor = opts.options.cutColor || false; ops.push(function (callback) { // create layer object var layerUuid = 'layer_id-' + uuid.v4(); var layer = { layerUuid : layerUuid, options : { // required sql : false, cartocss : false, file_id : file_id, metadata : options.metadata, layer_id : layerUuid, wicked : 'thing', srid : srid || 3857, data_type : 'raster', cutColor : cutColor } } callback(null, layer); }); // save layer to store.redis ops.push(function (layer, callback) { // save layer to store.redis store.layers.set(layer.layerUuid, JSON.stringify(layer), function (err) { if (err) console.error({ err_id : 2, err_msg : 'create raster', error : err }); callback(err, layer); }); }); // layer created, return async.waterfall(ops, done); }, getLayer : function (req, res) { // get layerUuid var layerUuid = req.body.layerUuid || req.query.layerUuid; if (!layerUuid) return pile.error.missingInformation(res, 'Please provide layerUuid.'); // retrieve layer and return it to client store.layers.get(layerUuid, function (err, layer) { if (err) console.error({ err_id : 21, err_msg : 'render vector', error : err }); res.end(layer); }); }, _cutWhite : function (options, callback) { var path = options.path; var originalPath = options.originalPath; var returnBuffer = options.returnBuffer; gm(originalPath) .whiteThreshold(200, 200, 200, 1) .transparent('#FFFFFF') .write(path, function (err) { if (!err && returnBuffer) { fs.readFile(path, callback); } else { callback(err); } }); }, _cutBlack : function (options, callback) { var path = options.path; var originalPath = options.originalPath; var returnBuffer = options.returnBuffer; gm(originalPath) .blackThreshold(20, 20, 20, 1) .transparent('#000000') .write(path, function (err) { if (!err && returnBuffer) { fs.readFile(path, callback); } else { callback(err); } }); }, cutColor : function (options, callback) { var path = options.path; var originalPath = options.originalPath; var color = options.color; var returnBuffer = options.returnBuffer; gm(originalPath) .whiteThreshold(220, 220, 220, 1) .transparent('#FFFFFF') .write(path, function (err) { if (!err && returnBuffer) { fs.readFile(path, callback); } else { callback(err); } }); }, _getTileErrorHandler : function (res, err) { if (err) console.error({ err_id : 60, err_msg : 'get tile error handler', error : err }); res.end(); }, createVectorTile : function (params, storedLayer, done) { // KUE: create raster tile var job = jobs.create('render_vector_tile', { // todo: cluster up with other machines, pluggable clusters params : params, storedLayer : storedLayer }).priority('high').attempts(5).save(); // KUE DONE: raster created job.on('complete', function (result) { // console.log('crated vecotr tile? ', result); // get tile store._readVectorTile(params, done); }); }, createRasterTile : function (params, storedLayer, done) { // KUE: create raster tile var job = jobs.create('render_raster_tile', { // todo: cluster up with other machines, pluggable clusters params : params, storedLayer : storedLayer }).priority('high').removeOnComplete(true).attempts(5).save(); // KUE DONE: raster created job.on('complete', function (result) { // get tile store._readRasterTile(params, done); }); job.on('failed', function (err) { done(err); }); }, _serveErrorTile : function (res) { var errorTile = 'public/errorTile.png'; fs.readFile('public/noAccessTile.png', function (err, tile) { res.writeHead(200, {'Content-Type': 'image/png'}); res.end(tile); }); }, serveEmptyTile : function (res) { fs.readFile('public/emptyTile.png', function (err, tile) { res.writeHead(200, {'Content-Type': 'image/png'}); res.end(tile); }); }, createGridTile : function (params, storedLayer, done) { // KUE: create raster tile var job = jobs.create('render_grid_tile', { // todo: cluster up with other machines, pluggable clusters params : params, storedLayer : storedLayer }).priority('high').attempts(5).save(); // KUE DONE: raster created job.on('complete', function (result) { // get tile pile._getGridTileFromRedis(params, done); }); job.on('failed', function (err) { done(err); }); }, // _renderVectorTile : function (params, done) { // pile._prepareTile(params, function (err, map) { // if (err) console.error({ // err_id : 3, // err_msg : 'render vector', // error : err // }); // if (err) return done(err); // var map_options = { // variables : { // zoom : params.z // insert min_max etc // } // } // // vector // var im = new mapnik.VectorTile(params.z, params.x, params.y); // // check // if (!im) return callback('Unsupported type.') // // render // map.render(im, map_options, function (err, tile) { // if (err) console.error({ // err_id : 4, // err_msg : 'render vector', // error : err // }); // store._saveVectorTile(tile, params, done); // }); // }); // }, _renderVectorTile : function (params, done) { // prepare tile: // parse url into layerUuid, zxy, type var ops = []; var map, layer, postgis, bbox; // check params if (!params.layerUuid) return done('Invalid url: Missing layerUuid.'); if (params.z == undefined) return done('Invalid url: Missing tile coordinates. z', params.z); if (params.x == undefined) return done('Invalid url: Missing tile coordinates. x', params.x); if (params.y == undefined) return done('Invalid url: Missing tile coordinates. y', params.y); if (!params.type) return done('Invalid url: Missing type extension.'); // look for stored layerUuid ops.push(function (callback) { store.layers.get(params.layerUuid, callback); }); // define settings, xml ops.push(function (storedLayer, callback) { if (!storedLayer) return callback('No such layerUuid.'); var storedLayer = JSON.parse(storedLayer); // default settings var default_postgis_settings = { user : pgsql_options.dbuser, password : pgsql_options.dbpass, host : pgsql_options.dbhost, type : 'postgis', geometry_field : 'the_geom_3857', srid : '3857' } // set bounding box bbox = mercator.xyz_to_envelope(parseInt(params.x), parseInt(params.y), parseInt(params.z), false); // insert layer settings var postgis_settings = default_postgis_settings; postgis_settings.dbname = storedLayer.options.database_name; postgis_settings.table = storedLayer.options.sql; postgis_settings.extent = storedLayer.options.extent; postgis_settings.geometry_field = storedLayer.options.geom_column; postgis_settings.srid = storedLayer.options.srid; postgis_settings.asynchronous_request = true; postgis_settings.max_async_connection = 10; // everything in spherical mercator (3857)! try { map = new mapnik.Map(256, 256, mercator.proj4); layer = new mapnik.Layer('layer', mercator.proj4); postgis = new mapnik.Datasource(postgis_settings); // catch errors } catch (e) { return callback(e.message); } // set buffer map.bufferSize = 128; // set extent map.extent = bbox; // must have extent! // set datasource layer.datasource = postgis; // add styles layer.styles = ['layer']; // style names in xml // add layer to map map.add_layer(layer); // parse xml from cartocss pile.cartoRenderer(storedLayer.options.cartocss, layer, callback); }); // load xml to map ops.push(function (xml, callback) { map.fromString(xml, {strict : true}, callback); }); // run ops async.waterfall(ops, function (err, map) { // render vector tile: if (err) console.error({ err_id : 3, err_msg : 'render vector', error : err }); if (err) return done(err); var map_options = { variables : { zoom : params.z // insert min_max etc } } // vector var im = new mapnik.VectorTile(params.z, params.x, params.y); // check if (!im) return callback('Unsupported type.') // render map.render(im, map_options, function (err, tile) { if (err) console.error({ err_id : 4, err_msg : 'render vector', error : err }); store._saveVectorTile(tile, params, done); }); }); }, _renderRasterTile : function (params, done) { pile._prepareTile(params, function (err, map) { if (err) return done(err); if (!map) return done('no map 7474'); // map options var map_options = { variables : { zoom : params.z // insert min_max etc } } var map_options = { buffer_size : 128, // buffer_size : 32, variables : { zoom : params.z // insert min_max etc } } // raster var im = new mapnik.Image(256, 256); // var im = new mapnik.Image(64, 64); // render map.render(im, map_options, function (err, tile) { if (err) console.error({ err_id : 5, err_msg : 'render raster', error : err }); if (err) return done(err); // save png to redis store._saveRasterTile(tile, params, done); }); }); }, _renderGridTile : function (params, done) { pile._prepareTile(params, function (err, map) { if (err) console.error({ err_id : 61, err_msg : 'render grid tile', error : err }); if (err) return done(err); if (!map) return done('no map 4493'); var map_options = { variables : { zoom : params.z // insert min_max etc } } // raster var im = new mapnik.Grid(map.width, map.height); // var fields = ['gid', 'east', 'north', 'range', 'azimuth', 'vel', 'coherence', 'height', 'demerr']; var fields = ['gid']; // todo: this is hardcoded!, get first column instead (could be ['id'] etc) var map_options = { layer : 0, fields : fields, buffer_size : 128 } // check if (!im) return callback('Unsupported type.') // render map.render(im, map_options, function (err, grid) { if (err) return done(err); if (!grid) return done('no grid 233'); grid.encode({features : true}, function (err, utf) { if (err) return done(err); // save grid to redis var keyString = 'grid_tile:' + params.layerUuid + ':' + params.z + ':' + params.x + ':' + params.y; store.layers.set(keyString, JSON.stringify(utf), done); }); }); }); }, // return tiles from redis/disk or created getVectorTile : function (params, storedLayer, done) { // check redis store._readVectorTile(params, function (err, data) { // return data if (data) return done(null, data); // create pile.createVectorTile(params, storedLayer, done); }); }, getRasterTile : function (params, storedLayer, done) { // check cache store._readRasterTile(params, function (err, data) { // return data if (data) return done(null, data); // create pile.createRasterTile(params, storedLayer, done); }); }, getGridTile : function (params, storedLayer, done) { // check cache pile._getGridTileFromRedis(params, function (err, data) { // found, return data if (data) return done(null, data); // not found, create pile.createGridTile(params, storedLayer, done); }); }, getRandomChars : function (len, charSet) { charSet = charSet || 'abcdefghijklmnopqrstuvwxyz'; var randomString = ''; for (var i = 0; i < len; i++) { var randomPoz = Math.floor(Math.random() * charSet.length); randomString += charSet.substring(randomPoz,randomPoz+1); } return randomString; }, // get tiles from redis _getRasterTileFromRedis : function (params, done) { var keyString = 'raster_tile:' + params.layerUuid + ':' + params.z + ':' + params.x + ':' + params.y; var key = new Buffer(keyString); store.layers.get(key, done); }, _getVectorTileFromRedis : function (params, done) { var keyString = 'vector_tile:' + params.layerUuid + ':' + params.z + ':' + params.x + ':' + params.y; var key = new Buffer(keyString); store.layers.get(key, done); }, _getGridTileFromRedis : function (params, done) { var keyString = 'grid_tile:' + params.layerUuid + ':' + params.z + ':' + params.x + ':' + params.y; store.layers.get(keyString, done); }, checkParams : function (params, done) { if (!params.layerUuid) return done('Invalid url: Missing layerUuid.'); if (params.z == undefined) return done('Invalid url: Missing tile coordinates. z', params.z); if (params.x == undefined) return done('Invalid url: Missing tile coordinates. x', params.x); if (params.y == undefined) return done('Invalid url: Missing tile coordinates. y', params.y); if (!params.type) return done('Invalid url: Missing type extension.'); return done(null); }, _prepareTile : function (params, done) { // parse url into layerUuid, zxy, type var ops = []; var map, layer, postgis, bbox; // check params if (!params.layerUuid) return done('Invalid url: Missing layerUuid.'); if (params.z == undefined) return done('Invalid url: Missing tile coordinates. z', params.z); if (params.x == undefined) return done('Invalid url: Missing tile coordinates. x', params.x); if (params.y == undefined) return done('Invalid url: Missing tile coordinates. y', params.y); if (!params.type) return done('Invalid url: Missing type extension.'); // look for stored layerUuid ops.push(function (callback) { store.layers.get(params.layerUuid, callback); }); // define settings, xml ops.push(function (storedLayer, callback) { if (!storedLayer) return callback('No such layerUuid.'); var storedLayer = JSON.parse(storedLayer); // default settings var default_postgis_settings = { user : pgsql_options.dbuser, password : pgsql_options.dbpass, host : pgsql_options.dbhost, type : 'postgis', geometry_field : 'the_geom_3857', srid : '3857' } // set bounding box bbox = mercator.xyz_to_envelope(parseInt(params.x), parseInt(params.y), parseInt(params.z), false); // insert layer settings var postgis_settings = default_postgis_settings; postgis_settings.dbname = storedLayer.options.database_name; postgis_settings.table = storedLayer.options.sql; postgis_settings.extent = storedLayer.options.extent; postgis_settings.geometry_field = storedLayer.options.geom_column; postgis_settings.srid = storedLayer.options.srid; postgis_settings.asynchronous_request = true; postgis_settings.max_async_connection = 10; // everything in spherical mercator (3857)! try { map = new mapnik.Map(256, 256, mercator.proj4); // map = new mapnik.Map(64, 64, mercator.proj4); layer = new mapnik.Layer('layer', mercator.proj4); postgis = new mapnik.Datasource(postgis_settings); // catch errors } catch (e) { return callback(e.message); } // set buffer // map.bufferSize = 32; map.bufferSize = 128; // set extent map.extent = bbox; // must have extent! // set datasource layer.datasource = postgis; // add styles layer.styles = ['layer']; // style names in xml // add layer to map map.add_layer(layer); // parse xml from cartocss pile.cartoRenderer(storedLayer.options.cartocss, layer, callback); }); // load xml to map ops.push(function (xml, callback) { map.fromString(xml, {strict : true}, callback); }); // run ops async.waterfall(ops, done); }, _checkTileIntersect : function (bbox, extentString) { var extent = [ parseFloat(extentString.split(' ')[0]), parseFloat(extentString.split(' ')[1].split(',')[0]), parseFloat(extentString.split(',')[1].split(' ')[0]), parseFloat(extentString.split(',')[1].split(' ')[1]), ] return pile._intersects(bbox, extent); }, _intersects : function (box1, box2) { // return true if boxes intersect, quick n dirty // tile var box1_xmin = box1[0] var box1_ymin = box1[1] var box1_xmax = box1[2] var box1_ymax = box1[3] // data var box2_xmin = box2[0] var box2_ymin = box2[1] var box2_xmax = box2[2] var box2_ymax = box2[3] // if both sides of tile is further north than extent, no overlap possible if (box1_ymax > box2_ymax && box1_ymin > box2_ymax) return false; // if both sides of tile is further west than extent, no overlap possible if (box1_xmin < box2_xmin && box1_xmax < box2_xmin) return false; // if both sides of tile is further south than extent, no overlap possible if (box1_ymin < box2_ymin && box1_ymax < box2_ymin) return false; // if both sides of tile is further east than extent, no overlap possible if (box1_xmax > box2_xmax && box1_xmin > box2_xmax) return false; return true; }, // convert CartoCSS to Mapnik XML cartoRenderer : function (css, layer, callback) { var options = { // srid 3857 "srs": "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over", "Stylesheet": [{ "id" : 'tile_style', "data" : css }], "Layer" : [layer] } try { // carto renderer var xml = new carto.Renderer().render(options); callback(null, xml); } catch (e) { var err = { message : e } callback(err); } }, // todo: old code, but we prob need this? getFile : function (req, res) { // get access token var access_token = pile._getAccessToken(req), file_id = req.query.file_id, ops = []; // no access if (!access_token) return pile.error.noAccess(res); // check for missing info if (!file_id) return pile.error.missingInformation(res, 'file_id'); // todo: check permission to access file // get from wu pile.request.get('/api/bridge/getFile', { file_id : file_id, access_token : access_token }, function (err, results) { }); }, request : { get : function (endpoint, options, callback) { var baseUrl = 'http://wu:3001', params = ''; if (_.size(options)) { params += '?'; var n = _.size(options); for (o in options) { params += o + '=' + options[o]; n--; if (n) params += '&' } } request({ method : 'GET', uri : baseUrl + endpoint + params }, function (err, response, body) { callback(err, body); }); }, }, _getAccessToken : function (req) { var access_token = req.query.access_token || req.body.access_token; return access_token; }, error : { missingInformation : function (res, missing) { var error = 'Missing information' var error_description = missing + ' Check out the documentation on https://docs.systemapic.com.'; res.json({ error : error, error_description : error_description }); }, noAccess : function (res) { res.json({ error : 'Unauthenicated.' }); }, } } // ######################################### // ### Initialize Kue ### // ######################################### // init kue var jobs = kue.createQueue({ redis : config.redis.temp, prefix : '_kue4' }); // clear kue jobs.watchStuckJobs(); // ######################################### // ### Clusters ### // ######################################### // master cluster: if (cluster.isMaster) { // start server server(pile); console.log('Cluster...' + numCPUs); for (var i = 0; i < numCPUs - 2; i++) { // 6 cpus // fork workers cluster.fork(); } // listen to exit, keep alive cluster.on('exit', function(worker, code, signal) { console.error({ err_id : 7, err_msg : 'cluster died', }); cluster.fork(); }); } else { // worker clusters, kues: console.log('...clustering!'); // ######################################### // ### Kue jobs: Vector render ### // ######################################### // render vector job jobs.process('render_vector_tile', 1, function (job, done) { var params = job.data.params; pile._renderVectorTile(params, function (err) { if (err) console.error({ err_id : 8, err_msg : 'render vector tile', error : err }); done(err); }); }); // render raster job jobs.process('render_raster_tile', 3, function (job, done) { var params = job.data.params; // render pile._renderRasterTile(params, function (err) { if (err) { console.error({ err_id : 9, err_msg : 'Error rendering raster tile', error : err }); return done(err); } done(null); }); }); // render grid job jobs.process('render_grid_tile', 1, function (job, done) { var params = job.data.params; pile._renderGridTile(params, function (err) { if (err) console.error({ err_id : 10, err_msg : 'Error rendering grid tile', error : err }); done(err); }); }); // render grid job jobs.process('proxy_tile', 100, function (job, done) { var options = job.data.options; proxy._getTile(options, function (err) { if (err) console.error({ err_id : 11, err_msg : 'proxy tile job', error : err }); done(); }); }); // remove stale jobs jobs.on('job complete', function (id) { kue.Job.get(id, function (err, job) { if (err) return; var params = job.data.params; var job_id = job.id; job.remove( function (err) { if (err) console.error({ err_id : 13, err_msg : 'job remove', error : err }); }); }); }); }
src/pile.js
// dependencies var _ = require('lodash'); var fs = require('fs-extra'); var kue = require('kue'); var path = require('path'); var zlib = require('zlib'); var uuid = require('uuid'); var async = require('async'); var redis = require('redis'); var carto = require('carto'); var mapnik = require('mapnik'); var colors = require('colors'); var cluster = require('cluster'); var numCPUs = require('os').cpus().length; var mongoose = require('mongoose'); var request = require('request'); var exec = require('child_process').exec; var pg = require('pg'); var gm = require('gm'); var sanitize = require("sanitize-filename"); // modules var server = require('./server'); var config = require('../config/pile-config'); var store = require('./store'); var proxy = require('./proxy'); // mercator var mercator = require('./sphericalmercator'); var geojsonArea = require('geojson-area'); // register mapnik plugions mapnik.register_default_fonts(); mapnik.register_default_input_plugins(); // global paths (todo: move to config) var VECTORPATH = '/data/vector_tiles/'; var RASTERPATH = '/data/raster_tiles/'; var GRIDPATH = '/data/grid_tiles/'; var PROXYPATH = '/data/proxy_tiles/'; var pgsql_options = { dbhost: 'postgis', dbuser: process.env.SYSTEMAPIC_PGSQL_USERNAME || 'docker', dbpass: process.env.SYSTEMAPIC_PGSQL_PASSWORD || 'docker' }; module.exports = pile = { headers : { jpeg : 'image/jpeg', png : 'image/png', pbf : 'application/x-protobuf', grid : 'application/json' }, proxyProviders : ['google', 'norkart'], // getTile : function (req, res) { if (pile.tileIsProxy(req)) return pile.serveProxyTile(req, res); if (pile.tileIsPostgis(req)) return pile.serveTile(req, res); res.end(); // todo: error handling }, tileIsProxy : function (req) { var params = req.params[0].split('/'); var provider = params[0]; var isProxy = _.contains(pile.proxyProviders, provider); return isProxy; }, tileIsPostgis : function (req) { var params = req.params[0].split('/'); var layer_id = params[0]; var isPostgis = _.contains(layer_id, 'layer_id-'); return isPostgis; }, // decide whether postgis or overlay_raster... todo: refactor with rasters in postgis (no more overlays) serveTile : function (req, res) { // parse url into layerUuid, zxy, type var ops = []; var parsed = req._parsedUrl.pathname.split('/'); var params = { layerUuid : parsed[3], z : parseInt(parsed[4]), x : parseInt(parsed[5]), y : parseInt(parsed[6].split('.')[0]), type : parsed[6].split('.')[1], }; store.layers.get(params.layerUuid, function (err, storedLayerJSON) { var storedLayer = JSON.parse(storedLayerJSON); console.log('storedLayer: ', storedLayer); if (storedLayer.options.data_type == 'raster') { // todo: diff between overlay/raster return pile.getOverlayTile(req, res); } if (storedLayer.options.data_type == 'vector') { return pile._getTile(req, res); } }); }, _getTile : function (req, res) { // parse url into layerUuid, zxy, type var ops = []; var parsed = req._parsedUrl.pathname.split('/'); var params = { layerUuid : parsed[3], z : parseInt(parsed[4]), x : parseInt(parsed[5]), y : parseInt(parsed[6].split('.')[0]), type : parsed[6].split('.')[1], }; var map; var layer; var postgis; var bbox; var type = params.type; var ops = []; var start_time = new Date().getTime(); // add access token to params params.access_token = req.query.access_token || req.body.access_token; // get stored layer store.layers.get(params.layerUuid, function (err, storedLayerJSON) { if (err) return pile._getTileErrorHandler(res, err); if (!storedLayerJSON) return pile._getTileErrorHandler(res, 'No stored layer.'); var storedLayer = JSON.parse(storedLayerJSON); console.log('storedLayer: ', storedLayer); // get tiles if (type == 'pbf') ops.push(function (callback) { pile.getVectorTile(params, storedLayer, callback); }); if (type == 'png') ops.push(function (callback) { pile.getRasterTile(params, storedLayer, callback); }); if (type == 'grid') ops.push(function (callback) { pile.getGridTile(params, storedLayer, callback); }); // run ops async.series(ops, function (err, data) { if (err) { console.error({ err_id : 2, err_msg : 'render vector', error : err }); // return res.end(); if (type == 'png') return pile.serveEmptyTile(res); return res.json({}); } // timer var end_time = new Date().getTime(); var create_tile_time = end_time - start_time; // log tile request console.tile({ z : params.z, x : params.x, y : params.y, format : type, layer_id : params.layerUuid, render_time : create_tile_time }); // send to client res.writeHead(200, {'Content-Type': pile.headers[type]}); res.end(data[0]); }); }); }, // todo: REFACTOR with proper postgis raster instead getOverlayTile : function (req, res) { // parse url into layerUuid, zxy, type var ops = [], parsed = req._parsedUrl.pathname.split('/'), params = { layerUuid : parsed[3], z : parseInt(parsed[4]), x : parseInt(parsed[5]), y : parseInt(parsed[6].split('.')[0]), type : parsed[6].split('.')[1], }; var map, layer, postgis, bbox; var type = params.type; var ops = []; console.log('overlaye params', params); // get stored layer store.layers.get(params.layerUuid, function (err, storedLayerJSON) { if (err) return pile._getTileErrorHandler(res, err); if (!storedLayerJSON) return pile._getTileErrorHandler(res, 'No stored layer.'); var storedLayer = JSON.parse(storedLayerJSON); var cutColor = storedLayer.options.cutColor; if (cutColor) { var colorName = sanitize(cutColor); // get file etc. var file_id = storedLayer.options.file_id; var originalPath = '/data/raster_tiles/' + file_id + '/raster/' + params.z + '/' + params.x + '/' + params.y + '.png'; var path = originalPath + '.cut-' + colorName; fs.readFile(path, function (err, buffer) { // not created yet, do it! if (err || !buffer) { // cut white; todo: all colors (with threshold) if (colorName == 'white') { pile._cutWhite({ path : path, originalPath : originalPath, returnBuffer : true }, function (err, buffer) { // send to client res.writeHead(200, {'Content-Type': pile.headers[type]}); res.end(buffer); }); // cut black: todo: https://github.com/systemapic/wu/issues/256 } else if (colorName == 'black') { pile._cutBlack({ path : path, originalPath : originalPath, returnBuffer : true }, function (err, buffer) { // send to client res.writeHead(200, {'Content-Type': pile.headers[type]}); res.end(buffer); }); // no cut } else { console.log('no cut raster! probably something wrong...') // send to client res.writeHead(200, {'Content-Type': pile.headers[type]}); res.end(buffer); } } else { // send to client res.writeHead(200, {'Content-Type': pile.headers[type]}); res.end(buffer); } }); } else { // get file etc. var file_id = storedLayer.options.file_id; var path = '/data/raster_tiles/' + file_id + '/raster/' + params.z + '/' + params.x + '/' + params.y + '.png'; fs.readFile(path, function (err, buffer) { // send to client res.writeHead(200, {'Content-Type': pile.headers[type]}); res.end(buffer); }); } }); }, serveProxyTile : function (req, res) { // parse url var params = req.params[0].split('/'); // set options var options = { provider : params[0], type : params[1], z : params[2], x : params[3], y : params[4].split('.')[0], format : params[4].split('.')[1] } // create proxy tile job var job = jobs.create('proxy_tile', { options : options, }).priority('high').attempts(5).save(); // proxy tile job done job.on('complete', function (result) { // serve proxy tile proxy.serveTile(res, options); }); }, fetchData : function (req, res) { var options = req.body, column = options.column, // gid row = options.row, // eg. 282844 layer_id = options.layer_id, ops = []; ops.push(function (callback) { // retrieve layer and return it to client store.layers.get(layer_id, function (err, layer) { if (err || !layer) return callback(err || 'no layer'); callback(null, JSON.parse(layer)); }); }); ops.push(function (layer, callback) { var table = layer.options.table_name; var database = layer.options.database_name; // do sql query on postgis var GET_DATA_SCRIPT_PATH = 'src/get_data_by_column.sh'; // st_extent script var command = [ GET_DATA_SCRIPT_PATH, // script layer.options.database_name, // database name layer.options.table_name, // table name column, row ].join(' '); // create database in postgis exec(command, {maxBuffer: 1024 * 1024 * 1000}, function (err, stdout, stdin) { if (err) return callback(err); // parse results var json = stdout.split('\n')[2]; var data = JSON.parse(json); // remove geom columns data.geom = null; data.the_geom_3857 = null; data.the_geom_4326 = null; // callback callback(null, data); }); }); async.waterfall(ops, function (err, data) { if (err) console.error({ err_id : 51, err_msg : 'fetch data script', error : err }); res.json(data); }); }, fetchDataArea : function (req, res) { var options = req.body, geojson = options.geojson, access_token = options.access_token, layer_id = options.layer_id; var ops = []; // error handling if (!geojson) return pile.error.missingInformation(res, 'Please provide an area.') ops.push(function (callback) { // retrieve layer and return it to client store.layers.get(layer_id, function (err, layer) { if (err || !layer) return callback(err || 'no layer'); callback(null, JSON.parse(layer)); }); }); ops.push(function (layer, callback) { var table = layer.options.table_name; var database = layer.options.database_name; var polygon = "'" + JSON.stringify(geojson.geometry) + "'"; var sql = '"' + layer.options.sql + '"'; // do sql query on postgis var GET_DATA_AREA_SCRIPT_PATH = 'src/get_data_by_area.sh'; // st_extent script var command = [ GET_DATA_AREA_SCRIPT_PATH, // script layer.options.database_name, // database name sql, polygon ].join(' '); // do postgis script exec(command, {maxBuffer: 1024 * 50000}, function (err, stdout, stdin) { if (err) return callback(err); var arr = stdout.split('\n'), result = []; arr.forEach(function (arrr) { try { var item = JSON.parse(arrr); result.push(item); } catch (e) {}; }); var points = []; result.forEach(function (point) { // delete geoms delete point.geom; delete point.the_geom_3857; delete point.the_geom_4326; // push points.push(point); }); // calculate averages, totals var average = pile._calculateAverages(points); var total_points = points.length; // only return 100 points if (points.length > 100) { points = points.slice(0, 100); } // return results var resultObject = { all : points, average : average, total_points : total_points, area : geojsonArea.geometry(geojson.geometry), layer_id : layer_id } // callback callback(null, resultObject); }); }); async.waterfall(ops, function (err, data) { if (err) console.error({ err_id : 52, err_msg : 'fetch data area script', error : err }); res.json(data); }); }, fetchHistogram : function (req, res) { var options = req.body, column = options.column, access_token = options.access_token, layer_id = options.layer_id, num_buckets = options.num_buckets || 20; var ops = []; ops.push(function (callback) { // retrieve layer and return it to client store.layers.get(layer_id, function (err, layer) { if (err || !layer) return callback(err || 'no layer'); callback(null, JSON.parse(layer)); }); }); ops.push(function (layer, callback) { var table = layer.options.table_name; var database = layer.options.database_name; // do sql query on postgis var GET_HISTOGRAM_SCRIPT = 'src/get_histogram.sh'; // st_extent script var command = [ GET_HISTOGRAM_SCRIPT, // script database, // database name table, column, num_buckets ].join(' '); // do postgis script exec(command, {maxBuffer: 1024 * 50000}, function (err, stdout, stdin) { if (err) return callback(err); var arr = stdout.split('\n'), result = []; arr.forEach(function (arrr) { try { var item = JSON.parse(arrr); result.push(item); } catch (e) {}; }); callback(null, result); }); }); async.waterfall(ops, function (err, data) { if (err) console.error({ err_id : 53, err_msg : 'fetch histogram script', error : err }); res.json(data); }); }, _calculateAverages : function (points) { var keys = {}; // get keys for (var key in points[0]) { keys[key] = []; } // sum values points.forEach(function (p) { for (var key in p) { keys[key].push(p[key]); } }); // calc avg var averages = {}; for (var k in keys) { averages[k] = (_.sum(keys[k]) / keys[k].length) } return averages; }, // this layer is only a postgis layer. a Wu Layer Model must be created by client after receiving this postgis layer createLayer : function (req, res) { var options = req.body, file_id = options.file_id, sql = options.sql, cartocss = options.cartocss, cartocss_version = options.cartocss_version, geom_column = options.geom_column, geom_type = options.geom_type, raster_band = options.raster_band, srid = options.srid, affected_tables = options.affected_tables, interactivity = options.interactivity, attributes = options.attributes, access_token = req.body.access_token; // log to file console.log({ type : 'createLayer', options : options }); // verify query if (!file_id) return pile.error.missingInformation(res, 'Please provide a file_id.') var ops = []; ops.push(function (callback) { // get upload status object from wu pile.request.get('/api/import/status', { // todo: write more pluggable file_id : file_id, access_token : access_token }, callback); }); ops.push(function (upload_status, callback) { if (!upload_status) return callback('No such upload_status.'); var upload_status = JSON.parse(upload_status); // check that done importing to postgis if (!upload_status.upload_success) return callback('The data was not uploaded correctly. Please check your data and error messages, and try again.') // todo: errors // check that done importing to postgis if (!upload_status.processing_success) return callback('The data is not done processing yet. Please try again in a little while.') // create postgis layer if (upload_status.data_type == 'vector') { return pile._createPostGISLayer({ upload_status : upload_status, options : options }, callback); } // create raster overlay if (upload_status.data_type == 'raster') { return pile._createRasterLayer({ upload_status : upload_status, options : options }, callback); } // error callback('Invalid data_type: ' + upload_status.data_type); }) async.waterfall(ops, function (err, layerObject) { if (err) { console.error({ err_id : 30, err_msg : 'create layer', error : err }); return res.json({error : err}); } // return layer to client res.json(layerObject); }); }, vectorizeLayer : function (req, res) { // vectorize raster (create postgis layer) return pile.vectorizeRaster({ options : options, upload_status : upload_status }, callback); var options = req.body, file_id = options.file_id, sql = options.sql, cartocss = options.cartocss, cartocss_version = options.cartocss_version, geom_column = options.geom_column, geom_type = options.geom_type, raster_band = options.raster_band, srid = options.srid, affected_tables = options.affected_tables, interactivity = options.interactivity, attributes = options.attributes, access_token = req.body.access_token; // log to file console.log({ type : 'createLayer', options : options }); // verify query if (!file_id) return pile.error.missingInformation(res, 'Please provide a file_id.') var ops = []; ops.push(function (callback) { // // get upload status object from wu // pile.request.get('/api/import/status', { // todo: write more pluggable // file_id : file_id, // access_token : access_token // }, callback); callback() }); ops.push(function (upload_status, callback) { if (!upload_status) return callback('No such upload_status.'); var upload_status = JSON.parse(upload_status); // check that done importing to postgis if (!upload_status.upload_success) return callback('The data was not uploaded correctly. Please check your data and error messages, and try again.') // todo: errors // check that done importing to postgis if (!upload_status.processing_success) return callback('The data is not done processing yet. Please try again in a little while.') // create postgis layer if (upload_status.data_type == 'vector') { return pile._createPostGISLayer({ upload_status : upload_status, options : options }, callback); } // create raster overlay if (upload_status.data_type == 'raster') { return pile._createRasterLayer({ upload_status : upload_status, options : options }, callback); } // error callback('Invalid data_type: ' + upload_status.data_type); }) async.waterfall(ops, function (err, layerObject) { if (err) { console.error({ err_id : 30, err_msg : 'create layer', error : err }); return res.json({error : err}); } // return layer to client res.json(layerObject); }); }, vectorizeRaster : function (data, done) { // create vector table from raster // create postgislayer (vector) from new table // return layer var status = data.upload_status; var options = data.options; var vectorized_raster_file_id; var layerJSON; var ops = []; ops.push(function (callback) { var VECTORIZE_SCRIPT_PATH = 'src/vectorize_raster.sh'; vectorized_raster_file_id = 'vectorized_raster_' + pile.getRandomChars(20); // st_extent script var command = [ VECTORIZE_SCRIPT_PATH, // script status.database_name, // database name vectorized_raster_file_id, status.table_name, // table name ].join(' '); // console.log('command: ', command); // create database in postgis exec(command, {maxBuffer: 1024 * 50000}, function (err, stdout, stdin) { // console.log('err, stdout, stdin', err, stdout, stdin); options.sql = "(SELECT * FROM " + vectorized_raster_file_id + ") as sub"; options.table_name = vectorized_raster_file_id; // callback callback(err); }); }); ops.push(function (callback) { pile._primeTableWithGeometries({ file_id : vectorized_raster_file_id, postgis_db : status.database_name, }, callback); }); ops.push(function (callback) { return pile._createPostGISLayer({ upload_status : status, options : options }, function (err, layer) { layerJSON = layer; callback(err); }); }); // ops.push(function (callback) { // }); async.series(ops, function (err) { done(err, layerJSON); }); }, _primeTableWithGeometries : function (options, done) { var file_id = options.file_id, postgis_db = options.postgis_db, ops = []; // console.log('_primeTableWithGeometries', options); // get geometry type ops.push(function (callback) { pile.pgquery({ postgis_db : postgis_db, query : 'SELECT ST_GeometryType(geom) from "' + file_id + '" limit 1' }, function (err, results) { if (err) return callback(err); if (!results || !results.rows || !results.rows.length) return callback('The dataset contains no valid geodata.'); var geometry_type = results.rows[0].st_geometrytype.split('ST_')[1]; callback(null, geometry_type); }) }); // create geometry 3857 ops.push(function (geometry_type, callback) { var column = ' the_geom_3857'; var geometry = ' geometry(' + geometry_type + ', 3857)'; var query = 'ALTER TABLE ' + file_id + ' ADD COLUMN' + column + geometry; pile.pgquery({ postgis_db : postgis_db, query : query }, function (err, results) { if (err) return callback(err); callback(null, geometry_type); }); }); // create geometry 4326 ops.push(function (geometry_type, callback) { var column = ' the_geom_4326'; var geometry = ' geometry(' + geometry_type + ', 4326)'; var query = 'ALTER TABLE ' + file_id + ' ADD COLUMN' + column + geometry; pile.pgquery({ postgis_db : postgis_db, query : query }, function (err, results) { if (err) return callback(err); callback(err, geometry_type); }); }); // populate geometry ops.push(function (geometry_type, callback) { var query = 'ALTER TABLE ' + file_id + ' ALTER COLUMN the_geom_3857 TYPE Geometry(' + geometry_type + ', 3857) USING ST_Transform(geom, 3857)' pile.pgquery({ postgis_db : postgis_db, query : query }, function (err, results) { if (err) return callback(err); callback(err, geometry_type); }); }); // populate geometry ops.push(function (geometry_type, callback) { var query = 'ALTER TABLE ' + file_id + ' ALTER COLUMN the_geom_4326 TYPE Geometry(' + geometry_type + ', 4326) USING ST_Transform(geom, 4326)' pile.pgquery({ postgis_db : postgis_db, query : query }, function (err, results) { if (err) return callback(err); callback(err); }); }); // create index for 3857 ops.push(function (callback) { var idx = file_id + '_the_geom_4326_idx'; var query = 'CREATE INDEX ' + idx + ' ON ' + file_id + ' USING GIST(the_geom_4326)' pile.pgquery({ postgis_db : postgis_db, query : query }, function (err, results) { if (err) return callback(err); callback(null); }); }); // create index for 4326 ops.push(function (callback) { var idx = file_id + '_the_geom_3857_idx'; var query = 'CREATE INDEX ' + idx + ' ON ' + file_id + ' USING GIST(the_geom_3857)' pile.pgquery({ postgis_db : postgis_db, query : query }, function (err, results) { if (err) return callback(err); callback(null, 'ok'); }); }); async.waterfall(ops, function (err, results) { done(err); }); }, pgquery : function (options, callback) { var postgis_db = options.postgis_db, variables = options.variables, query = options.query; var dbhost = pgsql_options.dbhost; var dbuser = pgsql_options.dbuser; var dbpass = pgsql_options.dbpass; var conString = 'postgres://'+dbuser+':'+dbpass+'@'+dbhost+'/' + postgis_db; pg.connect(conString, function(err, client, pgcb) { if (err) return callback(err); // do query client.query(query, variables, function(err, result) { // clean up after pg pgcb(); // client.end(); if (err) return callback(err); // return result callback(null, result); }); }); }, _createPostGISLayer : function (opts, done) { var ops = [], options = opts.upload_status, file_id = opts.options.file_id, sql = opts.options.sql, cartocss = opts.options.cartocss, cartocss_version = opts.options.cartocss_version, geom_column = opts.options.geom_column, geom_type = opts.options.geom_type, raster_band = opts.options.raster_band, srid = opts.options.srid, affected_tables = opts.options.affected_tables, interactivity = opts.options.interactivity, attributes = opts.options.attributes, access_token = opts.options.access_token; if (!sql) return done('Please provide a SQL statement.') if (!cartocss) return done('Please provide CartoCSS.') ops.push(function (callback) { // inject table name into sql var done_sql = sql.replace('table', options.table_name); // create layer object var layerUuid = 'layer_id-' + uuid.v4(); var layer = { layerUuid : layerUuid, options : { // required sql : done_sql, cartocss : cartocss, file_id : file_id, database_name : options.database_name, table_name : options.table_name, metadata : options.metadata, layer_id : layerUuid, wicked : 'thing', data_type : options.data_type || opts.options.data_type || 'vector', // optional // defaults cartocss_version : cartocss_version || '2.0.1', geom_column : geom_column || 'geom', geom_type : geom_type || 'geometry', raster_band : raster_band || 0, srid : srid || 3857, } } callback(null, layer); }); // get extent of file (todo: put in file object) ops.push(function (layer, callback) { var GET_EXTENT_SCRIPT_PATH = 'src/get_st_extent.sh'; // st_extent script var command = [ GET_EXTENT_SCRIPT_PATH, // script layer.options.database_name, // database name layer.options.table_name, // table name ].join(' '); // create database in postgis exec(command, {maxBuffer: 1024 * 50000}, function (err, stdout, stdin) { // parse stdout try { var extent = stdout.split('(')[1].split(')')[0]; } catch (e) { return callback(e); } // set extent layer.options.extent = extent; // callback callback(null, layer); }); }); // save layer to store.redis ops.push(function (layer, callback) { // save layer to store.redis store.layers.set(layer.layerUuid, JSON.stringify(layer), function (err) { if (err) console.error({ err_id : 1, err_msg : 'create postgis layer', error : err }); callback(err, layer); }); }); // layer created, return async.waterfall(ops, done); }, _createRasterLayer : function (opts, done) { var ops = [], options = opts.upload_status, file_id = opts.options.file_id, srid = opts.options.srid, srid = options.srid, access_token = opts.options.access_token; // console.log('_createRasterLayer', opts); var cutColor = opts.options.cutColor || false; ops.push(function (callback) { // create layer object var layerUuid = 'layer_id-' + uuid.v4(); var layer = { layerUuid : layerUuid, options : { // required sql : false, cartocss : false, file_id : file_id, metadata : options.metadata, layer_id : layerUuid, wicked : 'thing', srid : srid || 3857, data_type : 'raster', cutColor : cutColor } } callback(null, layer); }); // save layer to store.redis ops.push(function (layer, callback) { // save layer to store.redis store.layers.set(layer.layerUuid, JSON.stringify(layer), function (err) { if (err) console.error({ err_id : 2, err_msg : 'create raster', error : err }); callback(err, layer); }); }); // layer created, return async.waterfall(ops, done); }, getLayer : function (req, res) { // get layerUuid var layerUuid = req.body.layerUuid || req.query.layerUuid; if (!layerUuid) return pile.error.missingInformation(res, 'Please provide layerUuid.'); // retrieve layer and return it to client store.layers.get(layerUuid, function (err, layer) { if (err) console.error({ err_id : 21, err_msg : 'render vector', error : err }); res.end(layer); }); }, _cutWhite : function (options, callback) { var path = options.path; var originalPath = options.originalPath; var returnBuffer = options.returnBuffer; gm(originalPath) .whiteThreshold(200, 200, 200, 1) .transparent('#FFFFFF') .write(path, function (err) { if (!err && returnBuffer) { fs.readFile(path, callback); } else { callback(err); } }); }, _cutBlack : function (options, callback) { var path = options.path; var originalPath = options.originalPath; var returnBuffer = options.returnBuffer; gm(originalPath) .blackThreshold(20, 20, 20, 1) .transparent('#000000') .write(path, function (err) { if (!err && returnBuffer) { fs.readFile(path, callback); } else { callback(err); } }); }, cutColor : function (options, callback) { var path = options.path; var originalPath = options.originalPath; var color = options.color; var returnBuffer = options.returnBuffer; gm(originalPath) .whiteThreshold(220, 220, 220, 1) .transparent('#FFFFFF') .write(path, function (err) { if (!err && returnBuffer) { fs.readFile(path, callback); } else { callback(err); } }); }, _getTileErrorHandler : function (res, err) { if (err) console.error({ err_id : 60, err_msg : 'get tile error handler', error : err }); res.end(); }, createVectorTile : function (params, storedLayer, done) { // KUE: create raster tile var job = jobs.create('render_vector_tile', { // todo: cluster up with other machines, pluggable clusters params : params, storedLayer : storedLayer }).priority('high').attempts(5).save(); // KUE DONE: raster created job.on('complete', function (result) { // console.log('crated vecotr tile? ', result); // get tile store._readVectorTile(params, done); }); }, createRasterTile : function (params, storedLayer, done) { // KUE: create raster tile var job = jobs.create('render_raster_tile', { // todo: cluster up with other machines, pluggable clusters params : params, storedLayer : storedLayer }).priority('high').removeOnComplete(true).attempts(5).save(); // KUE DONE: raster created job.on('complete', function (result) { // get tile store._readRasterTile(params, done); }); job.on('failed', function (err) { done(err); }); }, _serveErrorTile : function (res) { var errorTile = 'public/errorTile.png'; fs.readFile('public/noAccessTile.png', function (err, tile) { res.writeHead(200, {'Content-Type': 'image/png'}); res.end(tile); }); }, serveEmptyTile : function (res) { fs.readFile('public/emptyTile.png', function (err, tile) { res.writeHead(200, {'Content-Type': 'image/png'}); res.end(tile); }); }, createGridTile : function (params, storedLayer, done) { // KUE: create raster tile var job = jobs.create('render_grid_tile', { // todo: cluster up with other machines, pluggable clusters params : params, storedLayer : storedLayer }).priority('high').attempts(5).save(); // KUE DONE: raster created job.on('complete', function (result) { // get tile pile._getGridTileFromRedis(params, done); }); job.on('failed', function (err) { done(err); }); }, // _renderVectorTile : function (params, done) { // pile._prepareTile(params, function (err, map) { // if (err) console.error({ // err_id : 3, // err_msg : 'render vector', // error : err // }); // if (err) return done(err); // var map_options = { // variables : { // zoom : params.z // insert min_max etc // } // } // // vector // var im = new mapnik.VectorTile(params.z, params.x, params.y); // // check // if (!im) return callback('Unsupported type.') // // render // map.render(im, map_options, function (err, tile) { // if (err) console.error({ // err_id : 4, // err_msg : 'render vector', // error : err // }); // store._saveVectorTile(tile, params, done); // }); // }); // }, _renderVectorTile : function (params, done) { // prepare tile: // parse url into layerUuid, zxy, type var ops = []; var map, layer, postgis, bbox; // check params if (!params.layerUuid) return done('Invalid url: Missing layerUuid.'); if (params.z == undefined) return done('Invalid url: Missing tile coordinates. z', params.z); if (params.x == undefined) return done('Invalid url: Missing tile coordinates. x', params.x); if (params.y == undefined) return done('Invalid url: Missing tile coordinates. y', params.y); if (!params.type) return done('Invalid url: Missing type extension.'); // look for stored layerUuid ops.push(function (callback) { store.layers.get(params.layerUuid, callback); }); // define settings, xml ops.push(function (storedLayer, callback) { if (!storedLayer) return callback('No such layerUuid.'); var storedLayer = JSON.parse(storedLayer); // default settings var default_postgis_settings = { user : pgsql_options.dbuser, password : pgsql_options.dbpass, host : pgsql_options.dbhost, type : 'postgis', geometry_field : 'the_geom_3857', srid : '3857' } // set bounding box bbox = mercator.xyz_to_envelope(parseInt(params.x), parseInt(params.y), parseInt(params.z), false); // insert layer settings var postgis_settings = default_postgis_settings; postgis_settings.dbname = storedLayer.options.database_name; postgis_settings.table = storedLayer.options.sql; postgis_settings.extent = storedLayer.options.extent; postgis_settings.geometry_field = storedLayer.options.geom_column; postgis_settings.srid = storedLayer.options.srid; postgis_settings.asynchronous_request = true; postgis_settings.max_async_connection = 10; // everything in spherical mercator (3857)! try { map = new mapnik.Map(256, 256, mercator.proj4); layer = new mapnik.Layer('layer', mercator.proj4); postgis = new mapnik.Datasource(postgis_settings); // catch errors } catch (e) { return callback(e.message); } // set buffer map.bufferSize = 128; // set extent map.extent = bbox; // must have extent! // set datasource layer.datasource = postgis; // add styles layer.styles = ['layer']; // style names in xml // add layer to map map.add_layer(layer); // parse xml from cartocss pile.cartoRenderer(storedLayer.options.cartocss, layer, callback); }); // load xml to map ops.push(function (xml, callback) { map.fromString(xml, {strict : true}, callback); }); // run ops async.waterfall(ops, function (err, map) { // render vector tile: if (err) console.error({ err_id : 3, err_msg : 'render vector', error : err }); if (err) return done(err); var map_options = { variables : { zoom : params.z // insert min_max etc } } // vector var im = new mapnik.VectorTile(params.z, params.x, params.y); // check if (!im) return callback('Unsupported type.') // render map.render(im, map_options, function (err, tile) { if (err) console.error({ err_id : 4, err_msg : 'render vector', error : err }); store._saveVectorTile(tile, params, done); }); }); }, _renderRasterTile : function (params, done) { pile._prepareTile(params, function (err, map) { if (err) return done(err); if (!map) return done('no map 7474'); // map options var map_options = { variables : { zoom : params.z // insert min_max etc } } var map_options = { buffer_size : 128, // buffer_size : 32, variables : { zoom : params.z // insert min_max etc } } // raster var im = new mapnik.Image(256, 256); // var im = new mapnik.Image(64, 64); // render map.render(im, map_options, function (err, tile) { if (err) console.error({ err_id : 5, err_msg : 'render raster', error : err }); if (err) return done(err); // save png to redis store._saveRasterTile(tile, params, done); }); }); }, _renderGridTile : function (params, done) { pile._prepareTile(params, function (err, map) { if (err) console.error({ err_id : 61, err_msg : 'render grid tile', error : err }); if (err) return done(err); if (!map) return done('no map 4493'); var map_options = { variables : { zoom : params.z // insert min_max etc } } // raster var im = new mapnik.Grid(map.width, map.height); // var fields = ['gid', 'east', 'north', 'range', 'azimuth', 'vel', 'coherence', 'height', 'demerr']; var fields = ['gid']; // todo: this is hardcoded!, get first column instead (could be ['id'] etc) var map_options = { layer : 0, fields : fields, buffer_size : 128 } // check if (!im) return callback('Unsupported type.') // render map.render(im, map_options, function (err, grid) { if (err) return done(err); if (!grid) return done('no grid 233'); grid.encode({features : true}, function (err, utf) { if (err) return done(err); // save grid to redis var keyString = 'grid_tile:' + params.layerUuid + ':' + params.z + ':' + params.x + ':' + params.y; store.layers.set(keyString, JSON.stringify(utf), done); }); }); }); }, // return tiles from redis/disk or created getVectorTile : function (params, storedLayer, done) { // check redis store._readVectorTile(params, function (err, data) { // return data if (data) return done(null, data); // create pile.createVectorTile(params, storedLayer, done); }); }, getRasterTile : function (params, storedLayer, done) { // check cache store._readRasterTile(params, function (err, data) { // return data if (data) return done(null, data); // create pile.createRasterTile(params, storedLayer, done); }); }, getGridTile : function (params, storedLayer, done) { // check cache pile._getGridTileFromRedis(params, function (err, data) { // found, return data if (data) return done(null, data); // not found, create pile.createGridTile(params, storedLayer, done); }); }, getRandomChars : function (len, charSet) { charSet = charSet || 'abcdefghijklmnopqrstuvwxyz'; var randomString = ''; for (var i = 0; i < len; i++) { var randomPoz = Math.floor(Math.random() * charSet.length); randomString += charSet.substring(randomPoz,randomPoz+1); } return randomString; }, // get tiles from redis _getRasterTileFromRedis : function (params, done) { var keyString = 'raster_tile:' + params.layerUuid + ':' + params.z + ':' + params.x + ':' + params.y; var key = new Buffer(keyString); store.layers.get(key, done); }, _getVectorTileFromRedis : function (params, done) { var keyString = 'vector_tile:' + params.layerUuid + ':' + params.z + ':' + params.x + ':' + params.y; var key = new Buffer(keyString); store.layers.get(key, done); }, _getGridTileFromRedis : function (params, done) { var keyString = 'grid_tile:' + params.layerUuid + ':' + params.z + ':' + params.x + ':' + params.y; store.layers.get(keyString, done); }, checkParams : function (params, done) { if (!params.layerUuid) return done('Invalid url: Missing layerUuid.'); if (params.z == undefined) return done('Invalid url: Missing tile coordinates. z', params.z); if (params.x == undefined) return done('Invalid url: Missing tile coordinates. x', params.x); if (params.y == undefined) return done('Invalid url: Missing tile coordinates. y', params.y); if (!params.type) return done('Invalid url: Missing type extension.'); return done(null); }, _prepareTile : function (params, done) { // parse url into layerUuid, zxy, type var ops = []; var map, layer, postgis, bbox; // check params if (!params.layerUuid) return done('Invalid url: Missing layerUuid.'); if (params.z == undefined) return done('Invalid url: Missing tile coordinates. z', params.z); if (params.x == undefined) return done('Invalid url: Missing tile coordinates. x', params.x); if (params.y == undefined) return done('Invalid url: Missing tile coordinates. y', params.y); if (!params.type) return done('Invalid url: Missing type extension.'); // look for stored layerUuid ops.push(function (callback) { store.layers.get(params.layerUuid, callback); }); // define settings, xml ops.push(function (storedLayer, callback) { if (!storedLayer) return callback('No such layerUuid.'); var storedLayer = JSON.parse(storedLayer); // default settings var default_postgis_settings = { user : pgsql_options.dbuser, password : pgsql_options.dbpass, host : pgsql_options.dbhost, type : 'postgis', geometry_field : 'the_geom_3857', srid : '3857' } // set bounding box bbox = mercator.xyz_to_envelope(parseInt(params.x), parseInt(params.y), parseInt(params.z), false); // insert layer settings var postgis_settings = default_postgis_settings; postgis_settings.dbname = storedLayer.options.database_name; postgis_settings.table = storedLayer.options.sql; postgis_settings.extent = storedLayer.options.extent; postgis_settings.geometry_field = storedLayer.options.geom_column; postgis_settings.srid = storedLayer.options.srid; postgis_settings.asynchronous_request = true; postgis_settings.max_async_connection = 10; // everything in spherical mercator (3857)! try { map = new mapnik.Map(256, 256, mercator.proj4); // map = new mapnik.Map(64, 64, mercator.proj4); layer = new mapnik.Layer('layer', mercator.proj4); postgis = new mapnik.Datasource(postgis_settings); // catch errors } catch (e) { return callback(e.message); } // set buffer // map.bufferSize = 32; map.bufferSize = 128; // set extent map.extent = bbox; // must have extent! // set datasource layer.datasource = postgis; // add styles layer.styles = ['layer']; // style names in xml // add layer to map map.add_layer(layer); // parse xml from cartocss pile.cartoRenderer(storedLayer.options.cartocss, layer, callback); }); // load xml to map ops.push(function (xml, callback) { map.fromString(xml, {strict : true}, callback); }); // run ops async.waterfall(ops, done); }, _checkTileIntersect : function (bbox, extentString) { var extent = [ parseFloat(extentString.split(' ')[0]), parseFloat(extentString.split(' ')[1].split(',')[0]), parseFloat(extentString.split(',')[1].split(' ')[0]), parseFloat(extentString.split(',')[1].split(' ')[1]), ] return pile._intersects(bbox, extent); }, _intersects : function (box1, box2) { // return true if boxes intersect, quick n dirty // tile var box1_xmin = box1[0] var box1_ymin = box1[1] var box1_xmax = box1[2] var box1_ymax = box1[3] // data var box2_xmin = box2[0] var box2_ymin = box2[1] var box2_xmax = box2[2] var box2_ymax = box2[3] // if both sides of tile is further north than extent, no overlap possible if (box1_ymax > box2_ymax && box1_ymin > box2_ymax) return false; // if both sides of tile is further west than extent, no overlap possible if (box1_xmin < box2_xmin && box1_xmax < box2_xmin) return false; // if both sides of tile is further south than extent, no overlap possible if (box1_ymin < box2_ymin && box1_ymax < box2_ymin) return false; // if both sides of tile is further east than extent, no overlap possible if (box1_xmax > box2_xmax && box1_xmin > box2_xmax) return false; return true; }, // convert CartoCSS to Mapnik XML cartoRenderer : function (css, layer, callback) { var options = { // srid 3857 "srs": "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over", "Stylesheet": [{ "id" : 'tile_style', "data" : css }], "Layer" : [layer] } try { // carto renderer var xml = new carto.Renderer().render(options); callback(null, xml); } catch (e) { var err = { message : e } callback(err); } }, // todo: old code, but we prob need this? getFile : function (req, res) { // get access token var access_token = pile._getAccessToken(req), file_id = req.query.file_id, ops = []; // no access if (!access_token) return pile.error.noAccess(res); // check for missing info if (!file_id) return pile.error.missingInformation(res, 'file_id'); // todo: check permission to access file // get from wu pile.request.get('/api/bridge/getFile', { file_id : file_id, access_token : access_token }, function (err, results) { }); }, request : { get : function (endpoint, options, callback) { var baseUrl = 'http://wu:3001', params = ''; if (_.size(options)) { params += '?'; var n = _.size(options); for (o in options) { params += o + '=' + options[o]; n--; if (n) params += '&' } } request({ method : 'GET', uri : baseUrl + endpoint + params }, function (err, response, body) { callback(err, body); }); }, }, _getAccessToken : function (req) { var access_token = req.query.access_token || req.body.access_token; return access_token; }, error : { missingInformation : function (res, missing) { var error = 'Missing information' var error_description = missing + ' Check out the documentation on https://docs.systemapic.com.'; res.json({ error : error, error_description : error_description }); }, noAccess : function (res) { res.json({ error : 'Unauthenicated.' }); }, } } // ######################################### // ### Initialize Kue ### // ######################################### // init kue var jobs = kue.createQueue({ redis : config.redis.temp, prefix : '_kue4' }); // clear kue jobs.watchStuckJobs(); // ######################################### // ### Clusters ### // ######################################### // master cluster: if (cluster.isMaster) { // start server server(pile); console.log('Cluster...' + numCPUs); for (var i = 0; i < numCPUs - 2; i++) { // 6 cpus // fork workers cluster.fork(); } // listen to exit, keep alive cluster.on('exit', function(worker, code, signal) { console.error({ err_id : 7, err_msg : 'cluster died', }); cluster.fork(); }); } else { // worker clusters, kues: console.log('...clustering!'); // ######################################### // ### Kue jobs: Vector render ### // ######################################### // render vector job jobs.process('render_vector_tile', 1, function (job, done) { var params = job.data.params; pile._renderVectorTile(params, function (err) { if (err) console.error({ err_id : 8, err_msg : 'render vector tile', error : err }); done(err); }); }); // render raster job jobs.process('render_raster_tile', 3, function (job, done) { var params = job.data.params; // render pile._renderRasterTile(params, function (err) { if (err) { console.error({ err_id : 9, err_msg : 'Error rendering raster tile', error : err }); return done(err); } done(null); }); }); // render grid job jobs.process('render_grid_tile', 1, function (job, done) { var params = job.data.params; pile._renderGridTile(params, function (err) { if (err) console.error({ err_id : 10, err_msg : 'Error rendering grid tile', error : err }); done(err); }); }); // render grid job jobs.process('proxy_tile', 100, function (job, done) { var options = job.data.options; proxy._getTile(options, function (err) { if (err) console.error({ err_id : 11, err_msg : 'proxy tile job', error : err }); done(); }); }); // remove stale jobs jobs.on('job complete', function (id) { kue.Job.get(id, function (err, job) { if (err) return; var params = job.data.params; var job_id = job.id; job.remove( function (err) { if (err) console.error({ err_id : 13, err_msg : 'job remove', error : err }); }); }); }); }
Create postgis layer for both vector and raster
src/pile.js
Create postgis layer for both vector and raster
<ide><path>rc/pile.js <ide> type : parsed[6].split('.')[1], <ide> }; <ide> <del> store.layers.get(params.layerUuid, function (err, storedLayerJSON) { <del> var storedLayer = JSON.parse(storedLayerJSON); <del> <del> console.log('storedLayer: ', storedLayer); <del> <del> if (storedLayer.options.data_type == 'raster') { // todo: diff between overlay/raster <del> return pile.getOverlayTile(req, res); <del> } <del> <del> if (storedLayer.options.data_type == 'vector') { <del> return pile._getTile(req, res); <del> } <del> <del> }); <del> }, <del> <add> return pile._getTile(req, res); <add> }, <ide> <ide> _getTile : function (req, res) { <ide> <ide> <ide> <ide> <del> // create postgis layer <del> if (upload_status.data_type == 'vector') { <del> <add> // create postgis layer for rasters and vector layers <add> if (upload_status.data_type == 'vector' <add> || upload_status.data_type == 'raster') <add> { <ide> return pile._createPostGISLayer({ <ide> upload_status : upload_status, <ide> options : options <ide> }, callback); <ide> } <del> <del> // create raster overlay <del> if (upload_status.data_type == 'raster') { <del> <del> return pile._createRasterLayer({ <del> upload_status : upload_status, <del> options : options <del> }, callback); <del> <del> } <ide> <ide> // error <ide> callback('Invalid data_type: ' + upload_status.data_type); <ide> <ide> <ide> <del> // create postgis layer <del> if (upload_status.data_type == 'vector') { <add> // create postgis layer for rasters and vector layers <add> if (upload_status.data_type == 'vector' <add> || upload_status.data_type == 'raster') <add> { <ide> <ide> return pile._createPostGISLayer({ <ide> upload_status : upload_status, <ide> options : options <ide> }, callback); <ide> } <del> <del> // create raster overlay <del> if (upload_status.data_type == 'raster') { <del> <del> return pile._createRasterLayer({ <del> upload_status : upload_status, <del> options : options <del> }, callback); <del> <del> } <ide> <ide> // error <ide> callback('Invalid data_type: ' + upload_status.data_type);
Java
apache-2.0
20848d1518b52e5c6610a20fdd4995cb5ea52a90
0
maxtat3/fmps
package ui; import controller.InputDataController; import controller.Stage1QuestionFrameController; import domain.User; import stage1.elements.GeneralElementStage1; import javax.swing.*; import javax.swing.border.EtchedBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; /** * */ public class Stage1QuestionFrame extends JFrame { private static final String PERCENT_SYM = "%"; private static final String ENT_LQ_ALLOY_SYM = "H<sub>L</sub><sup>0</sup>"; private static final String ENT_VAPORIZATION_SYM = "&Delta;H<sub>кип</sub>"; private static final String ENT_VAPOUR_SYM = "H<sub>g</sub>"; private static final String VAP_PRES_OVER_ALLOY_SYM = "P<sup>p</sup>"; private static final String DECR_MOLTEN_METAL_DUE_VAP_SYM = "&Delta;<i>v</i><sub>m</sub>"; private static final String KJOULE_SYM = "кДж/моль"; private JPanel jpMain = new JPanel(); private JPanel jpTitle = new JPanel(); private JPanel jpQuestion1 = new JPanel(); private JPanel jpQuestion2 = new JPanel(); private JPanel jpQuestion3 = new JPanel(); private JPanel jpQuestion4 = new JPanel(); private JPanel jpQuestion5 = new JPanel(); private JPanel jpQuestion6 = new JPanel(); private JPanel jpQuestion7 = new JPanel(); private JPanel jpQuestion8 = new JPanel(); private JPanel jpQuestion9 = new JPanel(); private JPanel jpStatusAndDirection = new JPanel(); // Elements for question 2 // 2.1 Расчет энтальпии жидкого сплава (кДж/моль) Enthalpy liquid alloy private JLabel jlEntLqAll = new JLabel("<html>Расчет энтальпии жидкого сплава: " + ENT_LQ_ALLOY_SYM + "</html>"); private JTextField jtfEntLqAll = new JTextField(); private JLabel jlEntLqAllUnits = new JLabel(KJOULE_SYM); // 2.2 Расчет энтальпии испарения (кДж/моль) Enthalpy vaporization private JLabel jlEntVaporization = new JLabel("<html>Расчет энтальпии испарения: " + ENT_VAPORIZATION_SYM + "</html>"); private JTextField jtfEntVaporization = new JTextField(); private JLabel jlEntVaporizationUnits = new JLabel(KJOULE_SYM); // 2.3 Энтальпия пара для сплава (кДж/моль) Enthalpy vapour private JLabel jlEntVapour = new JLabel("<html>Расчет энтальпии пара для сплава: " + ENT_VAPOUR_SYM + " </html>"); private JTextField jtfEntVapour = new JTextField(); private JLabel jlEntVapourUnits = new JLabel(KJOULE_SYM); // Elements for question 5 private JLabel jlVapPresOverAlloy = new JLabel("<html>Давление пара над сплавом " + VAP_PRES_OVER_ALLOY_SYM + " : </html>"); private JTextField jtfVapPresOverAlloy = new JTextField(); private JLabel jlVapPresOverAlloyUnits = new JLabel(" Па"); // Elements for question 9 private JLabel jlDecrMoltenMetalDueVap = new JLabel("<html>Уменьшение массы расплавленного металла за счет " + "испарения " + DECR_MOLTEN_METAL_DUE_VAP_SYM + " : </html>"); private JTextField jtfDecrMoltenMetalDueVap = new JTextField(); private JLabel jlDecrMoltenMetalDueVapUnits = new JLabel(" гр/сек"); private JButton jBtnExit = new JButton("Выход"); private JButton jBtnNext = new JButton("Далее >>>"); private JLabel jlUserFirstName = new JLabel(); // Имя private JLabel jlUserMiddleName = new JLabel(); // Отчество private JLabel jlUserLastName = new JLabel(); // Фамилия private JLabel jlStatusMsg = new JLabel("Правильных ответов: "); private PanelsTag panelsTag; private Stage1QuestionFrameController controller; private java.util.List<JTextField> jtfInputData = new ArrayList<>(); //for validate user input data only public Stage1QuestionFrame(User user) { super("Stage 1, question n"); controller = new Stage1QuestionFrameController(); jpQuestion1.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "Вопрос 1" )); jpQuestion2.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "Вопрос 2" )); jpQuestion3.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "Вопрос 3" )); jpQuestion4.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "Вопрос 4" )); jpQuestion5.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "Вопрос 5" )); jpQuestion6.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "Вопрос 6" )); jpQuestion7.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "Вопрос 7" )); jpQuestion8.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "Вопрос 8" )); jpQuestion9.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "Вопрос 9" )); jpQuestion1.add(new JLabel("Мольная доля всех элементов сплава (%): ")); jpQuestion2.add(new JLabel("Энтальпия жидкого сплава, энтальпия испарения, энтальпия пара (кДж/моль): ")); //2.1, 2.2, 2.3 jpQuestion3.add(new JLabel("Давление пара чистых компонентов (Па): ")); jpQuestion4.add(new JLabel("Парциальное давление компонент над сплавом (Па): ")); jpQuestion5.add(new JLabel("Давление пара над сплавом (Па): ")); jpQuestion6.add(new JLabel("Мольная доля каждого компонента в паре (%): ")); jpQuestion7.add(new JLabel("Весовая доля каждого компонента в паре (%): ")); jpQuestion8.add(new JLabel("Скорость испарения из сварочной ванны каждого элемента (гр/сек): ")); jpQuestion9.add(new JLabel("Скорость уменьшения массы расплавленного металла за счет испарения (гр/сек): ")); jpTitle.add(new JLabel("Задача 1. Расчет процессов испарения металлов при сварке плавлением")); jpTitle.setLayout(new FlowLayout(FlowLayout.CENTER)); jpMain.setLayout(new BorderLayout()); jpMain.add(jpTitle, BorderLayout.PAGE_START); // TODO: 26.05.17 May be remove all elements before load next panel from jpRows // Settings for status and directions panel jpStatusAndDirection.setLayout(new BoxLayout(jpStatusAndDirection, BoxLayout.Y_AXIS)); // add direction buttons JPanel jpDirBtns = new JPanel(new FlowLayout()); jBtnExit.setPreferredSize(new Dimension(100, 25)); jBtnNext.setPreferredSize(new Dimension(500, 25)); jpDirBtns.add(jBtnExit); jpDirBtns.add(jBtnNext); jpStatusAndDirection.add(jpDirBtns); // add JPanel jpStatAndDir = new JPanel(new FlowLayout(FlowLayout.CENTER)); jpStatAndDir.add(jlStatusMsg); jpStatusAndDirection.add(jpStatAndDir); // add FIO labels JPanel jpUserFIO = new JPanel(new FlowLayout()); jpUserFIO.add(jlUserLastName); // Ф jpUserFIO.add(jlUserFirstName); // И jpUserFIO.add(jlUserMiddleName); // О jpStatusAndDirection.add(jpUserFIO); jlUserFirstName.setText(user.getFirstName()); jlUserMiddleName.setText(user.getMiddleName()); jlUserLastName.setText(user.getLastName()); jlStatusMsg.setText(jlStatusMsg.getText() + "1/8"); // show question 1 panelsTag = PanelsTag.PANEL_1; switchQuestionPanel(); jpMain.add(jpStatusAndDirection, BorderLayout.PAGE_END); System.out.println("jtfInputData.size() = " + jtfInputData.size()); add(jpMain); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // setSize(500, 300); setLocation(200, 200); setVisible(true); pack(); // addComponentsListeners(); jBtnNext.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { switch (panelsTag) { case PANEL_1: if(generalValidateInputOfEachElem()) { panelsTag = PanelsTag.PANEL_2; switchQuestionPanel(); } break; case PANEL_2: if (validateInputQuestion2()) { panelsTag = PanelsTag.PANEL_3; switchQuestionPanel(); } break; case PANEL_3: if (generalValidateInputOfEachElem()) { panelsTag = PanelsTag.PANEL_4; switchQuestionPanel(); } break; case PANEL_4: if (generalValidateInputOfEachElem()) { panelsTag = PanelsTag.PANEL_5; switchQuestionPanel(); } break; case PANEL_5: if (validateInputQuestion5()) { panelsTag = PanelsTag.PANEL_6; switchQuestionPanel(); } break; case PANEL_6: if (generalValidateInputOfEachElem()) { panelsTag = PanelsTag.PANEL_7; switchQuestionPanel(); } break; case PANEL_7: if (generalValidateInputOfEachElem()) { panelsTag = PanelsTag.PANEL_8; switchQuestionPanel(); } break; case PANEL_8: if (generalValidateInputOfEachElem()) { panelsTag = PanelsTag.PANEL_9; switchQuestionPanel(); } break; case PANEL_9: if (validateInputQuestion9()) { System.out.println("*** Congratulations ***"); } break; } System.out.println("jtfInputData.size() = " + jtfInputData.size()); } }); } /** * Validate entered data which chemical elements involved. */ private boolean generalValidateInputOfEachElem() { int correctInputDataCounter = 0; for (JTextField jtf : jtfInputData) { String res = controller.validateInputData(jtf, InputDataController.ValidatorVariant.IS_NUMBER); if (!res.equals(InputDataController.SUCCESS_VALIDATE)) { jlStatusMsg.setText(res); return false; } correctInputDataCounter++; if (correctInputDataCounter == jtfInputData.size()) { jlStatusMsg.setText(""); } } return true; } /** * Validate entered data for question 2.1, 2.2, 2.3 */ private boolean validateInputQuestion2() { String res = controller.validateInputData(jtfEntLqAll, InputDataController.ValidatorVariant.IS_NUMBER); if (!res.equals(InputDataController.SUCCESS_VALIDATE)) { jlStatusMsg.setText(res); return false; } res = controller.validateInputData(jtfEntVaporization, InputDataController.ValidatorVariant.IS_NUMBER); if (!res.equals(InputDataController.SUCCESS_VALIDATE)) { jlStatusMsg.setText(res); return false; } res = controller.validateInputData(jtfEntVapour, InputDataController.ValidatorVariant.IS_NUMBER); if (!res.equals(InputDataController.SUCCESS_VALIDATE)) { jlStatusMsg.setText(res); return false; } jlStatusMsg.setText(""); return true; } /** * Validate entered data for question 5 */ private boolean validateInputQuestion5(){ String res = controller.validateInputData(jtfVapPresOverAlloy, InputDataController.ValidatorVariant.IS_NUMBER); if (!res.equals(InputDataController.SUCCESS_VALIDATE)) { jlStatusMsg.setText(res); return false; } jlStatusMsg.setText(""); return true; } /** * Validate entered data for question 9 */ private boolean validateInputQuestion9(){ if (jtfDecrMoltenMetalDueVap == null) System.out.println("jtfDecrMoltenMetalDueVap is null !"); else System.out.println("jtfDecrMoltenMetalDueVap is NOT null"); String res = controller.validateInputData(jtfDecrMoltenMetalDueVap, InputDataController.ValidatorVariant.IS_NUMBER); if (!res.equals(InputDataController.SUCCESS_VALIDATE)) { jlStatusMsg.setText(res); return false; } jlStatusMsg.setText(""); return true; } private void addRowsInputDataToPanel(JPanel jpRows, List<JTextField> jtfList, GeneralElementStage1 el) { JLabel jlName = new JLabel(el.toString() + " : "); JTextField jtfVal = new JTextField(); jtfVal.setColumns(4); jtfVal.setName(el.toString()); jtfList.add(jtfVal); JLabel jlPercent = new JLabel(PERCENT_SYM); JPanel jpItems = new JPanel(); jpItems.add(jlName); jpItems.add(jtfVal); jpItems.add(jlPercent); jpRows.add(jpItems); } // private void checkAnswer() { // System.out.println(jtfAnswer2.getText()); // if (jtfAnswer1.getText().equals("5") && panelsTag == PanelsTag.PANEL_1) { // panelsTag = PanelsTag.PANEL_2; // // } else if (jtfAnswer2.getText().equals("4") && panelsTag == PanelsTag.PANEL_2) { // panelsTag = PanelsTag.PANEL_3; // System.out.println("correct answer 2"); // // } else if (jtfAnswer3.getText().equals("8") && panelsTag == PanelsTag.PANEL_3){ // panelsTag = PanelsTag.PANEL_4; // } // else { // JOptionPane.showMessageDialog(rootPane, "Не правильный ответ", "Info", JOptionPane.INFORMATION_MESSAGE); // } // switchQuestionPanel(); // } private void switchQuestionPanel() { switch (panelsTag) { case PANEL_1: buildQuestion1Panel(); jpMain.add(jpQuestion1, BorderLayout.CENTER); break; case PANEL_2: buildQuestion2Panel(); jpMain.remove(jpQuestion1); jpMain.add(jpQuestion2, BorderLayout.CENTER); break; case PANEL_3: buildQuestion3Panel(); jpMain.remove(jpQuestion2); jpMain.add(jpQuestion3, BorderLayout.CENTER); break; case PANEL_4: buildQuestion4Panel(); jpMain.remove(jpQuestion3); jpMain.add(jpQuestion4, BorderLayout.CENTER); break; case PANEL_5: buildQuestion5Panel(); jpMain.remove(jpQuestion4); jpMain.add(jpQuestion5, BorderLayout.CENTER); break; case PANEL_6: buildQuestion6Panel(); jpMain.remove(jpQuestion5); jpMain.add(jpQuestion6, BorderLayout.CENTER); break; case PANEL_7: buildQuestion7Panel(); jpMain.remove(jpQuestion6); jpMain.add(jpQuestion7, BorderLayout.CENTER); break; case PANEL_8: buildQuestion8Panel(); jpMain.remove(jpQuestion7); jpMain.add(jpQuestion8, BorderLayout.CENTER); break; case PANEL_9: buildQuestion9Panel(); jpMain.remove(jpQuestion8); jpMain.add(jpQuestion9, BorderLayout.CENTER); break; } // showOtherViewElements(); revalidate(); repaint(); pack(); System.out.println("revalidate repaint pack "); } private void buildQuestion1Panel() { jpQuestion1.setLayout(new BoxLayout(jpQuestion1, BoxLayout.Y_AXIS)); JPanel jpRows = new JPanel(); jpRows.setLayout(new BoxLayout(jpRows, BoxLayout.Y_AXIS)); for(GeneralElementStage1 el : controller.receiveAllElementsStage1(InputDataController.AccessElementsStage1.TASK)){ addRowsInputDataToPanel(jpRows, jtfInputData, el); } jpQuestion1.add(jpRows); } private void buildQuestion2Panel() { jpQuestion2.setLayout(new BoxLayout(jpQuestion2, BoxLayout.Y_AXIS)); JPanel jpRowQ2p1 = new JPanel(); JPanel jpRowQ2p2 = new JPanel(); JPanel jpRowQ2p3 = new JPanel(); jtfEntLqAll.setName(ENT_LQ_ALLOY_SYM); jtfEntVaporization.setName(ENT_VAPORIZATION_SYM); jtfEntVapour.setName(ENT_VAPOUR_SYM); jpRowQ2p1.add(jlEntLqAll); jpRowQ2p1.add(jtfEntLqAll); jpRowQ2p1.add(jlEntLqAllUnits); jpRowQ2p2.add(jlEntVaporization); jpRowQ2p2.add(jtfEntVaporization); jpRowQ2p2.add(jlEntVaporizationUnits); jpRowQ2p3.add(jlEntVapour); jpRowQ2p3.add(jtfEntVapour); jpRowQ2p3.add(jlEntVapourUnits); jtfEntLqAll.setColumns(4); jtfEntVaporization.setColumns(4); jtfEntVapour.setColumns(4); jpQuestion2.add(jpRowQ2p1); jpQuestion2.add(jpRowQ2p2); jpQuestion2.add(jpRowQ2p3); } private void buildQuestion3Panel() { jpQuestion3.setLayout(new BoxLayout(jpQuestion3, BoxLayout.Y_AXIS)); JPanel jpRowsQ3 = new JPanel(); jpRowsQ3.setLayout(new BoxLayout(jpRowsQ3, BoxLayout.Y_AXIS)); for(GeneralElementStage1 el : controller.receiveAllElementsStage1(InputDataController.AccessElementsStage1.TASK)){ addRowsInputDataToPanel(jpRowsQ3, jtfInputData, el); } jpQuestion3.add(jpRowsQ3); } private void buildQuestion4Panel(){ jpQuestion4.setLayout(new BoxLayout(jpQuestion4, BoxLayout.Y_AXIS)); JPanel jpRowsQ4 = new JPanel(); jpRowsQ4.setLayout(new BoxLayout(jpRowsQ4, BoxLayout.Y_AXIS)); for(GeneralElementStage1 el : controller.receiveAllElementsStage1(InputDataController.AccessElementsStage1.TASK)){ addRowsInputDataToPanel(jpRowsQ4, jtfInputData, el); } jpQuestion4.add(jpRowsQ4); } private void buildQuestion5Panel(){ jpQuestion5.setLayout(new BoxLayout(jpQuestion5, BoxLayout.Y_AXIS)); JPanel jpRowQ5 = new JPanel(); jtfVapPresOverAlloy.setName("P<sup>p</sup>"); jpRowQ5.add(jlVapPresOverAlloy); jpRowQ5.add(jtfVapPresOverAlloy); jpRowQ5.add(jlVapPresOverAlloyUnits); jtfVapPresOverAlloy.setColumns(4); jpQuestion5.add(jpRowQ5); } private void buildQuestion6Panel(){ jpQuestion6.setLayout(new BoxLayout(jpQuestion6, BoxLayout.Y_AXIS)); JPanel jpRowsQ6 = new JPanel(); jpRowsQ6.setLayout(new BoxLayout(jpRowsQ6, BoxLayout.Y_AXIS)); for(GeneralElementStage1 el : controller.receiveAllElementsStage1(InputDataController.AccessElementsStage1.TASK)){ addRowsInputDataToPanel(jpRowsQ6, jtfInputData, el); } jpQuestion6.add(jpRowsQ6); } private void buildQuestion7Panel(){ jpQuestion7.setLayout(new BoxLayout(jpQuestion7, BoxLayout.Y_AXIS)); JPanel jpRowsQ7 = new JPanel(); jpRowsQ7.setLayout(new BoxLayout(jpRowsQ7, BoxLayout.Y_AXIS)); for(GeneralElementStage1 el : controller.receiveAllElementsStage1(InputDataController.AccessElementsStage1.TASK)){ addRowsInputDataToPanel(jpRowsQ7, jtfInputData, el); } jpQuestion7.add(jpRowsQ7); } private void buildQuestion8Panel(){ jpQuestion8.setLayout(new BoxLayout(jpQuestion8, BoxLayout.Y_AXIS)); JPanel jpRowsQ8 = new JPanel(); jpRowsQ8.setLayout(new BoxLayout(jpRowsQ8, BoxLayout.Y_AXIS)); for(GeneralElementStage1 el : controller.receiveAllElementsStage1(InputDataController.AccessElementsStage1.TASK)){ addRowsInputDataToPanel(jpRowsQ8, jtfInputData, el); } jpQuestion8.add(jpRowsQ8); } private void buildQuestion9Panel(){ jpQuestion9.setLayout(new BoxLayout(jpQuestion9, BoxLayout.Y_AXIS)); JPanel jpRowsQ9 = new JPanel(); jtfDecrMoltenMetalDueVap.setName("&Delta;<i>v</i><sup>m</sup>"); jpRowsQ9.add(jlDecrMoltenMetalDueVap); jpRowsQ9.add(jtfDecrMoltenMetalDueVap); jpRowsQ9.add(jlDecrMoltenMetalDueVapUnits); jtfDecrMoltenMetalDueVap.setColumns(4); jpQuestion9.add(jpRowsQ9); } private enum PanelsTag { PANEL_1, PANEL_2, PANEL_3, PANEL_4, PANEL_5, PANEL_6, PANEL_7, PANEL_8, PANEL_9 } // private void showOtherViewElements() { // jpMain.add(jpStatusAndDirection, BorderLayout.PAGE_END); // } }
src/main/java/ui/Stage1QuestionFrame.java
package ui; import controller.InputDataController; import controller.Stage1QuestionFrameController; import domain.User; import stage1.elements.GeneralElementStage1; import javax.swing.*; import javax.swing.border.EtchedBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; /** * */ public class Stage1QuestionFrame extends JFrame { private static final String ENT_LQ_ALLOY_SYM = "H<sub>L</sub><sup>0</sup>"; private static final String ENT_VAPORIZATION_SYM = "&Delta;H<sub>кип</sub>"; private static final String ENT_VAPOUR_SYM = "H<sub>g</sub>"; private static final String PERCENT_SYM = "%"; private static final String KJOULE_SYM = "кДж/моль"; private JPanel jpMain = new JPanel(); private JPanel jpTitle = new JPanel(); private JPanel jpQuestion1 = new JPanel(); private JPanel jpQuestion2 = new JPanel(); private JPanel jpQuestion3 = new JPanel(); private JPanel jpQuestion4 = new JPanel(); private JPanel jpQuestion5 = new JPanel(); private JPanel jpQuestion6 = new JPanel(); private JPanel jpQuestion7 = new JPanel(); private JPanel jpQuestion8 = new JPanel(); private JPanel jpQuestion9 = new JPanel(); private JPanel jpStatusAndDirection = new JPanel(); // Elements for question 2 // 2.1 Расчет энтальпии жидкого сплава (кДж/моль) Enthalpy liquid alloy private JLabel jlEntLqAll = new JLabel("<html>Расчет энтальпии жидкого сплава: " + ENT_LQ_ALLOY_SYM + "</html>"); private JTextField jtfEntLqAll = new JTextField(); private JLabel jlEntLqAllUnits = new JLabel(KJOULE_SYM); // 2.2 Расчет энтальпии испарения (кДж/моль) Enthalpy vaporization private JLabel jlEntVaporization = new JLabel("<html>Расчет энтальпии испарения: " + ENT_VAPORIZATION_SYM + "</html>"); private JTextField jtfEntVaporization = new JTextField(); private JLabel jlEntVaporizationUnits = new JLabel(KJOULE_SYM); // 2.3 Энтальпия пара для сплава (кДж/моль) Enthalpy vapour private JLabel jlEntVapour = new JLabel("<html>Расчет энтальпии пара для сплава: " + ENT_VAPOUR_SYM + " </html>"); private JTextField jtfEntVapour = new JTextField(); private JLabel jlEntVapourUnits = new JLabel(KJOULE_SYM); // Elements for question 5 private JLabel jlVapPresOverAlloy = new JLabel("<html>Давление пара над сплавом P<sup>p</sup>: </html>"); private JTextField jtfVapPresOverAlloy = new JTextField(); private JLabel jlVapPresOverAlloyUnits = new JLabel(" Па"); // Elements for question 9 private JLabel jlDecrMoltenMetalDueVap = new JLabel("<html>Уменьшение массы расплавленного металла за счет " + "испарения &Delta;<i>v</i><sub>m</sub> : </html>"); private JTextField jtfDecrMoltenMetalDueVap = new JTextField(); private JLabel jlDecrMoltenMetalDueVapUnits = new JLabel(" гр/сек"); private JButton jBtnExit = new JButton("Выход"); private JButton jBtnNext = new JButton("Далее >>>"); private JLabel jlUserFirstName = new JLabel(); // Имя private JLabel jlUserMiddleName = new JLabel(); // Отчество private JLabel jlUserLastName = new JLabel(); // Фамилия private JLabel jlStatusMsg = new JLabel("Правильных ответов: "); private PanelsTag panelsTag; private Stage1QuestionFrameController controller; private java.util.List<JTextField> jtfInputData = new ArrayList<>(); //for validate user input data only public Stage1QuestionFrame(User user) { super("Stage 1, question n"); controller = new Stage1QuestionFrameController(); jpQuestion1.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "Вопрос 1" )); jpQuestion2.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "Вопрос 2" )); jpQuestion3.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "Вопрос 3" )); jpQuestion4.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "Вопрос 4" )); jpQuestion5.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "Вопрос 5" )); jpQuestion6.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "Вопрос 6" )); jpQuestion7.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "Вопрос 7" )); jpQuestion8.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "Вопрос 8" )); jpQuestion9.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "Вопрос 9" )); jpQuestion1.add(new JLabel("Мольная доля всех элементов сплава (%): ")); jpQuestion2.add(new JLabel("Энтальпия жидкого сплава, энтальпия испарения, энтальпия пара (кДж/моль): ")); //2.1, 2.2, 2.3 jpQuestion3.add(new JLabel("Давление пара чистых компонентов (Па): ")); jpQuestion4.add(new JLabel("Парциальное давление компонент над сплавом (Па): ")); jpQuestion5.add(new JLabel("Давление пара над сплавом (Па): ")); jpQuestion6.add(new JLabel("Мольная доля каждого компонента в паре (%): ")); jpQuestion7.add(new JLabel("Весовая доля каждого компонента в паре (%): ")); jpQuestion8.add(new JLabel("Скорость испарения из сварочной ванны каждого элемента (гр/сек): ")); jpQuestion9.add(new JLabel("Скорость уменьшения массы расплавленного металла за счет испарения (гр/сек): ")); jpTitle.add(new JLabel("Задача 1. Расчет процессов испарения металлов при сварке плавлением")); jpTitle.setLayout(new FlowLayout(FlowLayout.CENTER)); jpMain.setLayout(new BorderLayout()); jpMain.add(jpTitle, BorderLayout.PAGE_START); // TODO: 26.05.17 May be remove all elements before load next panel from jpRows // Settings for status and directions panel jpStatusAndDirection.setLayout(new BoxLayout(jpStatusAndDirection, BoxLayout.Y_AXIS)); // add direction buttons JPanel jpDirBtns = new JPanel(new FlowLayout()); jBtnExit.setPreferredSize(new Dimension(100, 25)); jBtnNext.setPreferredSize(new Dimension(500, 25)); jpDirBtns.add(jBtnExit); jpDirBtns.add(jBtnNext); jpStatusAndDirection.add(jpDirBtns); // add JPanel jpStatAndDir = new JPanel(new FlowLayout(FlowLayout.CENTER)); jpStatAndDir.add(jlStatusMsg); jpStatusAndDirection.add(jpStatAndDir); // add FIO labels JPanel jpUserFIO = new JPanel(new FlowLayout()); jpUserFIO.add(jlUserLastName); // Ф jpUserFIO.add(jlUserFirstName); // И jpUserFIO.add(jlUserMiddleName); // О jpStatusAndDirection.add(jpUserFIO); jlUserFirstName.setText(user.getFirstName()); jlUserMiddleName.setText(user.getMiddleName()); jlUserLastName.setText(user.getLastName()); jlStatusMsg.setText(jlStatusMsg.getText() + "1/8"); // show question 1 panelsTag = PanelsTag.PANEL_1; switchQuestionPanel(); jpMain.add(jpStatusAndDirection, BorderLayout.PAGE_END); System.out.println("jtfInputData.size() = " + jtfInputData.size()); add(jpMain); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // setSize(500, 300); setLocation(200, 200); setVisible(true); pack(); // addComponentsListeners(); jBtnNext.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { switch (panelsTag) { case PANEL_1: if(generalValidateInputOfEachElem()) { panelsTag = PanelsTag.PANEL_2; switchQuestionPanel(); } break; case PANEL_2: if (validateInputQuestion2()) { panelsTag = PanelsTag.PANEL_3; switchQuestionPanel(); } break; case PANEL_3: if (generalValidateInputOfEachElem()) { panelsTag = PanelsTag.PANEL_4; switchQuestionPanel(); } break; case PANEL_4: if (generalValidateInputOfEachElem()) { panelsTag = PanelsTag.PANEL_5; switchQuestionPanel(); } break; case PANEL_5: if (validateInputQuestion5()) { panelsTag = PanelsTag.PANEL_6; switchQuestionPanel(); } break; case PANEL_6: if (generalValidateInputOfEachElem()) { panelsTag = PanelsTag.PANEL_7; switchQuestionPanel(); } break; case PANEL_7: if (generalValidateInputOfEachElem()) { panelsTag = PanelsTag.PANEL_8; switchQuestionPanel(); } break; case PANEL_8: if (generalValidateInputOfEachElem()) { panelsTag = PanelsTag.PANEL_9; switchQuestionPanel(); } break; case PANEL_9: if (validateInputQuestion9()) { System.out.println("*** Congratulations ***"); } break; } System.out.println("jtfInputData.size() = " + jtfInputData.size()); } }); } /** * Validate entered data which chemical elements involved. */ private boolean generalValidateInputOfEachElem() { int correctInputDataCounter = 0; for (JTextField jtf : jtfInputData) { String res = controller.validateInputData(jtf, InputDataController.ValidatorVariant.IS_NUMBER); if (!res.equals(InputDataController.SUCCESS_VALIDATE)) { jlStatusMsg.setText(res); return false; } correctInputDataCounter++; if (correctInputDataCounter == jtfInputData.size()) { jlStatusMsg.setText(""); } } return true; } /** * Validate entered data for question 2.1, 2.2, 2.3 */ private boolean validateInputQuestion2() { String res = controller.validateInputData(jtfEntLqAll, InputDataController.ValidatorVariant.IS_NUMBER); if (!res.equals(InputDataController.SUCCESS_VALIDATE)) { jlStatusMsg.setText(res); return false; } res = controller.validateInputData(jtfEntVaporization, InputDataController.ValidatorVariant.IS_NUMBER); if (!res.equals(InputDataController.SUCCESS_VALIDATE)) { jlStatusMsg.setText(res); return false; } res = controller.validateInputData(jtfEntVapour, InputDataController.ValidatorVariant.IS_NUMBER); if (!res.equals(InputDataController.SUCCESS_VALIDATE)) { jlStatusMsg.setText(res); return false; } jlStatusMsg.setText(""); return true; } /** * Validate entered data for question 5 */ private boolean validateInputQuestion5(){ String res = controller.validateInputData(jtfVapPresOverAlloy, InputDataController.ValidatorVariant.IS_NUMBER); if (!res.equals(InputDataController.SUCCESS_VALIDATE)) { jlStatusMsg.setText(res); return false; } jlStatusMsg.setText(""); return true; } /** * Validate entered data for question 9 */ private boolean validateInputQuestion9(){ if (jtfDecrMoltenMetalDueVap == null) System.out.println("jtfDecrMoltenMetalDueVap is null !"); else System.out.println("jtfDecrMoltenMetalDueVap is NOT null"); String res = controller.validateInputData(jtfDecrMoltenMetalDueVap, InputDataController.ValidatorVariant.IS_NUMBER); if (!res.equals(InputDataController.SUCCESS_VALIDATE)) { jlStatusMsg.setText(res); return false; } jlStatusMsg.setText(""); return true; } private void addRowsInputDataToPanel(JPanel jpRows, List<JTextField> jtfList, GeneralElementStage1 el) { JLabel jlName = new JLabel(el.toString() + " : "); JTextField jtfVal = new JTextField(); jtfVal.setColumns(4); jtfVal.setName(el.toString()); jtfList.add(jtfVal); JLabel jlPercent = new JLabel(PERCENT_SYM); JPanel jpItems = new JPanel(); jpItems.add(jlName); jpItems.add(jtfVal); jpItems.add(jlPercent); jpRows.add(jpItems); } // private void checkAnswer() { // System.out.println(jtfAnswer2.getText()); // if (jtfAnswer1.getText().equals("5") && panelsTag == PanelsTag.PANEL_1) { // panelsTag = PanelsTag.PANEL_2; // // } else if (jtfAnswer2.getText().equals("4") && panelsTag == PanelsTag.PANEL_2) { // panelsTag = PanelsTag.PANEL_3; // System.out.println("correct answer 2"); // // } else if (jtfAnswer3.getText().equals("8") && panelsTag == PanelsTag.PANEL_3){ // panelsTag = PanelsTag.PANEL_4; // } // else { // JOptionPane.showMessageDialog(rootPane, "Не правильный ответ", "Info", JOptionPane.INFORMATION_MESSAGE); // } // switchQuestionPanel(); // } private void switchQuestionPanel() { switch (panelsTag) { case PANEL_1: buildQuestion1Panel(); jpMain.add(jpQuestion1, BorderLayout.CENTER); break; case PANEL_2: buildQuestion2Panel(); jpMain.remove(jpQuestion1); jpMain.add(jpQuestion2, BorderLayout.CENTER); break; case PANEL_3: buildQuestion3Panel(); jpMain.remove(jpQuestion2); jpMain.add(jpQuestion3, BorderLayout.CENTER); break; case PANEL_4: buildQuestion4Panel(); jpMain.remove(jpQuestion3); jpMain.add(jpQuestion4, BorderLayout.CENTER); break; case PANEL_5: buildQuestion5Panel(); jpMain.remove(jpQuestion4); jpMain.add(jpQuestion5, BorderLayout.CENTER); break; case PANEL_6: buildQuestion6Panel(); jpMain.remove(jpQuestion5); jpMain.add(jpQuestion6, BorderLayout.CENTER); break; case PANEL_7: buildQuestion7Panel(); jpMain.remove(jpQuestion6); jpMain.add(jpQuestion7, BorderLayout.CENTER); break; case PANEL_8: buildQuestion8Panel(); jpMain.remove(jpQuestion7); jpMain.add(jpQuestion8, BorderLayout.CENTER); break; case PANEL_9: buildQuestion9Panel(); jpMain.remove(jpQuestion8); jpMain.add(jpQuestion9, BorderLayout.CENTER); break; } // showOtherViewElements(); revalidate(); repaint(); pack(); System.out.println("revalidate repaint pack "); } private void buildQuestion1Panel() { jpQuestion1.setLayout(new BoxLayout(jpQuestion1, BoxLayout.Y_AXIS)); JPanel jpRows = new JPanel(); jpRows.setLayout(new BoxLayout(jpRows, BoxLayout.Y_AXIS)); for(GeneralElementStage1 el : controller.receiveAllElementsStage1(InputDataController.AccessElementsStage1.TASK)){ addRowsInputDataToPanel(jpRows, jtfInputData, el); } jpQuestion1.add(jpRows); } private void buildQuestion2Panel() { jpQuestion2.setLayout(new BoxLayout(jpQuestion2, BoxLayout.Y_AXIS)); JPanel jpRowQ2p1 = new JPanel(); JPanel jpRowQ2p2 = new JPanel(); JPanel jpRowQ2p3 = new JPanel(); jtfEntLqAll.setName(ENT_LQ_ALLOY_SYM); jtfEntVaporization.setName(ENT_VAPORIZATION_SYM); jtfEntVapour.setName(ENT_VAPOUR_SYM); jpRowQ2p1.add(jlEntLqAll); jpRowQ2p1.add(jtfEntLqAll); jpRowQ2p1.add(jlEntLqAllUnits); jpRowQ2p2.add(jlEntVaporization); jpRowQ2p2.add(jtfEntVaporization); jpRowQ2p2.add(jlEntVaporizationUnits); jpRowQ2p3.add(jlEntVapour); jpRowQ2p3.add(jtfEntVapour); jpRowQ2p3.add(jlEntVapourUnits); jtfEntLqAll.setColumns(4); jtfEntVaporization.setColumns(4); jtfEntVapour.setColumns(4); jpQuestion2.add(jpRowQ2p1); jpQuestion2.add(jpRowQ2p2); jpQuestion2.add(jpRowQ2p3); } private void buildQuestion3Panel() { jpQuestion3.setLayout(new BoxLayout(jpQuestion3, BoxLayout.Y_AXIS)); JPanel jpRowsQ3 = new JPanel(); jpRowsQ3.setLayout(new BoxLayout(jpRowsQ3, BoxLayout.Y_AXIS)); for(GeneralElementStage1 el : controller.receiveAllElementsStage1(InputDataController.AccessElementsStage1.TASK)){ addRowsInputDataToPanel(jpRowsQ3, jtfInputData, el); } jpQuestion3.add(jpRowsQ3); } private void buildQuestion4Panel(){ jpQuestion4.setLayout(new BoxLayout(jpQuestion4, BoxLayout.Y_AXIS)); JPanel jpRowsQ4 = new JPanel(); jpRowsQ4.setLayout(new BoxLayout(jpRowsQ4, BoxLayout.Y_AXIS)); for(GeneralElementStage1 el : controller.receiveAllElementsStage1(InputDataController.AccessElementsStage1.TASK)){ addRowsInputDataToPanel(jpRowsQ4, jtfInputData, el); } jpQuestion4.add(jpRowsQ4); } private void buildQuestion5Panel(){ jpQuestion5.setLayout(new BoxLayout(jpQuestion5, BoxLayout.Y_AXIS)); JPanel jpRowQ5 = new JPanel(); jtfVapPresOverAlloy.setName("P<sup>p</sup>"); jpRowQ5.add(jlVapPresOverAlloy); jpRowQ5.add(jtfVapPresOverAlloy); jpRowQ5.add(jlVapPresOverAlloyUnits); jtfVapPresOverAlloy.setColumns(4); jpQuestion5.add(jpRowQ5); } private void buildQuestion6Panel(){ jpQuestion6.setLayout(new BoxLayout(jpQuestion6, BoxLayout.Y_AXIS)); JPanel jpRowsQ6 = new JPanel(); jpRowsQ6.setLayout(new BoxLayout(jpRowsQ6, BoxLayout.Y_AXIS)); for(GeneralElementStage1 el : controller.receiveAllElementsStage1(InputDataController.AccessElementsStage1.TASK)){ addRowsInputDataToPanel(jpRowsQ6, jtfInputData, el); } jpQuestion6.add(jpRowsQ6); } private void buildQuestion7Panel(){ jpQuestion7.setLayout(new BoxLayout(jpQuestion7, BoxLayout.Y_AXIS)); JPanel jpRowsQ7 = new JPanel(); jpRowsQ7.setLayout(new BoxLayout(jpRowsQ7, BoxLayout.Y_AXIS)); for(GeneralElementStage1 el : controller.receiveAllElementsStage1(InputDataController.AccessElementsStage1.TASK)){ addRowsInputDataToPanel(jpRowsQ7, jtfInputData, el); } jpQuestion7.add(jpRowsQ7); } private void buildQuestion8Panel(){ jpQuestion8.setLayout(new BoxLayout(jpQuestion8, BoxLayout.Y_AXIS)); JPanel jpRowsQ8 = new JPanel(); jpRowsQ8.setLayout(new BoxLayout(jpRowsQ8, BoxLayout.Y_AXIS)); for(GeneralElementStage1 el : controller.receiveAllElementsStage1(InputDataController.AccessElementsStage1.TASK)){ addRowsInputDataToPanel(jpRowsQ8, jtfInputData, el); } jpQuestion8.add(jpRowsQ8); } private void buildQuestion9Panel(){ jpQuestion9.setLayout(new BoxLayout(jpQuestion9, BoxLayout.Y_AXIS)); JPanel jpRowsQ9 = new JPanel(); jtfDecrMoltenMetalDueVap.setName("&Delta;<i>v</i><sup>m</sup>"); jpRowsQ9.add(jlDecrMoltenMetalDueVap); jpRowsQ9.add(jtfDecrMoltenMetalDueVap); jpRowsQ9.add(jlDecrMoltenMetalDueVapUnits); jtfDecrMoltenMetalDueVap.setColumns(4); jpQuestion9.add(jpRowsQ9); } private enum PanelsTag { PANEL_1, PANEL_2, PANEL_3, PANEL_4, PANEL_5, PANEL_6, PANEL_7, PANEL_8, PANEL_9 } // private void showOtherViewElements() { // jpMain.add(jpStatusAndDirection, BorderLayout.PAGE_END); // } }
Refactoring - some units (for question 5 and 9) moved to const.
src/main/java/ui/Stage1QuestionFrame.java
Refactoring - some units (for question 5 and 9) moved to const.
<ide><path>rc/main/java/ui/Stage1QuestionFrame.java <ide> */ <ide> public class Stage1QuestionFrame extends JFrame { <ide> <add> private static final String PERCENT_SYM = "%"; <ide> private static final String ENT_LQ_ALLOY_SYM = "H<sub>L</sub><sup>0</sup>"; <ide> private static final String ENT_VAPORIZATION_SYM = "&Delta;H<sub>кип</sub>"; <ide> private static final String ENT_VAPOUR_SYM = "H<sub>g</sub>"; <del> private static final String PERCENT_SYM = "%"; <add> private static final String VAP_PRES_OVER_ALLOY_SYM = "P<sup>p</sup>"; <add> private static final String DECR_MOLTEN_METAL_DUE_VAP_SYM = "&Delta;<i>v</i><sub>m</sub>"; <ide> private static final String KJOULE_SYM = "кДж/моль"; <ide> private JPanel jpMain = new JPanel(); <ide> private JPanel jpTitle = new JPanel(); <ide> private JTextField jtfEntVapour = new JTextField(); <ide> private JLabel jlEntVapourUnits = new JLabel(KJOULE_SYM); <ide> // Elements for question 5 <del> private JLabel jlVapPresOverAlloy = new JLabel("<html>Давление пара над сплавом P<sup>p</sup>: </html>"); <add> private JLabel jlVapPresOverAlloy = new JLabel("<html>Давление пара над сплавом " + VAP_PRES_OVER_ALLOY_SYM + " : </html>"); <ide> private JTextField jtfVapPresOverAlloy = new JTextField(); <ide> private JLabel jlVapPresOverAlloyUnits = new JLabel(" Па"); <ide> // Elements for question 9 <ide> private JLabel jlDecrMoltenMetalDueVap = new JLabel("<html>Уменьшение массы расплавленного металла за счет " + <del> "испарения &Delta;<i>v</i><sub>m</sub> : </html>"); <add> "испарения " + DECR_MOLTEN_METAL_DUE_VAP_SYM + " : </html>"); <ide> private JTextField jtfDecrMoltenMetalDueVap = new JTextField(); <ide> private JLabel jlDecrMoltenMetalDueVapUnits = new JLabel(" гр/сек"); <ide>
Java
apache-2.0
error: pathspec 'plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/data/DBDAttributeReferrer.java' did not match any file(s) known to git
b1449247c04cc6178b1031793af7bd75fd0827a6
1
liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2019 Serge Rider ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.model.data; import org.jkiss.dbeaver.model.struct.DBSEntityAttribute; import org.jkiss.dbeaver.model.struct.DBSEntityAttributeRef; /** * DBDAttributeReferrer */ public class DBDAttributeReferrer implements DBSEntityAttributeRef { private final DBSEntityAttribute attribute; public DBDAttributeReferrer(DBSEntityAttribute attribute) { this.attribute = attribute; } @Override public DBSEntityAttribute getAttribute() { return attribute; } }
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/data/DBDAttributeReferrer.java
dbeaver/dbeaver#5452 Redis: zset keys support
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/data/DBDAttributeReferrer.java
dbeaver/dbeaver#5452 Redis: zset keys support
<ide><path>lugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/data/DBDAttributeReferrer.java <add>/* <add> * DBeaver - Universal Database Manager <add> * Copyright (C) 2010-2019 Serge Rider ([email protected]) <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.jkiss.dbeaver.model.data; <add> <add>import org.jkiss.dbeaver.model.struct.DBSEntityAttribute; <add>import org.jkiss.dbeaver.model.struct.DBSEntityAttributeRef; <add> <add>/** <add> * DBDAttributeReferrer <add> */ <add>public class DBDAttributeReferrer implements DBSEntityAttributeRef { <add> <add> private final DBSEntityAttribute attribute; <add> <add> public DBDAttributeReferrer(DBSEntityAttribute attribute) { <add> this.attribute = attribute; <add> } <add> <add> @Override <add> public DBSEntityAttribute getAttribute() { <add> return attribute; <add> } <add>}
Java
apache-2.0
8936a10da590d6d050ddd2632c8182c860d29315
0
AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,aosp-mirror/platform_frameworks_support,AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,aosp-mirror/platform_frameworks_support,aosp-mirror/platform_frameworks_support,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,aosp-mirror/platform_frameworks_support,androidx/androidx,androidx/androidx
/* * Copyright (C) 2007 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 android.support.media; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.Location; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.util.Pair; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.Closeable; import java.io.DataInput; import java.io.DataInputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * This is a class for reading and writing Exif tags in a JPEG file or a RAW image file. * <p> * Supported formats are: JPEG, DNG, CR2, NEF, NRW, ARW, RW2, ORF, PEF, SRW and RAF. * <p> * Attribute mutation is supported for JPEG image files. */ public class ExifInterface { private static final String TAG = "ExifInterface"; private static final boolean DEBUG = false; // The Exif tag names. See JEITA CP-3451C specifications (Exif 2.3) Section 3-8. // A. Tags related to image data structure /** * <p>The number of columns of image data, equal to the number of pixels per row. In JPEG * compressed data, this tag shall not be used because a JPEG marker is used instead of it.</p> * * <ul> * <li>Tag = 256</li> * <li>Type = Unsigned short or Unsigned long</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_IMAGE_WIDTH = "ImageWidth"; /** * <p>The number of rows of image data. In JPEG compressed data, this tag shall not be used * because a JPEG marker is used instead of it.</p> * * <ul> * <li>Tag = 257</li> * <li>Type = Unsigned short or Unsigned long</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_IMAGE_LENGTH = "ImageLength"; /** * <p>The number of bits per image component. In this standard each component of the image is * 8 bits, so the value for this tag is 8. See also {@link #TAG_SAMPLES_PER_PIXEL}. In JPEG * compressed data, this tag shall not be used because a JPEG marker is used instead of it.</p> * * <ul> * <li>Tag = 258</li> * <li>Type = Unsigned short</li> * <li>Count = 3</li> * <li>Default = {@link #BITS_PER_SAMPLE_RGB}</li> * </ul> */ public static final String TAG_BITS_PER_SAMPLE = "BitsPerSample"; /** * <p>The compression scheme used for the image data. When a primary image is JPEG compressed, * this designation is not necessary. So, this tag shall not be recorded. When thumbnails use * JPEG compression, this tag value is set to 6.</p> * * <ul> * <li>Tag = 259</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> * * @see #DATA_UNCOMPRESSED * @see #DATA_JPEG */ public static final String TAG_COMPRESSION = "Compression"; /** * <p>The pixel composition. In JPEG compressed data, this tag shall not be used because a JPEG * marker is used instead of it.</p> * * <ul> * <li>Tag = 262</li> * <li>Type = SHORT</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> * * @see #PHOTOMETRIC_INTERPRETATION_RGB * @see #PHOTOMETRIC_INTERPRETATION_YCBCR */ public static final String TAG_PHOTOMETRIC_INTERPRETATION = "PhotometricInterpretation"; /** * <p>The image orientation viewed in terms of rows and columns.</p> * * <ul> * <li>Tag = 274</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #ORIENTATION_NORMAL}</li> * </ul> * * @see #ORIENTATION_UNDEFINED * @see #ORIENTATION_NORMAL * @see #ORIENTATION_FLIP_HORIZONTAL * @see #ORIENTATION_ROTATE_180 * @see #ORIENTATION_FLIP_VERTICAL * @see #ORIENTATION_TRANSPOSE * @see #ORIENTATION_ROTATE_90 * @see #ORIENTATION_TRANSVERSE * @see #ORIENTATION_ROTATE_270 */ public static final String TAG_ORIENTATION = "Orientation"; /** * <p>The number of components per pixel. Since this standard applies to RGB and YCbCr images, * the value set for this tag is 3. In JPEG compressed data, this tag shall not be used because * a JPEG marker is used instead of it.</p> * * <ul> * <li>Tag = 277</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = 3</li> * </ul> */ public static final String TAG_SAMPLES_PER_PIXEL = "SamplesPerPixel"; /** * <p>Indicates whether pixel components are recorded in chunky or planar format. In JPEG * compressed data, this tag shall not be used because a JPEG marker is used instead of it. * If this field does not exist, the TIFF default, {@link #FORMAT_CHUNKY}, is assumed.</p> * * <ul> * <li>Tag = 284</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * </ul> * * @see #FORMAT_CHUNKY * @see #FORMAT_PLANAR */ public static final String TAG_PLANAR_CONFIGURATION = "PlanarConfiguration"; /** * <p>The sampling ratio of chrominance components in relation to the luminance component. * In JPEG compressed data a JPEG marker is used instead of this tag. So, this tag shall not * be recorded.</p> * * <ul> * <li>Tag = 530</li> * <li>Type = Unsigned short</li> * <li>Count = 2</li> * <ul> * <li>[2, 1] = YCbCr4:2:2</li> * <li>[2, 2] = YCbCr4:2:0</li> * <li>Other = reserved</li> * </ul> * </ul> */ public static final String TAG_Y_CB_CR_SUB_SAMPLING = "YCbCrSubSampling"; /** * <p>The position of chrominance components in relation to the luminance component. This field * is designated only for JPEG compressed data or uncompressed YCbCr data. The TIFF default is * {@link #Y_CB_CR_POSITIONING_CENTERED}; but when Y:Cb:Cr = 4:2:2 it is recommended in this * standard that {@link #Y_CB_CR_POSITIONING_CO_SITED} be used to record data, in order to * improve the image quality when viewed on TV systems. When this field does not exist, * the reader shall assume the TIFF default. In the case of Y:Cb:Cr = 4:2:0, the TIFF default * ({@link #Y_CB_CR_POSITIONING_CENTERED}) is recommended. If the Exif/DCF reader does not * have the capability of supporting both kinds of positioning, it shall follow the TIFF * default regardless of the value in this field. It is preferable that readers can support * both centered and co-sited positioning.</p> * * <ul> * <li>Tag = 531</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #Y_CB_CR_POSITIONING_CENTERED}</li> * </ul> * * @see #Y_CB_CR_POSITIONING_CENTERED * @see #Y_CB_CR_POSITIONING_CO_SITED */ public static final String TAG_Y_CB_CR_POSITIONING = "YCbCrPositioning"; /** * <p>The number of pixels per {@link #TAG_RESOLUTION_UNIT} in the {@link #TAG_IMAGE_WIDTH} * direction. When the image resolution is unknown, 72 [dpi] shall be designated.</p> * * <ul> * <li>Tag = 282</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = 72</li> * </ul> * * @see #TAG_Y_RESOLUTION * @see #TAG_RESOLUTION_UNIT */ public static final String TAG_X_RESOLUTION = "XResolution"; /** * <p>The number of pixels per {@link #TAG_RESOLUTION_UNIT} in the {@link #TAG_IMAGE_WIDTH} * direction. The same value as {@link #TAG_X_RESOLUTION} shall be designated.</p> * * <ul> * <li>Tag = 283</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = 72</li> * </ul> * * @see #TAG_X_RESOLUTION * @see #TAG_RESOLUTION_UNIT */ public static final String TAG_Y_RESOLUTION = "YResolution"; /** * <p>The unit for measuring {@link #TAG_X_RESOLUTION} and {@link #TAG_Y_RESOLUTION}. The same * unit is used for both {@link #TAG_X_RESOLUTION} and {@link #TAG_Y_RESOLUTION}. If the image * resolution is unknown, {@link #RESOLUTION_UNIT_INCHES} shall be designated.</p> * * <ul> * <li>Tag = 296</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #RESOLUTION_UNIT_INCHES}</li> * </ul> * * @see #RESOLUTION_UNIT_INCHES * @see #RESOLUTION_UNIT_CENTIMETERS * @see #TAG_X_RESOLUTION * @see #TAG_Y_RESOLUTION */ public static final String TAG_RESOLUTION_UNIT = "ResolutionUnit"; // B. Tags related to recording offset /** * <p>For each strip, the byte offset of that strip. It is recommended that this be selected * so the number of strip bytes does not exceed 64 KBytes.In the case of JPEG compressed data, * this designation is not necessary. So, this tag shall not be recorded.</p> * * <ul> * <li>Tag = 273</li> * <li>Type = Unsigned short or Unsigned long</li> * <li>Count = StripsPerImage (for {@link #FORMAT_CHUNKY}) * or {@link #TAG_SAMPLES_PER_PIXEL} * StripsPerImage * (for {@link #FORMAT_PLANAR})</li> * <li>Default = None</li> * </ul> * * <p>StripsPerImage = floor(({@link #TAG_IMAGE_LENGTH} + {@link #TAG_ROWS_PER_STRIP} - 1) * / {@link #TAG_ROWS_PER_STRIP})</p> * * @see #TAG_ROWS_PER_STRIP * @see #TAG_STRIP_BYTE_COUNTS */ public static final String TAG_STRIP_OFFSETS = "StripOffsets"; /** * <p>The number of rows per strip. This is the number of rows in the image of one strip when * an image is divided into strips. In the case of JPEG compressed data, this designation is * not necessary. So, this tag shall not be recorded.</p> * * <ul> * <li>Tag = 278</li> * <li>Type = Unsigned short or Unsigned long</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> * * @see #TAG_STRIP_OFFSETS * @see #TAG_STRIP_BYTE_COUNTS */ public static final String TAG_ROWS_PER_STRIP = "RowsPerStrip"; /** * <p>The total number of bytes in each strip. In the case of JPEG compressed data, this * designation is not necessary. So, this tag shall not be recorded.</p> * * <ul> * <li>Tag = 279</li> * <li>Type = Unsigned short or Unsigned long</li> * <li>Count = StripsPerImage (when using {@link #FORMAT_CHUNKY}) * or {@link #TAG_SAMPLES_PER_PIXEL} * StripsPerImage * (when using {@link #FORMAT_PLANAR})</li> * <li>Default = None</li> * </ul> * * <p>StripsPerImage = floor(({@link #TAG_IMAGE_LENGTH} + {@link #TAG_ROWS_PER_STRIP} - 1) * / {@link #TAG_ROWS_PER_STRIP})</p> */ public static final String TAG_STRIP_BYTE_COUNTS = "StripByteCounts"; /** * <p>The offset to the start byte (SOI) of JPEG compressed thumbnail data. This shall not be * used for primary image JPEG data.</p> * * <ul> * <li>Tag = 513</li> * <li>Type = Unsigned long</li> * <li>Default = None</li> * </ul> */ public static final String TAG_JPEG_INTERCHANGE_FORMAT = "JPEGInterchangeFormat"; /** * <p>The number of bytes of JPEG compressed thumbnail data. This is not used for primary image * JPEG data. JPEG thumbnails are not divided but are recorded as a continuous JPEG bitstream * from SOI to EOI. APPn and COM markers should not be recorded. Compressed thumbnails shall be * recorded in no more than 64 KBytes, including all other data to be recorded in APP1.</p> * * <ul> * <li>Tag = 514</li> * <li>Type = Unsigned long</li> * <li>Default = None</li> * </ul> */ public static final String TAG_JPEG_INTERCHANGE_FORMAT_LENGTH = "JPEGInterchangeFormatLength"; // C. Tags related to Image Data Characteristics /** * <p>A transfer function for the image, described in tabular style. Normally this tag need not * be used, since color space is specified in {@link #TAG_COLOR_SPACE}.</p> * * <ul> * <li>Tag = 301</li> * <li>Type = Unsigned short</li> * <li>Count = 3 * 256</li> * <li>Default = None</li> * </ul> */ public static final String TAG_TRANSFER_FUNCTION = "TransferFunction"; /** * <p>The chromaticity of the white point of the image. Normally this tag need not be used, * since color space is specified in {@link #TAG_COLOR_SPACE}.</p> * * <ul> * <li>Tag = 318</li> * <li>Type = Unsigned rational</li> * <li>Count = 2</li> * <li>Default = None</li> * </ul> */ public static final String TAG_WHITE_POINT = "WhitePoint"; /** * <p>The chromaticity of the three primary colors of the image. Normally this tag need not * be used, since color space is specified in {@link #TAG_COLOR_SPACE}.</p> * * <ul> * <li>Tag = 319</li> * <li>Type = Unsigned rational</li> * <li>Count = 6</li> * <li>Default = None</li> * </ul> */ public static final String TAG_PRIMARY_CHROMATICITIES = "PrimaryChromaticities"; /** * <p>The matrix coefficients for transformation from RGB to YCbCr image data. About * the default value, please refer to JEITA CP-3451C Spec, Annex D.</p> * * <ul> * <li>Tag = 529</li> * <li>Type = Unsigned rational</li> * <li>Count = 3</li> * </ul> */ public static final String TAG_Y_CB_CR_COEFFICIENTS = "YCbCrCoefficients"; /** * <p>The reference black point value and reference white point value. No defaults are given * in TIFF, but the values below are given as defaults here. The color space is declared in * a color space information tag, with the default being the value that gives the optimal image * characteristics Interoperability these conditions</p> * * <ul> * <li>Tag = 532</li> * <li>Type = RATIONAL</li> * <li>Count = 6</li> * <li>Default = [0, 255, 0, 255, 0, 255] (when {@link #TAG_PHOTOMETRIC_INTERPRETATION} * is {@link #PHOTOMETRIC_INTERPRETATION_RGB}) * or [0, 255, 0, 128, 0, 128] (when {@link #TAG_PHOTOMETRIC_INTERPRETATION} * is {@link #PHOTOMETRIC_INTERPRETATION_YCBCR})</li> * </ul> */ public static final String TAG_REFERENCE_BLACK_WHITE = "ReferenceBlackWhite"; // D. Other tags /** * <p>The date and time of image creation. In this standard it is the date and time the file * was changed. The format is "YYYY:MM:DD HH:MM:SS" with time shown in 24-hour format, and * the date and time separated by one blank character ({@code 0x20}). When the date and time * are unknown, all the character spaces except colons (":") should be filled with blank * characters, or else the Interoperability field should be filled with blank characters. * The character string length is 20 Bytes including NULL for termination. When the field is * left blank, it is treated as unknown.</p> * * <ul> * <li>Tag = 306</li> * <li>Type = String</li> * <li>Length = 19</li> * <li>Default = None</li> * </ul> */ public static final String TAG_DATETIME = "DateTime"; /** * <p>An ASCII string giving the title of the image. It is possible to be added a comment * such as "1988 company picnic" or the like. Two-byte character codes cannot be used. When * a 2-byte code is necessary, {@link #TAG_USER_COMMENT} is to be used.</p> * * <ul> * <li>Tag = 270</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_IMAGE_DESCRIPTION = "ImageDescription"; /** * <p>The manufacturer of the recording equipment. This is the manufacturer of the DSC, * scanner, video digitizer or other equipment that generated the image. When the field is left * blank, it is treated as unknown.</p> * * <ul> * <li>Tag = 271</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_MAKE = "Make"; /** * <p>The model name or model number of the equipment. This is the model name of number of * the DSC, scanner, video digitizer or other equipment that generated the image. When * the field is left blank, it is treated as unknown.</p> * * <ul> * <li>Tag = 272</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_MODEL = "Model"; /** * <p>This tag records the name and version of the software or firmware of the camera or image * input device used to generate the image. The detailed format is not specified, but it is * recommended that the example shown below be followed. When the field is left blank, it is * treated as unknown.</p> * * <p>Ex.) "Exif Software Version 1.00a".</p> * * <ul> * <li>Tag = 305</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_SOFTWARE = "Software"; /** * <p>This tag records the name of the camera owner, photographer or image creator. * The detailed format is not specified, but it is recommended that the information be written * as in the example below for ease of Interoperability. When the field is left blank, it is * treated as unknown.</p> * * <p>Ex.) "Camera owner, John Smith; Photographer, Michael Brown; Image creator, * Ken James"</p> * * <ul> * <li>Tag = 315</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_ARTIST = "Artist"; /** * <p>Copyright information. In this standard the tag is used to indicate both the photographer * and editor copyrights. It is the copyright notice of the person or organization claiming * rights to the image. The Interoperability copyright statement including date and rights * should be written in this field; e.g., "Copyright, John Smith, 19xx. All rights reserved." * In this standard the field records both the photographer and editor copyrights, with each * recorded in a separate part of the statement. When there is a clear distinction between * the photographer and editor copyrights, these are to be written in the order of photographer * followed by editor copyright, separated by NULL (in this case, since the statement also ends * with a NULL, there are two NULL codes) (see example 1). When only the photographer copyright * is given, it is terminated by one NULL code (see example 2). When only the editor copyright * is given, the photographer copyright part consists of one space followed by a terminating * NULL code, then the editor copyright is given (see example 3). When the field is left blank, * it is treated as unknown.</p> * * <p>Ex. 1) When both the photographer copyright and editor copyright are given. * <ul><li>Photographer copyright + NULL + editor copyright + NULL</li></ul></p> * <p>Ex. 2) When only the photographer copyright is given. * <ul><li>Photographer copyright + NULL</li></ul></p> * <p>Ex. 3) When only the editor copyright is given. * <ul><li>Space ({@code 0x20}) + NULL + editor copyright + NULL</li></ul></p> * * <ul> * <li>Tag = 315</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_COPYRIGHT = "Copyright"; // Exif IFD Attribute Information // A. Tags related to version /** * <p>The version of this standard supported. Nonexistence of this field is taken to mean * nonconformance to the standard. In according with conformance to this standard, this tag * shall be recorded like "0230” as 4-byte ASCII.</p> * * <ul> * <li>Tag = 36864</li> * <li>Type = Undefined</li> * <li>Length = 4</li> * <li>Default = "0230"</li> * </ul> */ public static final String TAG_EXIF_VERSION = "ExifVersion"; /** * <p>The Flashpix format version supported by a FPXR file. If the FPXR function supports * Flashpix format Ver. 1.0, this is indicated similarly to {@link #TAG_EXIF_VERSION} by * recording "0100" as 4-byte ASCII.</p> * * <ul> * <li>Tag = 40960</li> * <li>Type = Undefined</li> * <li>Length = 4</li> * <li>Default = "0100"</li> * </ul> */ public static final String TAG_FLASHPIX_VERSION = "FlashpixVersion"; // B. Tags related to image data characteristics /** * <p>The color space information tag is always recorded as the color space specifier. * Normally {@link #COLOR_SPACE_S_RGB} is used to define the color space based on the PC * monitor conditions and environment. If a color space other than {@link #COLOR_SPACE_S_RGB} * is used, {@link #COLOR_SPACE_UNCALIBRATED} is set. Image data recorded as * {@link #COLOR_SPACE_UNCALIBRATED} may be treated as {@link #COLOR_SPACE_S_RGB} when it is * converted to Flashpix.</p> * * <ul> * <li>Tag = 40961</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * </ul> * * @see #COLOR_SPACE_S_RGB * @see #COLOR_SPACE_UNCALIBRATED */ public static final String TAG_COLOR_SPACE = "ColorSpace"; /** * <p>Indicates the value of coefficient gamma. The formula of transfer function used for image * reproduction is expressed as follows.</p> * * <p>(Reproduced value) = (Input value) ^ gamma</p> * * <p>Both reproduced value and input value indicate normalized value, whose minimum value is * 0 and maximum value is 1.</p> * * <ul> * <li>Tag = 42240</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GAMMA = "Gamma"; // C. Tags related to image configuration /** * <p>Information specific to compressed data. When a compressed file is recorded, the valid * width of the meaningful image shall be recorded in this tag, whether or not there is padding * data or a restart marker. This tag shall not exist in an uncompressed file.</p> * * <ul> * <li>Tag = 40962</li> * <li>Type = Unsigned short or Unsigned long</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_PIXEL_X_DIMENSION = "PixelXDimension"; /** * <p>Information specific to compressed data. When a compressed file is recorded, the valid * height of the meaningful image shall be recorded in this tag, whether or not there is * padding data or a restart marker. This tag shall not exist in an uncompressed file. * Since data padding is unnecessary in the vertical direction, the number of lines recorded * in this valid image height tag will in fact be the same as that recorded in the SOF.</p> * * <ul> * <li>Tag = 40963</li> * <li>Type = Unsigned short or Unsigned long</li> * <li>Count = 1</li> * </ul> */ public static final String TAG_PIXEL_Y_DIMENSION = "PixelYDimension"; /** * <p>Information specific to compressed data. The channels of each component are arranged * in order from the 1st component to the 4th. For uncompressed data the data arrangement is * given in the {@link #TAG_PHOTOMETRIC_INTERPRETATION}. However, since * {@link #TAG_PHOTOMETRIC_INTERPRETATION} can only express the order of Y, Cb and Cr, this tag * is provided for cases when compressed data uses components other than Y, Cb, and Cr and to * enable support of other sequences.</p> * * <ul> * <li>Tag = 37121</li> * <li>Type = Undefined</li> * <li>Length = 4</li> * <li>Default = 4 5 6 0 (if RGB uncompressed) or 1 2 3 0 (other cases)</li> * <ul> * <li>0 = does not exist</li> * <li>1 = Y</li> * <li>2 = Cb</li> * <li>3 = Cr</li> * <li>4 = R</li> * <li>5 = G</li> * <li>6 = B</li> * <li>other = reserved</li> * </ul> * </ul> */ public static final String TAG_COMPONENTS_CONFIGURATION = "ComponentsConfiguration"; /** * <p>Information specific to compressed data. The compression mode used for a compressed image * is indicated in unit bits per pixel.</p> * * <ul> * <li>Tag = 37122</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_COMPRESSED_BITS_PER_PIXEL = "CompressedBitsPerPixel"; // D. Tags related to user information /** * <p>A tag for manufacturers of Exif/DCF writers to record any desired information. * The contents are up to the manufacturer, but this tag shall not be used for any other than * its intended purpose.</p> * * <ul> * <li>Tag = 37500</li> * <li>Type = Undefined</li> * <li>Default = None</li> * </ul> */ public static final String TAG_MAKER_NOTE = "MakerNote"; /** * <p>A tag for Exif users to write keywords or comments on the image besides those in * {@link #TAG_IMAGE_DESCRIPTION}, and without the character code limitations of it.</p> * * <ul> * <li>Tag = 37510</li> * <li>Type = Undefined</li> * <li>Default = None</li> * </ul> */ public static final String TAG_USER_COMMENT = "UserComment"; // E. Tags related to related file information /** * <p>This tag is used to record the name of an audio file related to the image data. The only * relational information recorded here is the Exif audio file name and extension (an ASCII * string consisting of 8 characters + '.' + 3 characters). The path is not recorded.</p> * * <p>When using this tag, audio files shall be recorded in conformance to the Exif audio * format. Writers can also store the data such as Audio within APP2 as Flashpix extension * stream data. Audio files shall be recorded in conformance to the Exif audio format.</p> * * <ul> * <li>Tag = 40964</li> * <li>Type = String</li> * <li>Length = 12</li> * <li>Default = None</li> * </ul> */ public static final String TAG_RELATED_SOUND_FILE = "RelatedSoundFile"; // F. Tags related to date and time /** * <p>The date and time when the original image data was generated. For a DSC the date and time * the picture was taken are recorded. The format is "YYYY:MM:DD HH:MM:SS" with time shown in * 24-hour format, and the date and time separated by one blank character ({@code 0x20}). * When the date and time are unknown, all the character spaces except colons (":") should be * filled with blank characters, or else the Interoperability field should be filled with blank * characters. When the field is left blank, it is treated as unknown.</p> * * <ul> * <li>Tag = 36867</li> * <li>Type = String</li> * <li>Length = 19</li> * <li>Default = None</li> * </ul> */ public static final String TAG_DATETIME_ORIGINAL = "DateTimeOriginal"; /** * <p>The date and time when the image was stored as digital data. If, for example, an image * was captured by DSC and at the same time the file was recorded, then * {@link #TAG_DATETIME_ORIGINAL} and this tag will have the same contents. The format is * "YYYY:MM:DD HH:MM:SS" with time shown in 24-hour format, and the date and time separated by * one blank character ({@code 0x20}). When the date and time are unknown, all the character * spaces except colons (":")should be filled with blank characters, or else * the Interoperability field should be filled with blank characters. When the field is left * blank, it is treated as unknown.</p> * * <ul> * <li>Tag = 36868</li> * <li>Type = String</li> * <li>Length = 19</li> * <li>Default = None</li> * </ul> */ public static final String TAG_DATETIME_DIGITIZED = "DateTimeDigitized"; /** * <p>A tag used to record fractions of seconds for {@link #TAG_DATETIME}.</p> * * <ul> * <li>Tag = 37520</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_SUBSEC_TIME = "SubSecTime"; /** * <p>A tag used to record fractions of seconds for {@link #TAG_DATETIME_ORIGINAL}.</p> * * <ul> * <li>Tag = 37521</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_SUBSEC_TIME_ORIGINAL = "SubSecTimeOriginal"; /** * <p>A tag used to record fractions of seconds for {@link #TAG_DATETIME_DIGITIZED}.</p> * * <ul> * <li>Tag = 37522</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_SUBSEC_TIME_DIGITIZED = "SubSecTimeDigitized"; // G. Tags related to picture-taking condition /** * <p>Exposure time, given in seconds.</p> * * <ul> * <li>Tag = 33434</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_EXPOSURE_TIME = "ExposureTime"; /** * <p>The F number.</p> * * <ul> * <li>Tag = 33437</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_F_NUMBER = "FNumber"; /** * <p>TThe class of the program used by the camera to set exposure when the picture is taken. * The tag values are as follows.</p> * * <ul> * <li>Tag = 34850</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #EXPOSURE_PROGRAM_NOT_DEFINED}</li> * </ul> * * @see #EXPOSURE_PROGRAM_NOT_DEFINED * @see #EXPOSURE_PROGRAM_MANUAL * @see #EXPOSURE_PROGRAM_NORMAL * @see #EXPOSURE_PROGRAM_APERTURE_PRIORITY * @see #EXPOSURE_PROGRAM_SHUTTER_PRIORITY * @see #EXPOSURE_PROGRAM_CREATIVE * @see #EXPOSURE_PROGRAM_ACTION * @see #EXPOSURE_PROGRAM_PORTRAIT_MODE * @see #EXPOSURE_PROGRAM_LANDSCAPE_MODE */ public static final String TAG_EXPOSURE_PROGRAM = "ExposureProgram"; /** * <p>Indicates the spectral sensitivity of each channel of the camera used. The tag value is * an ASCII string compatible with the standard developed by the ASTM Technical committee.</p> * * <ul> * <li>Tag = 34852</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_SPECTRAL_SENSITIVITY = "SpectralSensitivity"; /** * @deprecated Use {@link #TAG_PHOTOGRAPHIC_SENSITIVITY} instead. * @see #TAG_PHOTOGRAPHIC_SENSITIVITY */ @Deprecated public static final String TAG_ISO_SPEED_RATINGS = "ISOSpeedRatings"; /** * <p>This tag indicates the sensitivity of the camera or input device when the image was shot. * More specifically, it indicates one of the following values that are parameters defined in * ISO 12232: standard output sensitivity (SOS), recommended exposure index (REI), or ISO * speed. Accordingly, if a tag corresponding to a parameter that is designated by * {@link #TAG_SENSITIVITY_TYPE} is recorded, the values of the tag and of this tag are * the same. However, if the value is 65535 or higher, the value of this tag shall be 65535. * When recording this tag, {@link #TAG_SENSITIVITY_TYPE} should also be recorded. In addition, * while “Count = Any”, only 1 count should be used when recording this tag.</p> * * <ul> * <li>Tag = 34855</li> * <li>Type = Unsigned short</li> * <li>Count = Any</li> * <li>Default = None</li> * </ul> */ public static final String TAG_PHOTOGRAPHIC_SENSITIVITY = "PhotographicSensitivity"; /** * <p>Indicates the Opto-Electric Conversion Function (OECF) specified in ISO 14524. OECF is * the relationship between the camera optical input and the image values.</p> * * <ul> * <li>Tag = 34856</li> * <li>Type = Undefined</li> * <li>Default = None</li> * </ul> */ public static final String TAG_OECF = "OECF"; /** * <p>This tag indicates which one of the parameters of ISO12232 is * {@link #TAG_PHOTOGRAPHIC_SENSITIVITY}. Although it is an optional tag, it should be recorded * when {@link #TAG_PHOTOGRAPHIC_SENSITIVITY} is recorded.</p> * * <ul> * <li>Tag = 34864</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> * * @see #SENSITIVITY_TYPE_UNKNOWN * @see #SENSITIVITY_TYPE_SOS * @see #SENSITIVITY_TYPE_REI * @see #SENSITIVITY_TYPE_ISO_SPEED * @see #SENSITIVITY_TYPE_SOS_AND_REI * @see #SENSITIVITY_TYPE_SOS_AND_ISO * @see #SENSITIVITY_TYPE_REI_AND_ISO * @see #SENSITIVITY_TYPE_SOS_AND_REI_AND_ISO */ public static final String TAG_SENSITIVITY_TYPE = "SensitivityType"; /** * <p>This tag indicates the standard output sensitivity value of a camera or input device * defined in ISO 12232. When recording this tag, {@link #TAG_PHOTOGRAPHIC_SENSITIVITY} and * {@link #TAG_SENSITIVITY_TYPE} shall also be recorded.</p> * * <ul> * <li>Tag = 34865</li> * <li>Type = Unsigned long</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_STANDARD_OUTPUT_SENSITIVITY = "StandardOutputSensitivity"; /** * <p>This tag indicates the recommended exposure index value of a camera or input device * defined in ISO 12232. When recording this tag, {@link #TAG_PHOTOGRAPHIC_SENSITIVITY} and * {@link #TAG_SENSITIVITY_TYPE} shall also be recorded.</p> * * <ul> * <li>Tag = 34866</li> * <li>Type = Unsigned long</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_RECOMMENDED_EXPOSURE_INDEX = "RecommendedExposureIndex"; /** * <p>This tag indicates the ISO speed value of a camera or input device that is defined in * ISO 12232. When recording this tag, {@link #TAG_PHOTOGRAPHIC_SENSITIVITY} and * {@link #TAG_SENSITIVITY_TYPE} shall also be recorded.</p> * * <ul> * <li>Tag = 34867</li> * <li>Type = Unsigned long</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_ISO_SPEED = "ISOSpeed"; /** * <p>This tag indicates the ISO speed latitude yyy value of a camera or input device that is * defined in ISO 12232. However, this tag shall not be recorded without {@link #TAG_ISO_SPEED} * and {@link #TAG_ISO_SPEED_LATITUDE_ZZZ}.</p> * * <ul> * <li>Tag = 34868</li> * <li>Type = Unsigned long</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_ISO_SPEED_LATITUDE_YYY = "ISOSpeedLatitudeyyy"; /** * <p>This tag indicates the ISO speed latitude zzz value of a camera or input device that is * defined in ISO 12232. However, this tag shall not be recorded without {@link #TAG_ISO_SPEED} * and {@link #TAG_ISO_SPEED_LATITUDE_YYY}.</p> * * <ul> * <li>Tag = 34869</li> * <li>Type = Unsigned long</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_ISO_SPEED_LATITUDE_ZZZ = "ISOSpeedLatitudezzz"; /** * <p>Shutter speed. The unit is the APEX setting.</p> * * <ul> * <li>Tag = 37377</li> * <li>Type = Signed rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_SHUTTER_SPEED_VALUE = "ShutterSpeedValue"; /** * <p>The lens aperture. The unit is the APEX value.</p> * * <ul> * <li>Tag = 37378</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_APERTURE_VALUE = "ApertureValue"; /** * <p>The value of brightness. The unit is the APEX value. Ordinarily it is given in the range * of -99.99 to 99.99. Note that if the numerator of the recorded value is 0xFFFFFFFF, * Unknown shall be indicated.</p> * * <ul> * <li>Tag = 37379</li> * <li>Type = Signed rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_BRIGHTNESS_VALUE = "BrightnessValue"; /** * <p>The exposure bias. The unit is the APEX value. Ordinarily it is given in the range of * -99.99 to 99.99.</p> * * <ul> * <li>Tag = 37380</li> * <li>Type = Signed rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_EXPOSURE_BIAS_VALUE = "ExposureBiasValue"; /** * <p>The smallest F number of the lens. The unit is the APEX value. Ordinarily it is given * in the range of 00.00 to 99.99, but it is not limited to this range.</p> * * <ul> * <li>Tag = 37381</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_MAX_APERTURE_VALUE = "MaxApertureValue"; /** * <p>The distance to the subject, given in meters. Note that if the numerator of the recorded * value is 0xFFFFFFFF, Infinity shall be indicated; and if the numerator is 0, Distance * unknown shall be indicated.</p> * * <ul> * <li>Tag = 37382</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_SUBJECT_DISTANCE = "SubjectDistance"; /** * <p>The metering mode.</p> * * <ul> * <li>Tag = 37383</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #METERING_MODE_UNKNOWN}</li> * </ul> * * @see #METERING_MODE_UNKNOWN * @see #METERING_MODE_AVERAGE * @see #METERING_MODE_CENTER_WEIGHT_AVERAGE * @see #METERING_MODE_SPOT * @see #METERING_MODE_MULTI_SPOT * @see #METERING_MODE_PATTERN * @see #METERING_MODE_PARTIAL * @see #METERING_MODE_OTHER */ public static final String TAG_METERING_MODE = "MeteringMode"; /** * <p>The kind of light source.</p> * * <ul> * <li>Tag = 37384</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #LIGHT_SOURCE_UNKNOWN}</li> * </ul> * * @see #LIGHT_SOURCE_UNKNOWN * @see #LIGHT_SOURCE_DAYLIGHT * @see #LIGHT_SOURCE_FLUORESCENT * @see #LIGHT_SOURCE_TUNGSTEN * @see #LIGHT_SOURCE_FLASH * @see #LIGHT_SOURCE_FINE_WEATHER * @see #LIGHT_SOURCE_CLOUDY_WEATHER * @see #LIGHT_SOURCE_SHADE * @see #LIGHT_SOURCE_DAYLIGHT_FLUORESCENT * @see #LIGHT_SOURCE_DAY_WHITE_FLUORESCENT * @see #LIGHT_SOURCE_COOL_WHITE_FLUORESCENT * @see #LIGHT_SOURCE_WHITE_FLUORESCENT * @see #LIGHT_SOURCE_WARM_WHITE_FLUORESCENT * @see #LIGHT_SOURCE_STANDARD_LIGHT_A * @see #LIGHT_SOURCE_STANDARD_LIGHT_B * @see #LIGHT_SOURCE_STANDARD_LIGHT_C * @see #LIGHT_SOURCE_D55 * @see #LIGHT_SOURCE_D65 * @see #LIGHT_SOURCE_D75 * @see #LIGHT_SOURCE_D50 * @see #LIGHT_SOURCE_ISO_STUDIO_TUNGSTEN * @see #LIGHT_SOURCE_OTHER */ public static final String TAG_LIGHT_SOURCE = "LightSource"; /** * <p>This tag indicates the status of flash when the image was shot. Bit 0 indicates the flash * firing status, bits 1 and 2 indicate the flash return status, bits 3 and 4 indicate * the flash mode, bit 5 indicates whether the flash function is present, and bit 6 indicates * "red eye" mode.</p> * * <ul> * <li>Tag = 37385</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * </ul> * * @see #FLAG_FLASH_FIRED * @see #FLAG_FLASH_RETURN_LIGHT_NOT_DETECTED * @see #FLAG_FLASH_RETURN_LIGHT_DETECTED * @see #FLAG_FLASH_MODE_COMPULSORY_FIRING * @see #FLAG_FLASH_MODE_COMPULSORY_SUPPRESSION * @see #FLAG_FLASH_MODE_AUTO * @see #FLAG_FLASH_NO_FLASH_FUNCTION * @see #FLAG_FLASH_RED_EYE_SUPPORTED */ public static final String TAG_FLASH = "Flash"; /** * <p>This tag indicates the location and area of the main subject in the overall scene.</p> * * <ul> * <li>Tag = 37396</li> * <li>Type = Unsigned short</li> * <li>Count = 2 or 3 or 4</li> * <li>Default = None</li> * </ul> * * <p>The subject location and area are defined by Count values as follows.</p> * * <ul> * <li>Count = 2 Indicates the location of the main subject as coordinates. The first value * is the X coordinate and the second is the Y coordinate.</li> * <li>Count = 3 The area of the main subject is given as a circle. The circular area is * expressed as center coordinates and diameter. The first value is * the center X coordinate, the second is the center Y coordinate, and * the third is the diameter.</li> * <li>Count = 4 The area of the main subject is given as a rectangle. The rectangular * area is expressed as center coordinates and area dimensions. The first * value is the center X coordinate, the second is the center Y coordinate, * the third is the width of the area, and the fourth is the height of * the area.</li> * </ul> * * <p>Note that the coordinate values, width, and height are expressed in relation to the upper * left as origin, prior to rotation processing as per {@link #TAG_ORIENTATION}.</p> */ public static final String TAG_SUBJECT_AREA = "SubjectArea"; /** * <p>The actual focal length of the lens, in mm. Conversion is not made to the focal length * of a 35mm film camera.</p> * * <ul> * <li>Tag = 37386</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_FOCAL_LENGTH = "FocalLength"; /** * <p>Indicates the strobe energy at the time the image is captured, as measured in Beam Candle * Power Seconds (BCPS).</p> * * <ul> * <li>Tag = 41483</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_FLASH_ENERGY = "FlashEnergy"; /** * <p>This tag records the camera or input device spatial frequency table and SFR values in * the direction of image width, image height, and diagonal direction, as specified in * ISO 12233.</p> * * <ul> * <li>Tag = 41484</li> * <li>Type = Undefined</li> * <li>Default = None</li> * </ul> */ public static final String TAG_SPATIAL_FREQUENCY_RESPONSE = "SpatialFrequencyResponse"; /** * <p>Indicates the number of pixels in the image width (X) direction per * {@link #TAG_FOCAL_PLANE_RESOLUTION_UNIT} on the camera focal plane.</p> * * <ul> * <li>Tag = 41486</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_FOCAL_PLANE_X_RESOLUTION = "FocalPlaneXResolution"; /** * <p>Indicates the number of pixels in the image height (Y) direction per * {@link #TAG_FOCAL_PLANE_RESOLUTION_UNIT} on the camera focal plane.</p> * * <ul> * <li>Tag = 41487</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_FOCAL_PLANE_Y_RESOLUTION = "FocalPlaneYResolution"; /** * <p>Indicates the unit for measuring {@link #TAG_FOCAL_PLANE_X_RESOLUTION} and * {@link #TAG_FOCAL_PLANE_Y_RESOLUTION}. This value is the same as * {@link #TAG_RESOLUTION_UNIT}.</p> * * <ul> * <li>Tag = 41488</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #RESOLUTION_UNIT_INCHES}</li> * </ul> * * @see #TAG_RESOLUTION_UNIT * @see #RESOLUTION_UNIT_INCHES * @see #RESOLUTION_UNIT_CENTIMETERS */ public static final String TAG_FOCAL_PLANE_RESOLUTION_UNIT = "FocalPlaneResolutionUnit"; /** * <p>Indicates the location of the main subject in the scene. The value of this tag represents * the pixel at the center of the main subject relative to the left edge, prior to rotation * processing as per {@link #TAG_ORIENTATION}. The first value indicates the X column number * and second indicates the Y row number. When a camera records the main subject location, * it is recommended that {@link #TAG_SUBJECT_AREA} be used instead of this tag.</p> * * <ul> * <li>Tag = 41492</li> * <li>Type = Unsigned short</li> * <li>Count = 2</li> * <li>Default = None</li> * </ul> */ public static final String TAG_SUBJECT_LOCATION = "SubjectLocation"; /** * <p>Indicates the exposure index selected on the camera or input device at the time the image * is captured.</p> * * <ul> * <li>Tag = 41493</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_EXPOSURE_INDEX = "ExposureIndex"; /** * <p>Indicates the image sensor type on the camera or input device.</p> * * <ul> * <li>Tag = 41495</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> * * @see #SENSOR_TYPE_NOT_DEFINED * @see #SENSOR_TYPE_ONE_CHIP * @see #SENSOR_TYPE_TWO_CHIP * @see #SENSOR_TYPE_THREE_CHIP * @see #SENSOR_TYPE_COLOR_SEQUENTIAL * @see #SENSOR_TYPE_TRILINEAR * @see #SENSOR_TYPE_COLOR_SEQUENTIAL_LINEAR */ public static final String TAG_SENSING_METHOD = "SensingMethod"; /** * <p>Indicates the image source. If a DSC recorded the image, this tag value always shall * be set to {@link #FILE_SOURCE_DSC}.</p> * * <ul> * <li>Tag = 41728</li> * <li>Type = Undefined</li> * <li>Length = 1</li> * <li>Default = {@link #FILE_SOURCE_DSC}</li> * </ul> * * @see #FILE_SOURCE_OTHER * @see #FILE_SOURCE_TRANSPARENT_SCANNER * @see #FILE_SOURCE_REFLEX_SCANNER * @see #FILE_SOURCE_DSC */ public static final String TAG_FILE_SOURCE = "FileSource"; /** * <p>Indicates the type of scene. If a DSC recorded the image, this tag value shall always * be set to {@link #SCENE_TYPE_DIRECTLY_PHOTOGRAPHED}.</p> * * <ul> * <li>Tag = 41729</li> * <li>Type = Undefined</li> * <li>Length = 1</li> * <li>Default = 1</li> * </ul> * * @see #SCENE_TYPE_DIRECTLY_PHOTOGRAPHED */ public static final String TAG_SCENE_TYPE = "SceneType"; /** * <p>Indicates the color filter array (CFA) geometric pattern of the image sensor when * a one-chip color area sensor is used. It does not apply to all sensing methods.</p> * * <ul> * <li>Tag = 41730</li> * <li>Type = Undefined</li> * <li>Default = None</li> * </ul> * * @see #TAG_SENSING_METHOD * @see #SENSOR_TYPE_ONE_CHIP */ public static final String TAG_CFA_PATTERN = "CFAPattern"; /** * <p>This tag indicates the use of special processing on image data, such as rendering geared * to output. When special processing is performed, the Exif/DCF reader is expected to disable * or minimize any further processing.</p> * * <ul> * <li>Tag = 41985</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #RENDERED_PROCESS_NORMAL}</li> * </ul> * * @see #RENDERED_PROCESS_NORMAL * @see #RENDERED_PROCESS_CUSTOM */ public static final String TAG_CUSTOM_RENDERED = "CustomRendered"; /** * <p>This tag indicates the exposure mode set when the image was shot. * In {@link #EXPOSURE_MODE_AUTO_BRACKET}, the camera shoots a series of frames of the same * scene at different exposure settings.</p> * * <ul> * <li>Tag = 41986</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> * * @see #EXPOSURE_MODE_AUTO * @see #EXPOSURE_MODE_MANUAL * @see #EXPOSURE_MODE_AUTO_BRACKET */ public static final String TAG_EXPOSURE_MODE = "ExposureMode"; /** * <p>This tag indicates the white balance mode set when the image was shot.</p> * * <ul> * <li>Tag = 41987</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> * * @see #WHITEBALANCE_AUTO * @see #WHITEBALANCE_MANUAL */ public static final String TAG_WHITE_BALANCE = "WhiteBalance"; /** * <p>This tag indicates the digital zoom ratio when the image was shot. If the numerator of * the recorded value is 0, this indicates that digital zoom was not used.</p> * * <ul> * <li>Tag = 41988</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_DIGITAL_ZOOM_RATIO = "DigitalZoomRatio"; /** * <p>This tag indicates the equivalent focal length assuming a 35mm film camera, in mm. * A value of 0 means the focal length is unknown. Note that this tag differs from * {@link #TAG_FOCAL_LENGTH}.</p> * * <ul> * <li>Tag = 41989</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_FOCAL_LENGTH_IN_35MM_FILM = "FocalLengthIn35mmFilm"; /** * <p>This tag indicates the type of scene that was shot. It may also be used to record * the mode in which the image was shot. Note that this differs from * {@link #TAG_SCENE_TYPE}.</p> * * <ul> * <li>Tag = 41990</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = 0</li> * </ul> * * @see #SCENE_CAPTURE_TYPE_STANDARD * @see #SCENE_CAPTURE_TYPE_LANDSCAPE * @see #SCENE_CAPTURE_TYPE_PORTRAIT * @see #SCENE_CAPTURE_TYPE_NIGHT */ public static final String TAG_SCENE_CAPTURE_TYPE = "SceneCaptureType"; /** * <p>This tag indicates the degree of overall image gain adjustment.</p> * * <ul> * <li>Tag = 41991</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> * * @see #GAIN_CONTROL_NONE * @see #GAIN_CONTROL_LOW_GAIN_UP * @see #GAIN_CONTROL_HIGH_GAIN_UP * @see #GAIN_CONTROL_LOW_GAIN_DOWN * @see #GAIN_CONTROL_HIGH_GAIN_DOWN */ public static final String TAG_GAIN_CONTROL = "GainControl"; /** * <p>This tag indicates the direction of contrast processing applied by the camera when * the image was shot.</p> * * <ul> * <li>Tag = 41992</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #CONTRAST_NORMAL}</li> * </ul> * * @see #CONTRAST_NORMAL * @see #CONTRAST_SOFT * @see #CONTRAST_HARD */ public static final String TAG_CONTRAST = "Contrast"; /** * <p>This tag indicates the direction of saturation processing applied by the camera when * the image was shot.</p> * * <ul> * <li>Tag = 41993</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #SATURATION_NORMAL}</li> * </ul> * * @see #SATURATION_NORMAL * @see #SATURATION_LOW * @see #SATURATION_HIGH */ public static final String TAG_SATURATION = "Saturation"; /** * <p>This tag indicates the direction of sharpness processing applied by the camera when * the image was shot.</p> * * <ul> * <li>Tag = 41994</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #SHARPNESS_NORMAL}</li> * </ul> * * @see #SHARPNESS_NORMAL * @see #SHARPNESS_SOFT * @see #SHARPNESS_HARD */ public static final String TAG_SHARPNESS = "Sharpness"; /** * <p>This tag indicates information on the picture-taking conditions of a particular camera * model. The tag is used only to indicate the picture-taking conditions in the Exif/DCF * reader.</p> * * <ul> * <li>Tag = 41995</li> * <li>Type = Undefined</li> * <li>Default = None</li> * </ul> */ public static final String TAG_DEVICE_SETTING_DESCRIPTION = "DeviceSettingDescription"; /** * <p>This tag indicates the distance to the subject.</p> * * <ul> * <li>Tag = 41996</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> * * @see #SUBJECT_DISTANCE_RANGE_UNKNOWN * @see #SUBJECT_DISTANCE_RANGE_MACRO * @see #SUBJECT_DISTANCE_RANGE_CLOSE_VIEW * @see #SUBJECT_DISTANCE_RANGE_DISTANT_VIEW */ public static final String TAG_SUBJECT_DISTANCE_RANGE = "SubjectDistanceRange"; // H. Other tags /** * <p>This tag indicates an identifier assigned uniquely to each image. It is recorded as * an ASCII string equivalent to hexadecimal notation and 128-bit fixed length.</p> * * <ul> * <li>Tag = 42016</li> * <li>Type = String</li> * <li>Length = 32</li> * <li>Default = None</li> * </ul> */ public static final String TAG_IMAGE_UNIQUE_ID = "ImageUniqueID"; /** * <p>This tag records the owner of a camera used in photography as an ASCII string.</p> * * <ul> * <li>Tag = 42032</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_CAMARA_OWNER_NAME = "CameraOwnerName"; /** * <p>This tag records the serial number of the body of the camera that was used in photography * as an ASCII string.</p> * * <ul> * <li>Tag = 42033</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_BODY_SERIAL_NUMBER = "BodySerialNumber"; /** * <p>This tag notes minimum focal length, maximum focal length, minimum F number in the * minimum focal length, and minimum F number in the maximum focal length, which are * specification information for the lens that was used in photography. When the minimum * F number is unknown, the notation is 0/0.</p> * * <ul> * <li>Tag = 42034</li> * <li>Type = Unsigned rational</li> * <li>Count = 4</li> * <li>Default = None</li> * <ul> * <li>Value 1 := Minimum focal length (unit: mm)</li> * <li>Value 2 : = Maximum focal length (unit: mm)</li> * <li>Value 3 : = Minimum F number in the minimum focal length</li> * <li>Value 4 : = Minimum F number in the maximum focal length</li> * </ul> * </ul> */ public static final String TAG_LENS_SPECIFICATION = "LensSpecification"; /** * <p>This tag records the lens manufacturer as an ASCII string.</p> * * <ul> * <li>Tag = 42035</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_LENS_MAKE = "LensMake"; /** * <p>This tag records the lens’s model name and model number as an ASCII string.</p> * * <ul> * <li>Tag = 42036</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_LENS_MODEL = "LensModel"; /** * <p>This tag records the serial number of the interchangeable lens that was used in * photography as an ASCII string.</p> * * <ul> * <li>Tag = 42037</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_LENS_SERIAL_NUMBER = "LensSerialNumber"; // GPS Attribute Information /** * <p>Indicates the version of GPS Info IFD. The version is given as 2.3.0.0. This tag is * mandatory when GPS-related tags are present. Note that this tag is written as a different * byte than {@link #TAG_EXIF_VERSION}.</p> * * <ul> * <li>Tag = 0</li> * <li>Type = Byte</li> * <li>Count = 4</li> * <li>Default = 2.3.0.0</li> * <ul> * <li>2300 = Version 2.3</li> * <li>Other = reserved</li> * </ul> * </ul> */ public static final String TAG_GPS_VERSION_ID = "GPSVersionID"; /** * <p>Indicates whether the latitude is north or south latitude.</p> * * <ul> * <li>Tag = 1</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = None</li> * </ul> * * @see #LATITUDE_NORTH * @see #LATITUDE_SOUTH */ public static final String TAG_GPS_LATITUDE_REF = "GPSLatitudeRef"; /** * <p>Indicates the latitude. The latitude is expressed as three RATIONAL values giving * the degrees, minutes, and seconds, respectively. If latitude is expressed as degrees, * minutes and seconds, a typical format would be dd/1,mm/1,ss/1. When degrees and minutes are * used and, for example, fractions of minutes are given up to two decimal places, the format * would be dd/1,mmmm/100,0/1.</p> * * <ul> * <li>Tag = 2</li> * <li>Type = Unsigned rational</li> * <li>Count = 3</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_LATITUDE = "GPSLatitude"; /** * <p>Indicates whether the longitude is east or west longitude.</p> * * <ul> * <li>Tag = 3</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = None</li> * </ul> * * @see #LONGITUDE_EAST * @see #LONGITUDE_WEST */ public static final String TAG_GPS_LONGITUDE_REF = "GPSLongitudeRef"; /** * <p>Indicates the longitude. The longitude is expressed as three RATIONAL values giving * the degrees, minutes, and seconds, respectively. If longitude is expressed as degrees, * minutes and seconds, a typical format would be ddd/1,mm/1,ss/1. When degrees and minutes * are used and, for example, fractions of minutes are given up to two decimal places, * the format would be ddd/1,mmmm/100,0/1.</p> * * <ul> * <li>Tag = 4</li> * <li>Type = Unsigned rational</li> * <li>Count = 3</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_LONGITUDE = "GPSLongitude"; /** * <p>Indicates the altitude used as the reference altitude. If the reference is sea level * and the altitude is above sea level, 0 is given. If the altitude is below sea level, * a value of 1 is given and the altitude is indicated as an absolute value in * {@link #TAG_GPS_ALTITUDE}.</p> * * <ul> * <li>Tag = 5</li> * <li>Type = Byte</li> * <li>Count = 1</li> * <li>Default = 0</li> * </ul> * * @see #ALTITUDE_ABOVE_SEA_LEVEL * @see #ALTITUDE_BELOW_SEA_LEVEL */ public static final String TAG_GPS_ALTITUDE_REF = "GPSAltitudeRef"; /** * <p>Indicates the altitude based on the reference in {@link #TAG_GPS_ALTITUDE_REF}. * The reference unit is meters.</p> * * <ul> * <li>Tag = 6</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_ALTITUDE = "GPSAltitude"; /** * <p>Indicates the time as UTC (Coordinated Universal Time). TimeStamp is expressed as three * unsigned rational values giving the hour, minute, and second.</p> * * <ul> * <li>Tag = 7</li> * <li>Type = Unsigned rational</li> * <li>Count = 3</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_TIMESTAMP = "GPSTimeStamp"; /** * <p>Indicates the GPS satellites used for measurements. This tag may be used to describe * the number of satellites, their ID number, angle of elevation, azimuth, SNR and other * information in ASCII notation. The format is not specified. If the GPS receiver is incapable * of taking measurements, value of the tag shall be set to {@code null}.</p> * * <ul> * <li>Tag = 8</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_SATELLITES = "GPSSatellites"; /** * <p>Indicates the status of the GPS receiver when the image is recorded. 'A' means * measurement is in progress, and 'V' means the measurement is interrupted.</p> * * <ul> * <li>Tag = 9</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = None</li> * </ul> * * @see #GPS_MEASUREMENT_IN_PROGRESS * @see #GPS_MEASUREMENT_INTERRUPTED */ public static final String TAG_GPS_STATUS = "GPSStatus"; /** * <p>Indicates the GPS measurement mode. Originally it was defined for GPS, but it may * be used for recording a measure mode to record the position information provided from * a mobile base station or wireless LAN as well as GPS.</p> * * <ul> * <li>Tag = 10</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = None</li> * </ul> * * @see #GPS_MEASUREMENT_2D * @see #GPS_MEASUREMENT_3D */ public static final String TAG_GPS_MEASURE_MODE = "GPSMeasureMode"; /** * <p>Indicates the GPS DOP (data degree of precision). An HDOP value is written during * two-dimensional measurement, and PDOP during three-dimensional measurement.</p> * * <ul> * <li>Tag = 11</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_DOP = "GPSDOP"; /** * <p>Indicates the unit used to express the GPS receiver speed of movement.</p> * * <ul> * <li>Tag = 12</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = {@link #GPS_SPEED_KILOMETERS_PER_HOUR}</li> * </ul> * * @see #GPS_SPEED_KILOMETERS_PER_HOUR * @see #GPS_SPEED_MILES_PER_HOUR * @see #GPS_SPEED_KNOTS */ public static final String TAG_GPS_SPEED_REF = "GPSSpeedRef"; /** * <p>Indicates the speed of GPS receiver movement.</p> * * <ul> * <li>Tag = 13</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_SPEED = "GPSSpeed"; /** * <p>Indicates the reference for giving the direction of GPS receiver movement.</p> * * <ul> * <li>Tag = 14</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = {@link #GPS_DIRECTION_TRUE}</li> * </ul> * * @see #GPS_DIRECTION_TRUE * @see #GPS_DIRECTION_MAGNETIC */ public static final String TAG_GPS_TRACK_REF = "GPSTrackRef"; /** * <p>Indicates the direction of GPS receiver movement. * The range of values is from 0.00 to 359.99.</p> * * <ul> * <li>Tag = 15</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_TRACK = "GPSTrack"; /** * <p>Indicates the reference for giving the direction of the image when it is captured.</p> * * <ul> * <li>Tag = 16</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = {@link #GPS_DIRECTION_TRUE}</li> * </ul> * * @see #GPS_DIRECTION_TRUE * @see #GPS_DIRECTION_MAGNETIC */ public static final String TAG_GPS_IMG_DIRECTION_REF = "GPSImgDirectionRef"; /** * <p>ndicates the direction of the image when it was captured. * The range of values is from 0.00 to 359.99.</p> * * <ul> * <li>Tag = 17</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_IMG_DIRECTION = "GPSImgDirection"; /** * <p>Indicates the geodetic survey data used by the GPS receiver. If the survey data is * restricted to Japan,the value of this tag is 'TOKYO' or 'WGS-84'. If a GPS Info tag is * recorded, it is strongly recommended that this tag be recorded.</p> * * <ul> * <li>Tag = 18</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_MAP_DATUM = "GPSMapDatum"; /** * <p>Indicates whether the latitude of the destination point is north or south latitude.</p> * * <ul> * <li>Tag = 19</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = None</li> * </ul> * * @see #LATITUDE_NORTH * @see #LATITUDE_SOUTH */ public static final String TAG_GPS_DEST_LATITUDE_REF = "GPSDestLatitudeRef"; /** * <p>Indicates the latitude of the destination point. The latitude is expressed as three * unsigned rational values giving the degrees, minutes, and seconds, respectively. * If latitude is expressed as degrees, minutes and seconds, a typical format would be * dd/1,mm/1,ss/1. When degrees and minutes are used and, for example, fractions of minutes * are given up to two decimal places, the format would be dd/1, mmmm/100, 0/1.</p> * * <ul> * <li>Tag = 20</li> * <li>Type = Unsigned rational</li> * <li>Count = 3</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_DEST_LATITUDE = "GPSDestLatitude"; /** * <p>Indicates whether the longitude of the destination point is east or west longitude.</p> * * <ul> * <li>Tag = 21</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = None</li> * </ul> * * @see #LONGITUDE_EAST * @see #LONGITUDE_WEST */ public static final String TAG_GPS_DEST_LONGITUDE_REF = "GPSDestLongitudeRef"; /** * <p>Indicates the longitude of the destination point. The longitude is expressed as three * unsigned rational values giving the degrees, minutes, and seconds, respectively. * If longitude is expressed as degrees, minutes and seconds, a typical format would be ddd/1, * mm/1, ss/1. When degrees and minutes are used and, for example, fractions of minutes are * given up to two decimal places, the format would be ddd/1, mmmm/100, 0/1.</p> * * <ul> * <li>Tag = 22</li> * <li>Type = Unsigned rational</li> * <li>Count = 3</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_DEST_LONGITUDE = "GPSDestLongitude"; /** * <p>Indicates the reference used for giving the bearing to the destination point.</p> * * <ul> * <li>Tag = 23</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = {@link #GPS_DIRECTION_TRUE}</li> * </ul> * * @see #GPS_DIRECTION_TRUE * @see #GPS_DIRECTION_MAGNETIC */ public static final String TAG_GPS_DEST_BEARING_REF = "GPSDestBearingRef"; /** * <p>Indicates the bearing to the destination point. * The range of values is from 0.00 to 359.99.</p> * * <ul> * <li>Tag = 24</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_DEST_BEARING = "GPSDestBearing"; /** * <p>Indicates the unit used to express the distance to the destination point.</p> * * <ul> * <li>Tag = 25</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = {@link #GPS_DISTANCE_KILOMETERS}</li> * </ul> * * @see #GPS_DISTANCE_KILOMETERS * @see #GPS_DISTANCE_MILES * @see #GPS_DISTANCE_NAUTICAL_MILES */ public static final String TAG_GPS_DEST_DISTANCE_REF = "GPSDestDistanceRef"; /** * <p>Indicates the distance to the destination point.</p> * * <ul> * <li>Tag = 26</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_DEST_DISTANCE = "GPSDestDistance"; /** * <p>A character string recording the name of the method used for location finding. * The first byte indicates the character code used, and this is followed by the name of * the method.</p> * * <ul> * <li>Tag = 27</li> * <li>Type = Undefined</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_PROCESSING_METHOD = "GPSProcessingMethod"; /** * <p>A character string recording the name of the GPS area. The first byte indicates * the character code used, and this is followed by the name of the GPS area.</p> * * <ul> * <li>Tag = 28</li> * <li>Type = Undefined</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_AREA_INFORMATION = "GPSAreaInformation"; /** * <p>A character string recording date and time information relative to UTC (Coordinated * Universal Time). The format is "YYYY:MM:DD".</p> * * <ul> * <li>Tag = 29</li> * <li>Type = String</li> * <li>Length = 10</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_DATESTAMP = "GPSDateStamp"; /** * <p>Indicates whether differential correction is applied to the GPS receiver.</p> * * <ul> * <li>Tag = 30</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> * * @see #GPS_MEASUREMENT_NO_DIFFERENTIAL * @see #GPS_MEASUREMENT_DIFFERENTIAL_CORRECTED */ public static final String TAG_GPS_DIFFERENTIAL = "GPSDifferential"; /** * <p>This tag indicates horizontal positioning errors in meters.</p> * * <ul> * <li>Tag = 31</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_H_POSITIONING_ERROR = "GPSHPositioningError"; // Interoperability IFD Attribute Information /** * <p>Indicates the identification of the Interoperability rule.</p> * * <ul> * <li>Tag = 1</li> * <li>Type = String</li> * <li>Length = 4</li> * <li>Default = None</li> * <ul> * <li>"R98" = Indicates a file conforming to R98 file specification of Recommended * Exif Interoperability Rules (Exif R 98) or to DCF basic file stipulated * by Design Rule for Camera File System.</li> * <li>"THM" = Indicates a file conforming to DCF thumbnail file stipulated by Design * rule for Camera File System.</li> * <li>“R03” = Indicates a file conforming to DCF Option File stipulated by Design rule * for Camera File System.</li> * </ul> * </ul> */ public static final String TAG_INTEROPERABILITY_INDEX = "InteroperabilityIndex"; /** * @see #TAG_IMAGE_LENGTH */ public static final String TAG_THUMBNAIL_IMAGE_LENGTH = "ThumbnailImageLength"; /** * @see #TAG_IMAGE_WIDTH */ public static final String TAG_THUMBNAIL_IMAGE_WIDTH = "ThumbnailImageWidth"; /** Type is int. DNG Specification 1.4.0.0. Section 4 */ public static final String TAG_DNG_VERSION = "DNGVersion"; /** Type is int. DNG Specification 1.4.0.0. Section 4 */ public static final String TAG_DEFAULT_CROP_SIZE = "DefaultCropSize"; /** Type is undefined. See Olympus MakerNote tags in http://www.exiv2.org/tags-olympus.html. */ public static final String TAG_ORF_THUMBNAIL_IMAGE = "ThumbnailImage"; /** Type is int. See Olympus Camera Settings tags in http://www.exiv2.org/tags-olympus.html. */ public static final String TAG_ORF_PREVIEW_IMAGE_START = "PreviewImageStart"; /** Type is int. See Olympus Camera Settings tags in http://www.exiv2.org/tags-olympus.html. */ public static final String TAG_ORF_PREVIEW_IMAGE_LENGTH = "PreviewImageLength"; /** Type is int. See Olympus Image Processing tags in http://www.exiv2.org/tags-olympus.html. */ public static final String TAG_ORF_ASPECT_FRAME = "AspectFrame"; /** * Type is int. See PanasonicRaw tags in * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html */ public static final String TAG_RW2_SENSOR_BOTTOM_BORDER = "SensorBottomBorder"; /** * Type is int. See PanasonicRaw tags in * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html */ public static final String TAG_RW2_SENSOR_LEFT_BORDER = "SensorLeftBorder"; /** * Type is int. See PanasonicRaw tags in * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html */ public static final String TAG_RW2_SENSOR_RIGHT_BORDER = "SensorRightBorder"; /** * Type is int. See PanasonicRaw tags in * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html */ public static final String TAG_RW2_SENSOR_TOP_BORDER = "SensorTopBorder"; /** * Type is int. See PanasonicRaw tags in * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html */ public static final String TAG_RW2_ISO = "ISO"; /** * Type is undefined. See PanasonicRaw tags in * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html */ public static final String TAG_RW2_JPG_FROM_RAW = "JpgFromRaw"; /** Type is int. See JEITA CP-3451C Spec Section 3: Bilevel Images. */ public static final String TAG_NEW_SUBFILE_TYPE = "NewSubfileType"; /** Type is int. See JEITA CP-3451C Spec Section 3: Bilevel Images. */ public static final String TAG_SUBFILE_TYPE = "SubfileType"; /** * Private tags used for pointing the other IFD offsets. * The types of the following tags are int. * See JEITA CP-3451C Section 4.6.3: Exif-specific IFD. * For SubIFD, see Note 1 of Adobe PageMaker® 6.0 TIFF Technical Notes. */ private static final String TAG_EXIF_IFD_POINTER = "ExifIFDPointer"; private static final String TAG_GPS_INFO_IFD_POINTER = "GPSInfoIFDPointer"; private static final String TAG_INTEROPERABILITY_IFD_POINTER = "InteroperabilityIFDPointer"; private static final String TAG_SUB_IFD_POINTER = "SubIFDPointer"; // Proprietary pointer tags used for ORF files. // See http://www.exiv2.org/tags-olympus.html private static final String TAG_ORF_CAMERA_SETTINGS_IFD_POINTER = "CameraSettingsIFDPointer"; private static final String TAG_ORF_IMAGE_PROCESSING_IFD_POINTER = "ImageProcessingIFDPointer"; // Private tags used for thumbnail information. private static final String TAG_HAS_THUMBNAIL = "HasThumbnail"; private static final String TAG_THUMBNAIL_OFFSET = "ThumbnailOffset"; private static final String TAG_THUMBNAIL_LENGTH = "ThumbnailLength"; private static final String TAG_THUMBNAIL_DATA = "ThumbnailData"; private static final int MAX_THUMBNAIL_SIZE = 512; // Constants used for the Orientation Exif tag. public static final int ORIENTATION_UNDEFINED = 0; public static final int ORIENTATION_NORMAL = 1; /** * Indicates the image is left right reversed mirror. */ public static final int ORIENTATION_FLIP_HORIZONTAL = 2; /** * Indicates the image is rotated by 180 degree clockwise. */ public static final int ORIENTATION_ROTATE_180 = 3; /** * Indicates the image is upside down mirror, it can also be represented by flip * horizontally firstly and rotate 180 degree clockwise. */ public static final int ORIENTATION_FLIP_VERTICAL = 4; /** * Indicates the image is flipped about top-left <--> bottom-right axis, it can also be * represented by flip horizontally firstly and rotate 270 degree clockwise. */ public static final int ORIENTATION_TRANSPOSE = 5; /** * Indicates the image is rotated by 90 degree clockwise. */ public static final int ORIENTATION_ROTATE_90 = 6; /** * Indicates the image is flipped about top-right <--> bottom-left axis, it can also be * represented by flip horizontally firstly and rotate 90 degree clockwise. */ public static final int ORIENTATION_TRANSVERSE = 7; /** * Indicates the image is rotated by 270 degree clockwise. */ public static final int ORIENTATION_ROTATE_270 = 8; private static final List<Integer> ROTATION_ORDER = Arrays.asList(ORIENTATION_NORMAL, ORIENTATION_ROTATE_90, ORIENTATION_ROTATE_180, ORIENTATION_ROTATE_270); private static final List<Integer> FLIPPED_ROTATION_ORDER = Arrays.asList( ORIENTATION_FLIP_HORIZONTAL, ORIENTATION_TRANSVERSE, ORIENTATION_FLIP_VERTICAL, ORIENTATION_TRANSPOSE); /** * The contant used by {@link #TAG_PLANAR_CONFIGURATION} to denote Chunky format. */ public static final short FORMAT_CHUNKY = 1; /** * The contant used by {@link #TAG_PLANAR_CONFIGURATION} to denote Planar format. */ public static final short FORMAT_PLANAR = 2; /** * The contant used by {@link #TAG_Y_CB_CR_POSITIONING} to denote Centered positioning. */ public static final short Y_CB_CR_POSITIONING_CENTERED = 1; /** * The contant used by {@link #TAG_Y_CB_CR_POSITIONING} to denote Co-sited positioning. */ public static final short Y_CB_CR_POSITIONING_CO_SITED = 2; /** * The contant used to denote resolution unit as inches. */ public static final short RESOLUTION_UNIT_INCHES = 2; /** * The contant used to denote resolution unit as centimeters. */ public static final short RESOLUTION_UNIT_CENTIMETERS = 3; /** * The contant used by {@link #TAG_COLOR_SPACE} to denote sRGB color space. */ public static final int COLOR_SPACE_S_RGB = 1; /** * The contant used by {@link #TAG_COLOR_SPACE} to denote Uncalibrated. */ public static final int COLOR_SPACE_UNCALIBRATED = 65535; /** * The contant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is not defined. */ public static final short EXPOSURE_PROGRAM_NOT_DEFINED = 0; /** * The contant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is Manual. */ public static final short EXPOSURE_PROGRAM_MANUAL = 1; /** * The contant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is Normal. */ public static final short EXPOSURE_PROGRAM_NORMAL = 2; /** * The contant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is * Aperture priority. */ public static final short EXPOSURE_PROGRAM_APERTURE_PRIORITY = 3; /** * The contant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is * Shutter priority. */ public static final short EXPOSURE_PROGRAM_SHUTTER_PRIORITY = 4; /** * The contant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is Creative * program (biased toward depth of field). */ public static final short EXPOSURE_PROGRAM_CREATIVE = 5; /** * The contant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is Action * program (biased toward fast shutter speed). */ public static final short EXPOSURE_PROGRAM_ACTION = 6; /** * The contant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is Portrait mode * (for closeup photos with the background out of focus). */ public static final short EXPOSURE_PROGRAM_PORTRAIT_MODE = 7; /** * The contant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is Landscape * mode (for landscape photos with the background in focus). */ public static final short EXPOSURE_PROGRAM_LANDSCAPE_MODE = 8; /** * The contant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is unknown. */ public static final short SENSITIVITY_TYPE_UNKNOWN = 0; /** * The contant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is Standard * output sensitivity (SOS). */ public static final short SENSITIVITY_TYPE_SOS = 1; /** * The contant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is Recommended * exposure index (REI). */ public static final short SENSITIVITY_TYPE_REI = 2; /** * The contant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is ISO speed. */ public static final short SENSITIVITY_TYPE_ISO_SPEED = 3; /** * The contant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is Standard * output sensitivity (SOS) and recommended exposure index (REI). */ public static final short SENSITIVITY_TYPE_SOS_AND_REI = 4; /** * The contant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is Standard * output sensitivity (SOS) and ISO speed. */ public static final short SENSITIVITY_TYPE_SOS_AND_ISO = 5; /** * The contant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is Recommended * exposure index (REI) and ISO speed. */ public static final short SENSITIVITY_TYPE_REI_AND_ISO = 6; /** * The contant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is Standard * output sensitivity (SOS) and recommended exposure index (REI) and ISO speed. */ public static final short SENSITIVITY_TYPE_SOS_AND_REI_AND_ISO = 7; /** * The contant used by {@link #TAG_METERING_MODE} to denote metering mode is unknown. */ public static final short METERING_MODE_UNKNOWN = 0; /** * The contant used by {@link #TAG_METERING_MODE} to denote metering mode is Average. */ public static final short METERING_MODE_AVERAGE = 1; /** * The contant used by {@link #TAG_METERING_MODE} to denote metering mode is * CenterWeightedAverage. */ public static final short METERING_MODE_CENTER_WEIGHT_AVERAGE = 2; /** * The contant used by {@link #TAG_METERING_MODE} to denote metering mode is Spot. */ public static final short METERING_MODE_SPOT = 3; /** * The contant used by {@link #TAG_METERING_MODE} to denote metering mode is MultiSpot. */ public static final short METERING_MODE_MULTI_SPOT = 4; /** * The contant used by {@link #TAG_METERING_MODE} to denote metering mode is Pattern. */ public static final short METERING_MODE_PATTERN = 5; /** * The contant used by {@link #TAG_METERING_MODE} to denote metering mode is Partial. */ public static final short METERING_MODE_PARTIAL = 6; /** * The contant used by {@link #TAG_METERING_MODE} to denote metering mode is other. */ public static final short METERING_MODE_OTHER = 255; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is unknown. */ public static final short LIGHT_SOURCE_UNKNOWN = 0; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Daylight. */ public static final short LIGHT_SOURCE_DAYLIGHT = 1; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Fluorescent. */ public static final short LIGHT_SOURCE_FLUORESCENT = 2; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Tungsten * (incandescent light). */ public static final short LIGHT_SOURCE_TUNGSTEN = 3; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Flash. */ public static final short LIGHT_SOURCE_FLASH = 4; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Fine weather. */ public static final short LIGHT_SOURCE_FINE_WEATHER = 9; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Cloudy weather. */ public static final short LIGHT_SOURCE_CLOUDY_WEATHER = 10; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Shade. */ public static final short LIGHT_SOURCE_SHADE = 11; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Daylight fluorescent * (D 5700 - 7100K). */ public static final short LIGHT_SOURCE_DAYLIGHT_FLUORESCENT = 12; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Day white fluorescent * (N 4600 - 5500K). */ public static final short LIGHT_SOURCE_DAY_WHITE_FLUORESCENT = 13; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Cool white * fluorescent (W 3800 - 4500K). */ public static final short LIGHT_SOURCE_COOL_WHITE_FLUORESCENT = 14; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is White fluorescent * (WW 3250 - 3800K). */ public static final short LIGHT_SOURCE_WHITE_FLUORESCENT = 15; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Warm white * fluorescent (L 2600 - 3250K). */ public static final short LIGHT_SOURCE_WARM_WHITE_FLUORESCENT = 16; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Standard light A. */ public static final short LIGHT_SOURCE_STANDARD_LIGHT_A = 17; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Standard light B. */ public static final short LIGHT_SOURCE_STANDARD_LIGHT_B = 18; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Standard light C. */ public static final short LIGHT_SOURCE_STANDARD_LIGHT_C = 19; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is D55. */ public static final short LIGHT_SOURCE_D55 = 20; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is D65. */ public static final short LIGHT_SOURCE_D65 = 21; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is D75. */ public static final short LIGHT_SOURCE_D75 = 22; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is D50. */ public static final short LIGHT_SOURCE_D50 = 23; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is ISO studio tungsten. */ public static final short LIGHT_SOURCE_ISO_STUDIO_TUNGSTEN = 24; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is other. */ public static final short LIGHT_SOURCE_OTHER = 255; /** * The flag used by {@link #TAG_FLASH} to indicate whether the flash is fired. */ public static final short FLAG_FLASH_FIRED = 0b0000_0001; /** * The flag used by {@link #TAG_FLASH} to indicate strobe return light is not detected. */ public static final short FLAG_FLASH_RETURN_LIGHT_NOT_DETECTED = 0b0000_0100; /** * The flag used by {@link #TAG_FLASH} to indicate strobe return light is detected. */ public static final short FLAG_FLASH_RETURN_LIGHT_DETECTED = 0b0000_0110; /** * The flag used by {@link #TAG_FLASH} to indicate the camera's flash mode is Compulsory flash * firing. * * @see #FLAG_FLASH_MODE_COMPULSORY_SUPPRESSION * @see #FLAG_FLASH_MODE_AUTO */ public static final short FLAG_FLASH_MODE_COMPULSORY_FIRING = 0b0000_1000; /** * The flag used by {@link #TAG_FLASH} to indicate the camera's flash mode is Compulsory flash * suppression. * * @see #FLAG_FLASH_MODE_COMPULSORY_FIRING * @see #FLAG_FLASH_MODE_AUTO */ public static final short FLAG_FLASH_MODE_COMPULSORY_SUPPRESSION = 0b0001_0000; /** * The flag used by {@link #TAG_FLASH} to indicate the camera's flash mode is Auto. * * @see #FLAG_FLASH_MODE_COMPULSORY_FIRING * @see #FLAG_FLASH_MODE_COMPULSORY_SUPPRESSION */ public static final short FLAG_FLASH_MODE_AUTO = 0b0001_1000; /** * The flag used by {@link #TAG_FLASH} to indicate no flash function is present. */ public static final short FLAG_FLASH_NO_FLASH_FUNCTION = 0b0010_0000; /** * The flag used by {@link #TAG_FLASH} to indicate red-eye reduction is supported. */ public static final short FLAG_FLASH_RED_EYE_SUPPORTED = 0b0100_0000; /** * The contant used by {@link #TAG_SENSING_METHOD} to denote the image sensor type is not * defined. */ public static final short SENSOR_TYPE_NOT_DEFINED = 1; /** * The contant used by {@link #TAG_SENSING_METHOD} to denote the image sensor type is One-chip * color area sensor. */ public static final short SENSOR_TYPE_ONE_CHIP = 2; /** * The contant used by {@link #TAG_SENSING_METHOD} to denote the image sensor type is Two-chip * color area sensor. */ public static final short SENSOR_TYPE_TWO_CHIP = 3; /** * The contant used by {@link #TAG_SENSING_METHOD} to denote the image sensor type is Three-chip * color area sensor. */ public static final short SENSOR_TYPE_THREE_CHIP = 4; /** * The contant used by {@link #TAG_SENSING_METHOD} to denote the image sensor type is Color * sequential area sensor. */ public static final short SENSOR_TYPE_COLOR_SEQUENTIAL = 5; /** * The contant used by {@link #TAG_SENSING_METHOD} to denote the image sensor type is Trilinear * sensor. */ public static final short SENSOR_TYPE_TRILINEAR = 7; /** * The contant used by {@link #TAG_SENSING_METHOD} to denote the image sensor type is Color * sequential linear sensor. */ public static final short SENSOR_TYPE_COLOR_SEQUENTIAL_LINEAR = 8; /** * The contant used by {@link #TAG_FILE_SOURCE} to denote the source is other. */ public static final short FILE_SOURCE_OTHER = 0; /** * The contant used by {@link #TAG_FILE_SOURCE} to denote the source is scanner of transparent * type. */ public static final short FILE_SOURCE_TRANSPARENT_SCANNER = 1; /** * The contant used by {@link #TAG_FILE_SOURCE} to denote the source is scanner of reflex type. */ public static final short FILE_SOURCE_REFLEX_SCANNER = 2; /** * The contant used by {@link #TAG_FILE_SOURCE} to denote the source is DSC. */ public static final short FILE_SOURCE_DSC = 3; /** * The contant used by {@link #TAG_SCENE_TYPE} to denote the scene is directly photographed. */ public static final short SCENE_TYPE_DIRECTLY_PHOTOGRAPHED = 1; /** * The contant used by {@link #TAG_CUSTOM_RENDERED} to denote no special processing is used. */ public static final short RENDERED_PROCESS_NORMAL = 0; /** * The contant used by {@link #TAG_CUSTOM_RENDERED} to denote special processing is used. */ public static final short RENDERED_PROCESS_CUSTOM = 1; /** * The contant used by {@link #TAG_EXPOSURE_MODE} to denote the exposure mode is Auto. */ public static final short EXPOSURE_MODE_AUTO = 0; /** * The contant used by {@link #TAG_EXPOSURE_MODE} to denote the exposure mode is Manual. */ public static final short EXPOSURE_MODE_MANUAL = 1; /** * The contant used by {@link #TAG_EXPOSURE_MODE} to denote the exposure mode is Auto bracket. */ public static final short EXPOSURE_MODE_AUTO_BRACKET = 2; /** * The contant used by {@link #TAG_WHITE_BALANCE} to denote the white balance is Auto. * * @deprecated Use {@link #WHITE_BALANCE_AUTO} instead. */ @Deprecated public static final int WHITEBALANCE_AUTO = 0; /** * The contant used by {@link #TAG_WHITE_BALANCE} to denote the white balance is Manual. * * @deprecated Use {@link #WHITE_BALANCE_MANUAL} instead. */ @Deprecated public static final int WHITEBALANCE_MANUAL = 1; /** * The contant used by {@link #TAG_WHITE_BALANCE} to denote the white balance is Auto. */ public static final short WHITE_BALANCE_AUTO = 0; /** * The contant used by {@link #TAG_WHITE_BALANCE} to denote the white balance is Manual. */ public static final short WHITE_BALANCE_MANUAL = 1; /** * The contant used by {@link #TAG_SCENE_CAPTURE_TYPE} to denote the scene capture type is * Standard. */ public static final short SCENE_CAPTURE_TYPE_STANDARD = 0; /** * The contant used by {@link #TAG_SCENE_CAPTURE_TYPE} to denote the scene capture type is * Landscape. */ public static final short SCENE_CAPTURE_TYPE_LANDSCAPE = 1; /** * The contant used by {@link #TAG_SCENE_CAPTURE_TYPE} to denote the scene capture type is * Portrait. */ public static final short SCENE_CAPTURE_TYPE_PORTRAIT = 2; /** * The contant used by {@link #TAG_SCENE_CAPTURE_TYPE} to denote the scene capture type is Night * scene. */ public static final short SCENE_CAPTURE_TYPE_NIGHT = 3; /** * The contant used by {@link #TAG_GAIN_CONTROL} to denote none gain adjustment. */ public static final short GAIN_CONTROL_NONE = 0; /** * The contant used by {@link #TAG_GAIN_CONTROL} to denote low gain up. */ public static final short GAIN_CONTROL_LOW_GAIN_UP = 1; /** * The contant used by {@link #TAG_GAIN_CONTROL} to denote high gain up. */ public static final short GAIN_CONTROL_HIGH_GAIN_UP = 2; /** * The contant used by {@link #TAG_GAIN_CONTROL} to denote low gain down. */ public static final short GAIN_CONTROL_LOW_GAIN_DOWN = 3; /** * The contant used by {@link #TAG_GAIN_CONTROL} to denote high gain down. */ public static final short GAIN_CONTROL_HIGH_GAIN_DOWN = 4; /** * The contant used by {@link #TAG_CONTRAST} to denote normal contrast. */ public static final short CONTRAST_NORMAL = 0; /** * The contant used by {@link #TAG_CONTRAST} to denote soft contrast. */ public static final short CONTRAST_SOFT = 1; /** * The contant used by {@link #TAG_CONTRAST} to denote hard contrast. */ public static final short CONTRAST_HARD = 2; /** * The contant used by {@link #TAG_SATURATION} to denote normal saturation. */ public static final short SATURATION_NORMAL = 0; /** * The contant used by {@link #TAG_SATURATION} to denote low saturation. */ public static final short SATURATION_LOW = 0; /** * The contant used by {@link #TAG_SHARPNESS} to denote high saturation. */ public static final short SATURATION_HIGH = 0; /** * The contant used by {@link #TAG_SHARPNESS} to denote normal sharpness. */ public static final short SHARPNESS_NORMAL = 0; /** * The contant used by {@link #TAG_SHARPNESS} to denote soft sharpness. */ public static final short SHARPNESS_SOFT = 1; /** * The contant used by {@link #TAG_SHARPNESS} to denote hard sharpness. */ public static final short SHARPNESS_HARD = 2; /** * The contant used by {@link #TAG_SUBJECT_DISTANCE_RANGE} to denote the subject distance range * is unknown. */ public static final short SUBJECT_DISTANCE_RANGE_UNKNOWN = 0; /** * The contant used by {@link #TAG_SUBJECT_DISTANCE_RANGE} to denote the subject distance range * is Macro. */ public static final short SUBJECT_DISTANCE_RANGE_MACRO = 1; /** * The contant used by {@link #TAG_SUBJECT_DISTANCE_RANGE} to denote the subject distance range * is Close view. */ public static final short SUBJECT_DISTANCE_RANGE_CLOSE_VIEW = 2; /** * The contant used by {@link #TAG_SUBJECT_DISTANCE_RANGE} to denote the subject distance range * is Distant view. */ public static final short SUBJECT_DISTANCE_RANGE_DISTANT_VIEW = 3; /** * The contant used by GPS latitude-related tags to denote the latitude is North latitude. * * @see #TAG_GPS_LATITUDE_REF * @see #TAG_GPS_DEST_LATITUDE_REF */ public static final String LATITUDE_NORTH = "N"; /** * The contant used by GPS latitude-related tags to denote the latitude is South latitude. * * @see #TAG_GPS_LATITUDE_REF * @see #TAG_GPS_DEST_LATITUDE_REF */ public static final String LATITUDE_SOUTH = "S"; /** * The contant used by GPS longitude-related tags to denote the longitude is East longitude. * * @see #TAG_GPS_LONGITUDE_REF * @see #TAG_GPS_DEST_LONGITUDE_REF */ public static final String LONGITUDE_EAST = "E"; /** * The contant used by GPS longitude-related tags to denote the longitude is West longitude. * * @see #TAG_GPS_LONGITUDE_REF * @see #TAG_GPS_DEST_LONGITUDE_REF */ public static final String LONGITUDE_WEST = "W"; /** * The contant used by {@link #TAG_GPS_ALTITUDE_REF} to denote the altitude is above sea level. */ public static final short ALTITUDE_ABOVE_SEA_LEVEL = 0; /** * The contant used by {@link #TAG_GPS_ALTITUDE_REF} to denote the altitude is below sea level. */ public static final short ALTITUDE_BELOW_SEA_LEVEL = 1; /** * The contant used by {@link #TAG_GPS_STATUS} to denote GPS measurement is in progress. */ public static final String GPS_MEASUREMENT_IN_PROGRESS = "A"; /** * The contant used by {@link #TAG_GPS_STATUS} to denote GPS measurement is interrupted. */ public static final String GPS_MEASUREMENT_INTERRUPTED = "V"; /** * The contant used by {@link #TAG_GPS_MEASURE_MODE} to denote GPS measurement is 2-dimensional. */ public static final String GPS_MEASUREMENT_2D = "2"; /** * The contant used by {@link #TAG_GPS_MEASURE_MODE} to denote GPS measurement is 3-dimensional. */ public static final String GPS_MEASUREMENT_3D = "3"; /** * The contant used by {@link #TAG_GPS_SPEED_REF} to denote the speed unit is kilometers per * hour. */ public static final String GPS_SPEED_KILOMETERS_PER_HOUR = "K"; /** * The contant used by {@link #TAG_GPS_SPEED_REF} to denote the speed unit is miles per hour. */ public static final String GPS_SPEED_MILES_PER_HOUR = "M"; /** * The contant used by {@link #TAG_GPS_SPEED_REF} to denote the speed unit is knots. */ public static final String GPS_SPEED_KNOTS = "N"; /** * The contant used by GPS attributes to denote the direction is true direction. */ public static final String GPS_DIRECTION_TRUE = "T"; /** * The contant used by GPS attributes to denote the direction is magnetic direction. */ public static final String GPS_DIRECTION_MAGNETIC = "M"; /** * The contant used by {@link #TAG_GPS_DEST_DISTANCE_REF} to denote the distance unit is * kilometers. */ public static final String GPS_DISTANCE_KILOMETERS = "K"; /** * The contant used by {@link #TAG_GPS_DEST_DISTANCE_REF} to denote the distance unit is miles. */ public static final String GPS_DISTANCE_MILES = "M"; /** * The contant used by {@link #TAG_GPS_DEST_DISTANCE_REF} to denote the distance unit is * nautical miles. */ public static final String GPS_DISTANCE_NAUTICAL_MILES = "N"; /** * The contant used by {@link #TAG_GPS_DIFFERENTIAL} to denote no differential correction is * applied. */ public static final short GPS_MEASUREMENT_NO_DIFFERENTIAL = 0; /** * The contant used by {@link #TAG_GPS_DIFFERENTIAL} to denote differential correction is * applied. */ public static final short GPS_MEASUREMENT_DIFFERENTIAL_CORRECTED = 1; /** * The constant used by {@link #TAG_COMPRESSION} to denote the image is not compressed. */ public static final int DATA_UNCOMPRESSED = 1; /** * The constant used by {@link #TAG_COMPRESSION} to denote the image is huffman compressed. */ public static final int DATA_HUFFMAN_COMPRESSED = 2; /** * The constant used by {@link #TAG_COMPRESSION} to denote the image is JPEG. */ public static final int DATA_JPEG = 6; /** * The constant used by {@link #TAG_COMPRESSION}, see DNG Specification 1.4.0.0. * Section 3, Compression */ public static final int DATA_JPEG_COMPRESSED = 7; /** * The constant used by {@link #TAG_COMPRESSION}, see DNG Specification 1.4.0.0. * Section 3, Compression */ public static final int DATA_DEFLATE_ZIP = 8; /** * The constant used by {@link #TAG_COMPRESSION} to denote the image is pack-bits compressed. */ public static final int DATA_PACK_BITS_COMPRESSED = 32773; /** * The constant used by {@link #TAG_COMPRESSION}, see DNG Specification 1.4.0.0. * Section 3, Compression */ public static final int DATA_LOSSY_JPEG = 34892; /** * The constant used by {@link #TAG_BITS_PER_SAMPLE}. * See JEITA CP-3451C Spec Section 6, Differences from Palette Color Images */ public static final int[] BITS_PER_SAMPLE_RGB = new int[] { 8, 8, 8 }; /** * The constant used by {@link #TAG_BITS_PER_SAMPLE}. * See JEITA CP-3451C Spec Section 4, Differences from Bilevel Images */ public static final int[] BITS_PER_SAMPLE_GREYSCALE_1 = new int[] { 4 }; /** * The constant used by {@link #TAG_BITS_PER_SAMPLE}. * See JEITA CP-3451C Spec Section 4, Differences from Bilevel Images */ public static final int[] BITS_PER_SAMPLE_GREYSCALE_2 = new int[] { 8 }; /** * The constant used by {@link #TAG_PHOTOMETRIC_INTERPRETATION}. */ public static final int PHOTOMETRIC_INTERPRETATION_WHITE_IS_ZERO = 0; /** * The constant used by {@link #TAG_PHOTOMETRIC_INTERPRETATION}. */ public static final int PHOTOMETRIC_INTERPRETATION_BLACK_IS_ZERO = 1; /** * The constant used by {@link #TAG_PHOTOMETRIC_INTERPRETATION}. */ public static final int PHOTOMETRIC_INTERPRETATION_RGB = 2; /** * The constant used by {@link #TAG_PHOTOMETRIC_INTERPRETATION}. */ public static final int PHOTOMETRIC_INTERPRETATION_YCBCR = 6; /** * The constant used by {@link #TAG_NEW_SUBFILE_TYPE}. See JEITA CP-3451C Spec Section 8. */ public static final int ORIGINAL_RESOLUTION_IMAGE = 0; /** * The constant used by {@link #TAG_NEW_SUBFILE_TYPE}. See JEITA CP-3451C Spec Section 8. */ public static final int REDUCED_RESOLUTION_IMAGE = 1; // Maximum size for checking file type signature (see image_type_recognition_lite.cc) private static final int SIGNATURE_CHECK_SIZE = 5000; static final byte[] JPEG_SIGNATURE = new byte[] {(byte) 0xff, (byte) 0xd8, (byte) 0xff}; private static final String RAF_SIGNATURE = "FUJIFILMCCD-RAW"; private static final int RAF_OFFSET_TO_JPEG_IMAGE_OFFSET = 84; private static final int RAF_INFO_SIZE = 160; private static final int RAF_JPEG_LENGTH_VALUE_SIZE = 4; // See http://fileformats.archiveteam.org/wiki/Olympus_ORF private static final short ORF_SIGNATURE_1 = 0x4f52; private static final short ORF_SIGNATURE_2 = 0x5352; // There are two formats for Olympus Makernote Headers. Each has different identifiers and // offsets to the actual data. // See http://www.exiv2.org/makernote.html#R1 private static final byte[] ORF_MAKER_NOTE_HEADER_1 = new byte[] {(byte) 0x4f, (byte) 0x4c, (byte) 0x59, (byte) 0x4d, (byte) 0x50, (byte) 0x00}; // "OLYMP\0" private static final byte[] ORF_MAKER_NOTE_HEADER_2 = new byte[] {(byte) 0x4f, (byte) 0x4c, (byte) 0x59, (byte) 0x4d, (byte) 0x50, (byte) 0x55, (byte) 0x53, (byte) 0x00, (byte) 0x49, (byte) 0x49}; // "OLYMPUS\0II" private static final int ORF_MAKER_NOTE_HEADER_1_SIZE = 8; private static final int ORF_MAKER_NOTE_HEADER_2_SIZE = 12; // See http://fileformats.archiveteam.org/wiki/RW2 private static final short RW2_SIGNATURE = 0x0055; // See http://fileformats.archiveteam.org/wiki/Pentax_PEF private static final String PEF_SIGNATURE = "PENTAX"; // See http://www.exiv2.org/makernote.html#R11 private static final int PEF_MAKER_NOTE_SKIP_SIZE = 6; private static SimpleDateFormat sFormatter; // See Exchangeable image file format for digital still cameras: Exif version 2.2. // The following values are for parsing EXIF data area. There are tag groups in EXIF data area. // They are called "Image File Directory". They have multiple data formats to cover various // image metadata from GPS longitude to camera model name. // Types of Exif byte alignments (see JEITA CP-3451C Section 4.5.2) static final short BYTE_ALIGN_II = 0x4949; // II: Intel order static final short BYTE_ALIGN_MM = 0x4d4d; // MM: Motorola order // TIFF Header Fixed Constant (see JEITA CP-3451C Section 4.5.2) static final byte START_CODE = 0x2a; // 42 private static final int IFD_OFFSET = 8; // Formats for the value in IFD entry (See TIFF 6.0 Section 2, "Image File Directory".) private static final int IFD_FORMAT_BYTE = 1; private static final int IFD_FORMAT_STRING = 2; private static final int IFD_FORMAT_USHORT = 3; private static final int IFD_FORMAT_ULONG = 4; private static final int IFD_FORMAT_URATIONAL = 5; private static final int IFD_FORMAT_SBYTE = 6; private static final int IFD_FORMAT_UNDEFINED = 7; private static final int IFD_FORMAT_SSHORT = 8; private static final int IFD_FORMAT_SLONG = 9; private static final int IFD_FORMAT_SRATIONAL = 10; private static final int IFD_FORMAT_SINGLE = 11; private static final int IFD_FORMAT_DOUBLE = 12; // Format indicating a new IFD entry (See Adobe PageMaker® 6.0 TIFF Technical Notes, "New Tag") private static final int IFD_FORMAT_IFD = 13; // Names for the data formats for debugging purpose. static final String[] IFD_FORMAT_NAMES = new String[] { "", "BYTE", "STRING", "USHORT", "ULONG", "URATIONAL", "SBYTE", "UNDEFINED", "SSHORT", "SLONG", "SRATIONAL", "SINGLE", "DOUBLE" }; // Sizes of the components of each IFD value format static final int[] IFD_FORMAT_BYTES_PER_FORMAT = new int[] { 0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 1 }; private static final byte[] EXIF_ASCII_PREFIX = new byte[] { 0x41, 0x53, 0x43, 0x49, 0x49, 0x0, 0x0, 0x0 }; // A class for indicating EXIF rational type. private static class Rational { public final long numerator; public final long denominator; private Rational(double value) { this((long) (value * 10000), 10000); } private Rational(long numerator, long denominator) { // Handle erroneous case if (denominator == 0) { this.numerator = 0; this.denominator = 1; return; } this.numerator = numerator; this.denominator = denominator; } @Override public String toString() { return numerator + "/" + denominator; } public double calculate() { return (double) numerator / denominator; } } // A class for indicating EXIF attribute. private static class ExifAttribute { public final int format; public final int numberOfComponents; public final byte[] bytes; private ExifAttribute(int format, int numberOfComponents, byte[] bytes) { this.format = format; this.numberOfComponents = numberOfComponents; this.bytes = bytes; } public static ExifAttribute createUShort(int[] values, ByteOrder byteOrder) { final ByteBuffer buffer = ByteBuffer.wrap( new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_USHORT] * values.length]); buffer.order(byteOrder); for (int value : values) { buffer.putShort((short) value); } return new ExifAttribute(IFD_FORMAT_USHORT, values.length, buffer.array()); } public static ExifAttribute createUShort(int value, ByteOrder byteOrder) { return createUShort(new int[] {value}, byteOrder); } public static ExifAttribute createULong(long[] values, ByteOrder byteOrder) { final ByteBuffer buffer = ByteBuffer.wrap( new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_ULONG] * values.length]); buffer.order(byteOrder); for (long value : values) { buffer.putInt((int) value); } return new ExifAttribute(IFD_FORMAT_ULONG, values.length, buffer.array()); } public static ExifAttribute createULong(long value, ByteOrder byteOrder) { return createULong(new long[] {value}, byteOrder); } public static ExifAttribute createSLong(int[] values, ByteOrder byteOrder) { final ByteBuffer buffer = ByteBuffer.wrap( new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_SLONG] * values.length]); buffer.order(byteOrder); for (int value : values) { buffer.putInt(value); } return new ExifAttribute(IFD_FORMAT_SLONG, values.length, buffer.array()); } public static ExifAttribute createSLong(int value, ByteOrder byteOrder) { return createSLong(new int[] {value}, byteOrder); } public static ExifAttribute createByte(String value) { // Exception for GPSAltitudeRef tag if (value.length() == 1 && value.charAt(0) >= '0' && value.charAt(0) <= '1') { final byte[] bytes = new byte[] { (byte) (value.charAt(0) - '0') }; return new ExifAttribute(IFD_FORMAT_BYTE, bytes.length, bytes); } final byte[] ascii = value.getBytes(ASCII); return new ExifAttribute(IFD_FORMAT_BYTE, ascii.length, ascii); } public static ExifAttribute createString(String value) { final byte[] ascii = (value + '\0').getBytes(ASCII); return new ExifAttribute(IFD_FORMAT_STRING, ascii.length, ascii); } public static ExifAttribute createURational(Rational[] values, ByteOrder byteOrder) { final ByteBuffer buffer = ByteBuffer.wrap( new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_URATIONAL] * values.length]); buffer.order(byteOrder); for (Rational value : values) { buffer.putInt((int) value.numerator); buffer.putInt((int) value.denominator); } return new ExifAttribute(IFD_FORMAT_URATIONAL, values.length, buffer.array()); } public static ExifAttribute createURational(Rational value, ByteOrder byteOrder) { return createURational(new Rational[] {value}, byteOrder); } public static ExifAttribute createSRational(Rational[] values, ByteOrder byteOrder) { final ByteBuffer buffer = ByteBuffer.wrap( new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_SRATIONAL] * values.length]); buffer.order(byteOrder); for (Rational value : values) { buffer.putInt((int) value.numerator); buffer.putInt((int) value.denominator); } return new ExifAttribute(IFD_FORMAT_SRATIONAL, values.length, buffer.array()); } public static ExifAttribute createSRational(Rational value, ByteOrder byteOrder) { return createSRational(new Rational[] {value}, byteOrder); } public static ExifAttribute createDouble(double[] values, ByteOrder byteOrder) { final ByteBuffer buffer = ByteBuffer.wrap( new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_DOUBLE] * values.length]); buffer.order(byteOrder); for (double value : values) { buffer.putDouble(value); } return new ExifAttribute(IFD_FORMAT_DOUBLE, values.length, buffer.array()); } public static ExifAttribute createDouble(double value, ByteOrder byteOrder) { return createDouble(new double[] {value}, byteOrder); } @Override public String toString() { return "(" + IFD_FORMAT_NAMES[format] + ", data length:" + bytes.length + ")"; } private Object getValue(ByteOrder byteOrder) { ByteOrderedDataInputStream inputStream = null; try { inputStream = new ByteOrderedDataInputStream(bytes); inputStream.setByteOrder(byteOrder); switch (format) { case IFD_FORMAT_BYTE: case IFD_FORMAT_SBYTE: { // Exception for GPSAltitudeRef tag if (bytes.length == 1 && bytes[0] >= 0 && bytes[0] <= 1) { return new String(new char[] { (char) (bytes[0] + '0') }); } return new String(bytes, ASCII); } case IFD_FORMAT_UNDEFINED: case IFD_FORMAT_STRING: { int index = 0; if (numberOfComponents >= EXIF_ASCII_PREFIX.length) { boolean same = true; for (int i = 0; i < EXIF_ASCII_PREFIX.length; ++i) { if (bytes[i] != EXIF_ASCII_PREFIX[i]) { same = false; break; } } if (same) { index = EXIF_ASCII_PREFIX.length; } } StringBuilder stringBuilder = new StringBuilder(); while (index < numberOfComponents) { int ch = bytes[index]; if (ch == 0) { break; } if (ch >= 32) { stringBuilder.append((char) ch); } else { stringBuilder.append('?'); } ++index; } return stringBuilder.toString(); } case IFD_FORMAT_USHORT: { final int[] values = new int[numberOfComponents]; for (int i = 0; i < numberOfComponents; ++i) { values[i] = inputStream.readUnsignedShort(); } return values; } case IFD_FORMAT_ULONG: { final long[] values = new long[numberOfComponents]; for (int i = 0; i < numberOfComponents; ++i) { values[i] = inputStream.readUnsignedInt(); } return values; } case IFD_FORMAT_URATIONAL: { final Rational[] values = new Rational[numberOfComponents]; for (int i = 0; i < numberOfComponents; ++i) { final long numerator = inputStream.readUnsignedInt(); final long denominator = inputStream.readUnsignedInt(); values[i] = new Rational(numerator, denominator); } return values; } case IFD_FORMAT_SSHORT: { final int[] values = new int[numberOfComponents]; for (int i = 0; i < numberOfComponents; ++i) { values[i] = inputStream.readShort(); } return values; } case IFD_FORMAT_SLONG: { final int[] values = new int[numberOfComponents]; for (int i = 0; i < numberOfComponents; ++i) { values[i] = inputStream.readInt(); } return values; } case IFD_FORMAT_SRATIONAL: { final Rational[] values = new Rational[numberOfComponents]; for (int i = 0; i < numberOfComponents; ++i) { final long numerator = inputStream.readInt(); final long denominator = inputStream.readInt(); values[i] = new Rational(numerator, denominator); } return values; } case IFD_FORMAT_SINGLE: { final double[] values = new double[numberOfComponents]; for (int i = 0; i < numberOfComponents; ++i) { values[i] = inputStream.readFloat(); } return values; } case IFD_FORMAT_DOUBLE: { final double[] values = new double[numberOfComponents]; for (int i = 0; i < numberOfComponents; ++i) { values[i] = inputStream.readDouble(); } return values; } default: return null; } } catch (IOException e) { Log.w(TAG, "IOException occurred during reading a value", e); return null; } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { Log.e(TAG, "IOException occurred while closing InputStream", e); } } } } public double getDoubleValue(ByteOrder byteOrder) { Object value = getValue(byteOrder); if (value == null) { throw new NumberFormatException("NULL can't be converted to a double value"); } if (value instanceof String) { return Double.parseDouble((String) value); } if (value instanceof long[]) { long[] array = (long[]) value; if (array.length == 1) { return array[0]; } throw new NumberFormatException("There are more than one component"); } if (value instanceof int[]) { int[] array = (int[]) value; if (array.length == 1) { return array[0]; } throw new NumberFormatException("There are more than one component"); } if (value instanceof double[]) { double[] array = (double[]) value; if (array.length == 1) { return array[0]; } throw new NumberFormatException("There are more than one component"); } if (value instanceof Rational[]) { Rational[] array = (Rational[]) value; if (array.length == 1) { return array[0].calculate(); } throw new NumberFormatException("There are more than one component"); } throw new NumberFormatException("Couldn't find a double value"); } public int getIntValue(ByteOrder byteOrder) { Object value = getValue(byteOrder); if (value == null) { throw new NumberFormatException("NULL can't be converted to a integer value"); } if (value instanceof String) { return Integer.parseInt((String) value); } if (value instanceof long[]) { long[] array = (long[]) value; if (array.length == 1) { return (int) array[0]; } throw new NumberFormatException("There are more than one component"); } if (value instanceof int[]) { int[] array = (int[]) value; if (array.length == 1) { return array[0]; } throw new NumberFormatException("There are more than one component"); } throw new NumberFormatException("Couldn't find a integer value"); } public String getStringValue(ByteOrder byteOrder) { Object value = getValue(byteOrder); if (value == null) { return null; } if (value instanceof String) { return (String) value; } final StringBuilder stringBuilder = new StringBuilder(); if (value instanceof long[]) { long[] array = (long[]) value; for (int i = 0; i < array.length; ++i) { stringBuilder.append(array[i]); if (i + 1 != array.length) { stringBuilder.append(","); } } return stringBuilder.toString(); } if (value instanceof int[]) { int[] array = (int[]) value; for (int i = 0; i < array.length; ++i) { stringBuilder.append(array[i]); if (i + 1 != array.length) { stringBuilder.append(","); } } return stringBuilder.toString(); } if (value instanceof double[]) { double[] array = (double[]) value; for (int i = 0; i < array.length; ++i) { stringBuilder.append(array[i]); if (i + 1 != array.length) { stringBuilder.append(","); } } return stringBuilder.toString(); } if (value instanceof Rational[]) { Rational[] array = (Rational[]) value; for (int i = 0; i < array.length; ++i) { stringBuilder.append(array[i].numerator); stringBuilder.append('/'); stringBuilder.append(array[i].denominator); if (i + 1 != array.length) { stringBuilder.append(","); } } return stringBuilder.toString(); } return null; } public int size() { return IFD_FORMAT_BYTES_PER_FORMAT[format] * numberOfComponents; } } // A class for indicating EXIF tag. static class ExifTag { public final int number; public final String name; public final int primaryFormat; public final int secondaryFormat; private ExifTag(String name, int number, int format) { this.name = name; this.number = number; this.primaryFormat = format; this.secondaryFormat = -1; } private ExifTag(String name, int number, int primaryFormat, int secondaryFormat) { this.name = name; this.number = number; this.primaryFormat = primaryFormat; this.secondaryFormat = secondaryFormat; } private boolean isFormatCompatible(int format) { if (primaryFormat == IFD_FORMAT_UNDEFINED || format == IFD_FORMAT_UNDEFINED) { return true; } else if (primaryFormat == format || secondaryFormat == format) { return true; } else if ((primaryFormat == IFD_FORMAT_ULONG || secondaryFormat == IFD_FORMAT_ULONG) && format == IFD_FORMAT_USHORT) { return true; } else if ((primaryFormat == IFD_FORMAT_SLONG || secondaryFormat == IFD_FORMAT_SLONG) && format == IFD_FORMAT_SSHORT) { return true; } else if ((primaryFormat == IFD_FORMAT_DOUBLE || secondaryFormat == IFD_FORMAT_DOUBLE) && format == IFD_FORMAT_SINGLE) { return true; } return false; } } // Primary image IFD TIFF tags (See JEITA CP-3451C Section 4.6.8 Tag Support Levels) private static final ExifTag[] IFD_TIFF_TAGS = new ExifTag[] { // For below two, see TIFF 6.0 Spec Section 3: Bilevel Images. new ExifTag(TAG_NEW_SUBFILE_TYPE, 254, IFD_FORMAT_ULONG), new ExifTag(TAG_SUBFILE_TYPE, 255, IFD_FORMAT_ULONG), new ExifTag(TAG_IMAGE_WIDTH, 256, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_IMAGE_LENGTH, 257, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_BITS_PER_SAMPLE, 258, IFD_FORMAT_USHORT), new ExifTag(TAG_COMPRESSION, 259, IFD_FORMAT_USHORT), new ExifTag(TAG_PHOTOMETRIC_INTERPRETATION, 262, IFD_FORMAT_USHORT), new ExifTag(TAG_IMAGE_DESCRIPTION, 270, IFD_FORMAT_STRING), new ExifTag(TAG_MAKE, 271, IFD_FORMAT_STRING), new ExifTag(TAG_MODEL, 272, IFD_FORMAT_STRING), new ExifTag(TAG_STRIP_OFFSETS, 273, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_ORIENTATION, 274, IFD_FORMAT_USHORT), new ExifTag(TAG_SAMPLES_PER_PIXEL, 277, IFD_FORMAT_USHORT), new ExifTag(TAG_ROWS_PER_STRIP, 278, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_STRIP_BYTE_COUNTS, 279, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_X_RESOLUTION, 282, IFD_FORMAT_URATIONAL), new ExifTag(TAG_Y_RESOLUTION, 283, IFD_FORMAT_URATIONAL), new ExifTag(TAG_PLANAR_CONFIGURATION, 284, IFD_FORMAT_USHORT), new ExifTag(TAG_RESOLUTION_UNIT, 296, IFD_FORMAT_USHORT), new ExifTag(TAG_TRANSFER_FUNCTION, 301, IFD_FORMAT_USHORT), new ExifTag(TAG_SOFTWARE, 305, IFD_FORMAT_STRING), new ExifTag(TAG_DATETIME, 306, IFD_FORMAT_STRING), new ExifTag(TAG_ARTIST, 315, IFD_FORMAT_STRING), new ExifTag(TAG_WHITE_POINT, 318, IFD_FORMAT_URATIONAL), new ExifTag(TAG_PRIMARY_CHROMATICITIES, 319, IFD_FORMAT_URATIONAL), // See Adobe PageMaker® 6.0 TIFF Technical Notes, Note 1. new ExifTag(TAG_SUB_IFD_POINTER, 330, IFD_FORMAT_ULONG), new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT, 513, IFD_FORMAT_ULONG), new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 514, IFD_FORMAT_ULONG), new ExifTag(TAG_Y_CB_CR_COEFFICIENTS, 529, IFD_FORMAT_URATIONAL), new ExifTag(TAG_Y_CB_CR_SUB_SAMPLING, 530, IFD_FORMAT_USHORT), new ExifTag(TAG_Y_CB_CR_POSITIONING, 531, IFD_FORMAT_USHORT), new ExifTag(TAG_REFERENCE_BLACK_WHITE, 532, IFD_FORMAT_URATIONAL), new ExifTag(TAG_COPYRIGHT, 33432, IFD_FORMAT_STRING), new ExifTag(TAG_EXIF_IFD_POINTER, 34665, IFD_FORMAT_ULONG), new ExifTag(TAG_GPS_INFO_IFD_POINTER, 34853, IFD_FORMAT_ULONG), // RW2 file tags // See http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html) new ExifTag(TAG_RW2_SENSOR_TOP_BORDER, 4, IFD_FORMAT_ULONG), new ExifTag(TAG_RW2_SENSOR_LEFT_BORDER, 5, IFD_FORMAT_ULONG), new ExifTag(TAG_RW2_SENSOR_BOTTOM_BORDER, 6, IFD_FORMAT_ULONG), new ExifTag(TAG_RW2_SENSOR_RIGHT_BORDER, 7, IFD_FORMAT_ULONG), new ExifTag(TAG_RW2_ISO, 23, IFD_FORMAT_USHORT), new ExifTag(TAG_RW2_JPG_FROM_RAW, 46, IFD_FORMAT_UNDEFINED) }; // Primary image IFD Exif Private tags (See JEITA CP-3451C Section 4.6.8 Tag Support Levels) private static final ExifTag[] IFD_EXIF_TAGS = new ExifTag[] { new ExifTag(TAG_EXPOSURE_TIME, 33434, IFD_FORMAT_URATIONAL), new ExifTag(TAG_F_NUMBER, 33437, IFD_FORMAT_URATIONAL), new ExifTag(TAG_EXPOSURE_PROGRAM, 34850, IFD_FORMAT_USHORT), new ExifTag(TAG_SPECTRAL_SENSITIVITY, 34852, IFD_FORMAT_STRING), new ExifTag(TAG_PHOTOGRAPHIC_SENSITIVITY, 34855, IFD_FORMAT_USHORT), new ExifTag(TAG_OECF, 34856, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_EXIF_VERSION, 36864, IFD_FORMAT_STRING), new ExifTag(TAG_DATETIME_ORIGINAL, 36867, IFD_FORMAT_STRING), new ExifTag(TAG_DATETIME_DIGITIZED, 36868, IFD_FORMAT_STRING), new ExifTag(TAG_COMPONENTS_CONFIGURATION, 37121, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_COMPRESSED_BITS_PER_PIXEL, 37122, IFD_FORMAT_URATIONAL), new ExifTag(TAG_SHUTTER_SPEED_VALUE, 37377, IFD_FORMAT_SRATIONAL), new ExifTag(TAG_APERTURE_VALUE, 37378, IFD_FORMAT_URATIONAL), new ExifTag(TAG_BRIGHTNESS_VALUE, 37379, IFD_FORMAT_SRATIONAL), new ExifTag(TAG_EXPOSURE_BIAS_VALUE, 37380, IFD_FORMAT_SRATIONAL), new ExifTag(TAG_MAX_APERTURE_VALUE, 37381, IFD_FORMAT_URATIONAL), new ExifTag(TAG_SUBJECT_DISTANCE, 37382, IFD_FORMAT_URATIONAL), new ExifTag(TAG_METERING_MODE, 37383, IFD_FORMAT_USHORT), new ExifTag(TAG_LIGHT_SOURCE, 37384, IFD_FORMAT_USHORT), new ExifTag(TAG_FLASH, 37385, IFD_FORMAT_USHORT), new ExifTag(TAG_FOCAL_LENGTH, 37386, IFD_FORMAT_URATIONAL), new ExifTag(TAG_SUBJECT_AREA, 37396, IFD_FORMAT_USHORT), new ExifTag(TAG_MAKER_NOTE, 37500, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_USER_COMMENT, 37510, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_SUBSEC_TIME, 37520, IFD_FORMAT_STRING), new ExifTag(TAG_SUBSEC_TIME_ORIGINAL, 37521, IFD_FORMAT_STRING), new ExifTag(TAG_SUBSEC_TIME_DIGITIZED, 37522, IFD_FORMAT_STRING), new ExifTag(TAG_FLASHPIX_VERSION, 40960, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_COLOR_SPACE, 40961, IFD_FORMAT_USHORT), new ExifTag(TAG_PIXEL_X_DIMENSION, 40962, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_PIXEL_Y_DIMENSION, 40963, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_RELATED_SOUND_FILE, 40964, IFD_FORMAT_STRING), new ExifTag(TAG_INTEROPERABILITY_IFD_POINTER, 40965, IFD_FORMAT_ULONG), new ExifTag(TAG_FLASH_ENERGY, 41483, IFD_FORMAT_URATIONAL), new ExifTag(TAG_SPATIAL_FREQUENCY_RESPONSE, 41484, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_FOCAL_PLANE_X_RESOLUTION, 41486, IFD_FORMAT_URATIONAL), new ExifTag(TAG_FOCAL_PLANE_Y_RESOLUTION, 41487, IFD_FORMAT_URATIONAL), new ExifTag(TAG_FOCAL_PLANE_RESOLUTION_UNIT, 41488, IFD_FORMAT_USHORT), new ExifTag(TAG_SUBJECT_LOCATION, 41492, IFD_FORMAT_USHORT), new ExifTag(TAG_EXPOSURE_INDEX, 41493, IFD_FORMAT_URATIONAL), new ExifTag(TAG_SENSING_METHOD, 41495, IFD_FORMAT_USHORT), new ExifTag(TAG_FILE_SOURCE, 41728, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_SCENE_TYPE, 41729, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_CFA_PATTERN, 41730, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_CUSTOM_RENDERED, 41985, IFD_FORMAT_USHORT), new ExifTag(TAG_EXPOSURE_MODE, 41986, IFD_FORMAT_USHORT), new ExifTag(TAG_WHITE_BALANCE, 41987, IFD_FORMAT_USHORT), new ExifTag(TAG_DIGITAL_ZOOM_RATIO, 41988, IFD_FORMAT_URATIONAL), new ExifTag(TAG_FOCAL_LENGTH_IN_35MM_FILM, 41989, IFD_FORMAT_USHORT), new ExifTag(TAG_SCENE_CAPTURE_TYPE, 41990, IFD_FORMAT_USHORT), new ExifTag(TAG_GAIN_CONTROL, 41991, IFD_FORMAT_USHORT), new ExifTag(TAG_CONTRAST, 41992, IFD_FORMAT_USHORT), new ExifTag(TAG_SATURATION, 41993, IFD_FORMAT_USHORT), new ExifTag(TAG_SHARPNESS, 41994, IFD_FORMAT_USHORT), new ExifTag(TAG_DEVICE_SETTING_DESCRIPTION, 41995, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_SUBJECT_DISTANCE_RANGE, 41996, IFD_FORMAT_USHORT), new ExifTag(TAG_IMAGE_UNIQUE_ID, 42016, IFD_FORMAT_STRING), new ExifTag(TAG_DNG_VERSION, 50706, IFD_FORMAT_BYTE), new ExifTag(TAG_DEFAULT_CROP_SIZE, 50720, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG) }; // Primary image IFD GPS Info tags (See JEITA CP-3451C Section 4.6.8 Tag Support Levels) private static final ExifTag[] IFD_GPS_TAGS = new ExifTag[] { new ExifTag(TAG_GPS_VERSION_ID, 0, IFD_FORMAT_BYTE), new ExifTag(TAG_GPS_LATITUDE_REF, 1, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_LATITUDE, 2, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_LONGITUDE_REF, 3, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_LONGITUDE, 4, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_ALTITUDE_REF, 5, IFD_FORMAT_BYTE), new ExifTag(TAG_GPS_ALTITUDE, 6, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_TIMESTAMP, 7, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_SATELLITES, 8, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_STATUS, 9, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_MEASURE_MODE, 10, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_DOP, 11, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_SPEED_REF, 12, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_SPEED, 13, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_TRACK_REF, 14, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_TRACK, 15, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_IMG_DIRECTION_REF, 16, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_IMG_DIRECTION, 17, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_MAP_DATUM, 18, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_DEST_LATITUDE_REF, 19, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_DEST_LATITUDE, 20, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_DEST_LONGITUDE_REF, 21, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_DEST_LONGITUDE, 22, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_DEST_BEARING_REF, 23, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_DEST_BEARING, 24, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_DEST_DISTANCE_REF, 25, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_DEST_DISTANCE, 26, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_PROCESSING_METHOD, 27, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_GPS_AREA_INFORMATION, 28, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_GPS_DATESTAMP, 29, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_DIFFERENTIAL, 30, IFD_FORMAT_USHORT) }; // Primary image IFD Interoperability tag (See JEITA CP-3451C Section 4.6.8 Tag Support Levels) private static final ExifTag[] IFD_INTEROPERABILITY_TAGS = new ExifTag[] { new ExifTag(TAG_INTEROPERABILITY_INDEX, 1, IFD_FORMAT_STRING) }; // IFD Thumbnail tags (See JEITA CP-3451C Section 4.6.8 Tag Support Levels) private static final ExifTag[] IFD_THUMBNAIL_TAGS = new ExifTag[] { // For below two, see TIFF 6.0 Spec Section 3: Bilevel Images. new ExifTag(TAG_NEW_SUBFILE_TYPE, 254, IFD_FORMAT_ULONG), new ExifTag(TAG_SUBFILE_TYPE, 255, IFD_FORMAT_ULONG), new ExifTag(TAG_THUMBNAIL_IMAGE_WIDTH, 256, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_THUMBNAIL_IMAGE_LENGTH, 257, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_BITS_PER_SAMPLE, 258, IFD_FORMAT_USHORT), new ExifTag(TAG_COMPRESSION, 259, IFD_FORMAT_USHORT), new ExifTag(TAG_PHOTOMETRIC_INTERPRETATION, 262, IFD_FORMAT_USHORT), new ExifTag(TAG_IMAGE_DESCRIPTION, 270, IFD_FORMAT_STRING), new ExifTag(TAG_MAKE, 271, IFD_FORMAT_STRING), new ExifTag(TAG_MODEL, 272, IFD_FORMAT_STRING), new ExifTag(TAG_STRIP_OFFSETS, 273, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_ORIENTATION, 274, IFD_FORMAT_USHORT), new ExifTag(TAG_SAMPLES_PER_PIXEL, 277, IFD_FORMAT_USHORT), new ExifTag(TAG_ROWS_PER_STRIP, 278, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_STRIP_BYTE_COUNTS, 279, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_X_RESOLUTION, 282, IFD_FORMAT_URATIONAL), new ExifTag(TAG_Y_RESOLUTION, 283, IFD_FORMAT_URATIONAL), new ExifTag(TAG_PLANAR_CONFIGURATION, 284, IFD_FORMAT_USHORT), new ExifTag(TAG_RESOLUTION_UNIT, 296, IFD_FORMAT_USHORT), new ExifTag(TAG_TRANSFER_FUNCTION, 301, IFD_FORMAT_USHORT), new ExifTag(TAG_SOFTWARE, 305, IFD_FORMAT_STRING), new ExifTag(TAG_DATETIME, 306, IFD_FORMAT_STRING), new ExifTag(TAG_ARTIST, 315, IFD_FORMAT_STRING), new ExifTag(TAG_WHITE_POINT, 318, IFD_FORMAT_URATIONAL), new ExifTag(TAG_PRIMARY_CHROMATICITIES, 319, IFD_FORMAT_URATIONAL), // See Adobe PageMaker® 6.0 TIFF Technical Notes, Note 1. new ExifTag(TAG_SUB_IFD_POINTER, 330, IFD_FORMAT_ULONG), new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT, 513, IFD_FORMAT_ULONG), new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 514, IFD_FORMAT_ULONG), new ExifTag(TAG_Y_CB_CR_COEFFICIENTS, 529, IFD_FORMAT_URATIONAL), new ExifTag(TAG_Y_CB_CR_SUB_SAMPLING, 530, IFD_FORMAT_USHORT), new ExifTag(TAG_Y_CB_CR_POSITIONING, 531, IFD_FORMAT_USHORT), new ExifTag(TAG_REFERENCE_BLACK_WHITE, 532, IFD_FORMAT_URATIONAL), new ExifTag(TAG_COPYRIGHT, 33432, IFD_FORMAT_STRING), new ExifTag(TAG_EXIF_IFD_POINTER, 34665, IFD_FORMAT_ULONG), new ExifTag(TAG_GPS_INFO_IFD_POINTER, 34853, IFD_FORMAT_ULONG), new ExifTag(TAG_DNG_VERSION, 50706, IFD_FORMAT_BYTE), new ExifTag(TAG_DEFAULT_CROP_SIZE, 50720, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG) }; // RAF file tag (See piex.cc line 372) private static final ExifTag TAG_RAF_IMAGE_SIZE = new ExifTag(TAG_STRIP_OFFSETS, 273, IFD_FORMAT_USHORT); // ORF file tags (See http://www.exiv2.org/tags-olympus.html) private static final ExifTag[] ORF_MAKER_NOTE_TAGS = new ExifTag[] { new ExifTag(TAG_ORF_THUMBNAIL_IMAGE, 256, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_ORF_CAMERA_SETTINGS_IFD_POINTER, 8224, IFD_FORMAT_ULONG), new ExifTag(TAG_ORF_IMAGE_PROCESSING_IFD_POINTER, 8256, IFD_FORMAT_ULONG) }; private static final ExifTag[] ORF_CAMERA_SETTINGS_TAGS = new ExifTag[] { new ExifTag(TAG_ORF_PREVIEW_IMAGE_START, 257, IFD_FORMAT_ULONG), new ExifTag(TAG_ORF_PREVIEW_IMAGE_LENGTH, 258, IFD_FORMAT_ULONG) }; private static final ExifTag[] ORF_IMAGE_PROCESSING_TAGS = new ExifTag[] { new ExifTag(TAG_ORF_ASPECT_FRAME, 4371, IFD_FORMAT_USHORT) }; // PEF file tag (See http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Pentax.html) private static final ExifTag[] PEF_TAGS = new ExifTag[] { new ExifTag(TAG_COLOR_SPACE, 55, IFD_FORMAT_USHORT) }; // See JEITA CP-3451C Section 4.6.3: Exif-specific IFD. // The following values are used for indicating pointers to the other Image File Directories. // Indices of Exif Ifd tag groups /** @hide */ @Retention(RetentionPolicy.SOURCE) @IntDef({IFD_TYPE_PRIMARY, IFD_TYPE_EXIF, IFD_TYPE_GPS, IFD_TYPE_INTEROPERABILITY, IFD_TYPE_THUMBNAIL, IFD_TYPE_PREVIEW, IFD_TYPE_ORF_MAKER_NOTE, IFD_TYPE_ORF_CAMERA_SETTINGS, IFD_TYPE_ORF_IMAGE_PROCESSING, IFD_TYPE_PEF}) public @interface IfdType {} static final int IFD_TYPE_PRIMARY = 0; private static final int IFD_TYPE_EXIF = 1; private static final int IFD_TYPE_GPS = 2; private static final int IFD_TYPE_INTEROPERABILITY = 3; static final int IFD_TYPE_THUMBNAIL = 4; static final int IFD_TYPE_PREVIEW = 5; private static final int IFD_TYPE_ORF_MAKER_NOTE = 6; private static final int IFD_TYPE_ORF_CAMERA_SETTINGS = 7; private static final int IFD_TYPE_ORF_IMAGE_PROCESSING = 8; private static final int IFD_TYPE_PEF = 9; // List of Exif tag groups static final ExifTag[][] EXIF_TAGS = new ExifTag[][] { IFD_TIFF_TAGS, IFD_EXIF_TAGS, IFD_GPS_TAGS, IFD_INTEROPERABILITY_TAGS, IFD_THUMBNAIL_TAGS, IFD_TIFF_TAGS, ORF_MAKER_NOTE_TAGS, ORF_CAMERA_SETTINGS_TAGS, ORF_IMAGE_PROCESSING_TAGS, PEF_TAGS }; // List of tags for pointing to the other image file directory offset. private static final ExifTag[] EXIF_POINTER_TAGS = new ExifTag[] { new ExifTag(TAG_SUB_IFD_POINTER, 330, IFD_FORMAT_ULONG), new ExifTag(TAG_EXIF_IFD_POINTER, 34665, IFD_FORMAT_ULONG), new ExifTag(TAG_GPS_INFO_IFD_POINTER, 34853, IFD_FORMAT_ULONG), new ExifTag(TAG_INTEROPERABILITY_IFD_POINTER, 40965, IFD_FORMAT_ULONG), new ExifTag(TAG_ORF_CAMERA_SETTINGS_IFD_POINTER, 8224, IFD_FORMAT_BYTE), new ExifTag(TAG_ORF_IMAGE_PROCESSING_IFD_POINTER, 8256, IFD_FORMAT_BYTE) }; // Tags for indicating the thumbnail offset and length private static final ExifTag JPEG_INTERCHANGE_FORMAT_TAG = new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT, 513, IFD_FORMAT_ULONG); private static final ExifTag JPEG_INTERCHANGE_FORMAT_LENGTH_TAG = new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 514, IFD_FORMAT_ULONG); // Mappings from tag number to tag name and each item represents one IFD tag group. @SuppressWarnings("unchecked") private static final HashMap<Integer, ExifTag>[] sExifTagMapsForReading = new HashMap[EXIF_TAGS.length]; // Mappings from tag name to tag number and each item represents one IFD tag group. @SuppressWarnings("unchecked") private static final HashMap<String, ExifTag>[] sExifTagMapsForWriting = new HashMap[EXIF_TAGS.length]; private static final HashSet<String> sTagSetForCompatibility = new HashSet<>(Arrays.asList( TAG_F_NUMBER, TAG_DIGITAL_ZOOM_RATIO, TAG_EXPOSURE_TIME, TAG_SUBJECT_DISTANCE, TAG_GPS_TIMESTAMP)); // Mappings from tag number to IFD type for pointer tags. @SuppressWarnings("unchecked") private static final HashMap<Integer, Integer> sExifPointerTagMap = new HashMap(); // See JPEG File Interchange Format Version 1.02. // The following values are defined for handling JPEG streams. In this implementation, we are // not only getting information from EXIF but also from some JPEG special segments such as // MARKER_COM for user comment and MARKER_SOFx for image width and height. private static final Charset ASCII = Charset.forName("US-ASCII"); // Identifier for EXIF APP1 segment in JPEG static final byte[] IDENTIFIER_EXIF_APP1 = "Exif\0\0".getBytes(ASCII); // JPEG segment markers, that each marker consumes two bytes beginning with 0xff and ending with // the indicator. There is no SOF4, SOF8, SOF16 markers in JPEG and SOFx markers indicates start // of frame(baseline DCT) and the image size info exists in its beginning part. static final byte MARKER = (byte) 0xff; private static final byte MARKER_SOI = (byte) 0xd8; private static final byte MARKER_SOF0 = (byte) 0xc0; private static final byte MARKER_SOF1 = (byte) 0xc1; private static final byte MARKER_SOF2 = (byte) 0xc2; private static final byte MARKER_SOF3 = (byte) 0xc3; private static final byte MARKER_SOF5 = (byte) 0xc5; private static final byte MARKER_SOF6 = (byte) 0xc6; private static final byte MARKER_SOF7 = (byte) 0xc7; private static final byte MARKER_SOF9 = (byte) 0xc9; private static final byte MARKER_SOF10 = (byte) 0xca; private static final byte MARKER_SOF11 = (byte) 0xcb; private static final byte MARKER_SOF13 = (byte) 0xcd; private static final byte MARKER_SOF14 = (byte) 0xce; private static final byte MARKER_SOF15 = (byte) 0xcf; private static final byte MARKER_SOS = (byte) 0xda; static final byte MARKER_APP1 = (byte) 0xe1; private static final byte MARKER_COM = (byte) 0xfe; static final byte MARKER_EOI = (byte) 0xd9; // Supported Image File Types private static final int IMAGE_TYPE_UNKNOWN = 0; private static final int IMAGE_TYPE_ARW = 1; private static final int IMAGE_TYPE_CR2 = 2; private static final int IMAGE_TYPE_DNG = 3; private static final int IMAGE_TYPE_JPEG = 4; private static final int IMAGE_TYPE_NEF = 5; private static final int IMAGE_TYPE_NRW = 6; private static final int IMAGE_TYPE_ORF = 7; private static final int IMAGE_TYPE_PEF = 8; private static final int IMAGE_TYPE_RAF = 9; private static final int IMAGE_TYPE_RW2 = 10; private static final int IMAGE_TYPE_SRW = 11; static { sFormatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss"); sFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); // Build up the hash tables to look up Exif tags for reading Exif tags. for (int ifdType = 0; ifdType < EXIF_TAGS.length; ++ifdType) { sExifTagMapsForReading[ifdType] = new HashMap<>(); sExifTagMapsForWriting[ifdType] = new HashMap<>(); for (ExifTag tag : EXIF_TAGS[ifdType]) { sExifTagMapsForReading[ifdType].put(tag.number, tag); sExifTagMapsForWriting[ifdType].put(tag.name, tag); } } // Build up the hash table to look up Exif pointer tags. sExifPointerTagMap.put(EXIF_POINTER_TAGS[0].number, IFD_TYPE_PREVIEW); // 330 sExifPointerTagMap.put(EXIF_POINTER_TAGS[1].number, IFD_TYPE_EXIF); // 34665 sExifPointerTagMap.put(EXIF_POINTER_TAGS[2].number, IFD_TYPE_GPS); // 34853 sExifPointerTagMap.put(EXIF_POINTER_TAGS[3].number, IFD_TYPE_INTEROPERABILITY); // 40965 sExifPointerTagMap.put(EXIF_POINTER_TAGS[4].number, IFD_TYPE_ORF_CAMERA_SETTINGS); // 8224 sExifPointerTagMap.put(EXIF_POINTER_TAGS[5].number, IFD_TYPE_ORF_IMAGE_PROCESSING); // 8256 } private final String mFilename; private final AssetManager.AssetInputStream mAssetInputStream; private int mMimeType; @SuppressWarnings("unchecked") private final HashMap<String, ExifAttribute>[] mAttributes = new HashMap[EXIF_TAGS.length]; private ByteOrder mExifByteOrder = ByteOrder.BIG_ENDIAN; private boolean mHasThumbnail; // The following values used for indicating a thumbnail position. private int mThumbnailOffset; private int mThumbnailLength; private byte[] mThumbnailBytes; private int mThumbnailCompression; private int mExifOffset; private int mOrfMakerNoteOffset; private int mOrfThumbnailOffset; private int mOrfThumbnailLength; private int mRw2JpgFromRawOffset; private boolean mIsSupportedFile; // Pattern to check non zero timestamp private static final Pattern sNonZeroTimePattern = Pattern.compile(".*[1-9].*"); // Pattern to check gps timestamp private static final Pattern sGpsTimestampPattern = Pattern.compile("^([0-9][0-9]):([0-9][0-9]):([0-9][0-9])$"); /** * Reads Exif tags from the specified image file. */ public ExifInterface(@NonNull String filename) throws IOException { if (filename == null) { throw new IllegalArgumentException("filename cannot be null"); } FileInputStream in = null; mAssetInputStream = null; mFilename = filename; try { in = new FileInputStream(filename); loadAttributes(in); } finally { closeQuietly(in); } } /** * Reads Exif tags from the specified image input stream. Attribute mutation is not supported * for input streams. The given input stream will proceed its current position. Developers * should close the input stream after use. This constructor is not intended to be used with * an input stream that performs any networking operations. */ public ExifInterface(@NonNull InputStream inputStream) throws IOException { if (inputStream == null) { throw new IllegalArgumentException("inputStream cannot be null"); } mFilename = null; if (inputStream instanceof AssetManager.AssetInputStream) { mAssetInputStream = (AssetManager.AssetInputStream) inputStream; } else { mAssetInputStream = null; } loadAttributes(inputStream); } /** * Returns the EXIF attribute of the specified tag or {@code null} if there is no such tag in * the image file. * * @param tag the name of the tag. */ @Nullable private ExifAttribute getExifAttribute(@NonNull String tag) { if (TAG_ISO_SPEED_RATINGS.equals(tag)) { if (DEBUG) { Log.d(TAG, "getExifAttribute: Replacing TAG_ISO_SPEED_RATINGS with " + "TAG_PHOTOGRAPHIC_SENSITIVITY."); } tag = TAG_PHOTOGRAPHIC_SENSITIVITY; } // Retrieves all tag groups. The value from primary image tag group has a higher priority // than the value from the thumbnail tag group if there are more than one candidates. for (int i = 0; i < EXIF_TAGS.length; ++i) { ExifAttribute value = mAttributes[i].get(tag); if (value != null) { return value; } } return null; } /** * Returns the value of the specified tag or {@code null} if there * is no such tag in the image file. * * @param tag the name of the tag. */ @Nullable public String getAttribute(@NonNull String tag) { ExifAttribute attribute = getExifAttribute(tag); if (attribute != null) { if (!sTagSetForCompatibility.contains(tag)) { return attribute.getStringValue(mExifByteOrder); } if (tag.equals(TAG_GPS_TIMESTAMP)) { // Convert the rational values to the custom formats for backwards compatibility. if (attribute.format != IFD_FORMAT_URATIONAL && attribute.format != IFD_FORMAT_SRATIONAL) { Log.w(TAG, "GPS Timestamp format is not rational. format=" + attribute.format); return null; } Rational[] array = (Rational[]) attribute.getValue(mExifByteOrder); if (array == null || array.length != 3) { Log.w(TAG, "Invalid GPS Timestamp array. array=" + Arrays.toString(array)); return null; } return String.format("%02d:%02d:%02d", (int) ((float) array[0].numerator / array[0].denominator), (int) ((float) array[1].numerator / array[1].denominator), (int) ((float) array[2].numerator / array[2].denominator)); } try { return Double.toString(attribute.getDoubleValue(mExifByteOrder)); } catch (NumberFormatException e) { return null; } } return null; } /** * Returns the integer value of the specified tag. If there is no such tag * in the image file or the value cannot be parsed as integer, return * <var>defaultValue</var>. * * @param tag the name of the tag. * @param defaultValue the value to return if the tag is not available. */ public int getAttributeInt(@NonNull String tag, int defaultValue) { ExifAttribute exifAttribute = getExifAttribute(tag); if (exifAttribute == null) { return defaultValue; } try { return exifAttribute.getIntValue(mExifByteOrder); } catch (NumberFormatException e) { return defaultValue; } } /** * Returns the double value of the tag that is specified as rational or contains a * double-formatted value. If there is no such tag in the image file or the value cannot be * parsed as double, return <var>defaultValue</var>. * * @param tag the name of the tag. * @param defaultValue the value to return if the tag is not available. */ public double getAttributeDouble(@NonNull String tag, double defaultValue) { ExifAttribute exifAttribute = getExifAttribute(tag); if (exifAttribute == null) { return defaultValue; } try { return exifAttribute.getDoubleValue(mExifByteOrder); } catch (NumberFormatException e) { return defaultValue; } } /** * Sets the value of the specified tag. * * @param tag the name of the tag. * @param value the value of the tag. */ public void setAttribute(@NonNull String tag, @Nullable String value) { if (TAG_ISO_SPEED_RATINGS.equals(tag)) { if (DEBUG) { Log.d(TAG, "setAttribute: Replacing TAG_ISO_SPEED_RATINGS with " + "TAG_PHOTOGRAPHIC_SENSITIVITY."); } tag = TAG_PHOTOGRAPHIC_SENSITIVITY; } // Convert the given value to rational values for backwards compatibility. if (value != null && sTagSetForCompatibility.contains(tag)) { if (tag.equals(TAG_GPS_TIMESTAMP)) { Matcher m = sGpsTimestampPattern.matcher(value); if (!m.find()) { Log.w(TAG, "Invalid value for " + tag + " : " + value); return; } value = Integer.parseInt(m.group(1)) + "/1," + Integer.parseInt(m.group(2)) + "/1," + Integer.parseInt(m.group(3)) + "/1"; } else { try { double doubleValue = Double.parseDouble(value); value = new Rational(doubleValue).toString(); } catch (NumberFormatException e) { Log.w(TAG, "Invalid value for " + tag + " : " + value); return; } } } for (int i = 0 ; i < EXIF_TAGS.length; ++i) { if (i == IFD_TYPE_THUMBNAIL && !mHasThumbnail) { continue; } final ExifTag exifTag = sExifTagMapsForWriting[i].get(tag); if (exifTag != null) { if (value == null) { mAttributes[i].remove(tag); continue; } Pair<Integer, Integer> guess = guessDataFormat(value); int dataFormat; if (exifTag.primaryFormat == guess.first || exifTag.primaryFormat == guess.second) { dataFormat = exifTag.primaryFormat; } else if (exifTag.secondaryFormat != -1 && (exifTag.secondaryFormat == guess.first || exifTag.secondaryFormat == guess.second)) { dataFormat = exifTag.secondaryFormat; } else if (exifTag.primaryFormat == IFD_FORMAT_BYTE || exifTag.primaryFormat == IFD_FORMAT_UNDEFINED || exifTag.primaryFormat == IFD_FORMAT_STRING) { dataFormat = exifTag.primaryFormat; } else { Log.w(TAG, "Given tag (" + tag + ") value didn't match with one of expected " + "formats: " + IFD_FORMAT_NAMES[exifTag.primaryFormat] + (exifTag.secondaryFormat == -1 ? "" : ", " + IFD_FORMAT_NAMES[exifTag.secondaryFormat]) + " (guess: " + IFD_FORMAT_NAMES[guess.first] + (guess.second == -1 ? "" : ", " + IFD_FORMAT_NAMES[guess.second]) + ")"); continue; } switch (dataFormat) { case IFD_FORMAT_BYTE: { mAttributes[i].put(tag, ExifAttribute.createByte(value)); break; } case IFD_FORMAT_UNDEFINED: case IFD_FORMAT_STRING: { mAttributes[i].put(tag, ExifAttribute.createString(value)); break; } case IFD_FORMAT_USHORT: { final String[] values = value.split(","); final int[] intArray = new int[values.length]; for (int j = 0; j < values.length; ++j) { intArray[j] = Integer.parseInt(values[j]); } mAttributes[i].put(tag, ExifAttribute.createUShort(intArray, mExifByteOrder)); break; } case IFD_FORMAT_SLONG: { final String[] values = value.split(","); final int[] intArray = new int[values.length]; for (int j = 0; j < values.length; ++j) { intArray[j] = Integer.parseInt(values[j]); } mAttributes[i].put(tag, ExifAttribute.createSLong(intArray, mExifByteOrder)); break; } case IFD_FORMAT_ULONG: { final String[] values = value.split(","); final long[] longArray = new long[values.length]; for (int j = 0; j < values.length; ++j) { longArray[j] = Long.parseLong(values[j]); } mAttributes[i].put(tag, ExifAttribute.createULong(longArray, mExifByteOrder)); break; } case IFD_FORMAT_URATIONAL: { final String[] values = value.split(","); final Rational[] rationalArray = new Rational[values.length]; for (int j = 0; j < values.length; ++j) { final String[] numbers = values[j].split("/"); rationalArray[j] = new Rational((long) Double.parseDouble(numbers[0]), (long) Double.parseDouble(numbers[1])); } mAttributes[i].put(tag, ExifAttribute.createURational(rationalArray, mExifByteOrder)); break; } case IFD_FORMAT_SRATIONAL: { final String[] values = value.split(","); final Rational[] rationalArray = new Rational[values.length]; for (int j = 0; j < values.length; ++j) { final String[] numbers = values[j].split("/"); rationalArray[j] = new Rational((long) Double.parseDouble(numbers[0]), (long) Double.parseDouble(numbers[1])); } mAttributes[i].put(tag, ExifAttribute.createSRational(rationalArray, mExifByteOrder)); break; } case IFD_FORMAT_DOUBLE: { final String[] values = value.split(","); final double[] doubleArray = new double[values.length]; for (int j = 0; j < values.length; ++j) { doubleArray[j] = Double.parseDouble(values[j]); } mAttributes[i].put(tag, ExifAttribute.createDouble(doubleArray, mExifByteOrder)); break; } default: Log.w(TAG, "Data format isn't one of expected formats: " + dataFormat); continue; } } } } /** * Resets the {@link #TAG_ORIENTATION} of the image to be {@link #ORIENTATION_NORMAL}. */ public void resetOrientation() { setAttribute(TAG_ORIENTATION, Integer.toString(ORIENTATION_NORMAL)); } /** * Rotates the image by the given degree clockwise. The degree should be a multiple of * 90 (e.g, 90, 180, -90, etc.). * * @param degree The degree of rotation. */ public void rotate(int degree) { if (degree % 90 !=0) { throw new IllegalArgumentException("degree should be a multiple of 90"); } int currentOrientation = getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL); int currentIndex, newIndex; int resultOrientation; if (ROTATION_ORDER.contains(currentOrientation)) { currentIndex = ROTATION_ORDER.indexOf(currentOrientation); newIndex = (currentIndex + degree / 90) % 4; newIndex += newIndex < 0 ? 4 : 0; resultOrientation = ROTATION_ORDER.get(newIndex); } else if (FLIPPED_ROTATION_ORDER.contains(currentOrientation)) { currentIndex = FLIPPED_ROTATION_ORDER.indexOf(currentOrientation); newIndex = (currentIndex + degree / 90) % 4; newIndex += newIndex < 0 ? 4 : 0; resultOrientation = FLIPPED_ROTATION_ORDER.get(newIndex); } else { resultOrientation = ORIENTATION_UNDEFINED; } setAttribute(TAG_ORIENTATION, Integer.toString(resultOrientation)); } /** * Flips the image vertically. */ public void flipVertically() { int currentOrientation = getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL); int resultOrientation; switch (currentOrientation) { case ORIENTATION_FLIP_HORIZONTAL: resultOrientation = ORIENTATION_ROTATE_180; break; case ORIENTATION_ROTATE_180: resultOrientation = ORIENTATION_FLIP_HORIZONTAL; break; case ORIENTATION_FLIP_VERTICAL: resultOrientation = ORIENTATION_NORMAL; break; case ORIENTATION_TRANSPOSE: resultOrientation = ORIENTATION_ROTATE_270; break; case ORIENTATION_ROTATE_90: resultOrientation = ORIENTATION_TRANSVERSE; break; case ORIENTATION_TRANSVERSE: resultOrientation = ORIENTATION_ROTATE_90; break; case ORIENTATION_ROTATE_270: resultOrientation = ORIENTATION_TRANSPOSE; break; case ORIENTATION_NORMAL: resultOrientation = ORIENTATION_FLIP_VERTICAL; break; case ORIENTATION_UNDEFINED: default: resultOrientation = ORIENTATION_UNDEFINED; break; } setAttribute(TAG_ORIENTATION, Integer.toString(resultOrientation)); } /** * Flips the image horizontally. */ public void flipHorizontally() { int currentOrientation = getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL); int resultOrientation; switch (currentOrientation) { case ORIENTATION_FLIP_HORIZONTAL: resultOrientation = ORIENTATION_NORMAL; break; case ORIENTATION_ROTATE_180: resultOrientation = ORIENTATION_FLIP_VERTICAL; break; case ORIENTATION_FLIP_VERTICAL: resultOrientation = ORIENTATION_ROTATE_180; break; case ORIENTATION_TRANSPOSE: resultOrientation = ORIENTATION_ROTATE_90; break; case ORIENTATION_ROTATE_90: resultOrientation = ORIENTATION_TRANSPOSE; break; case ORIENTATION_TRANSVERSE: resultOrientation = ORIENTATION_ROTATE_270; break; case ORIENTATION_ROTATE_270: resultOrientation = ORIENTATION_TRANSVERSE; break; case ORIENTATION_NORMAL: resultOrientation = ORIENTATION_FLIP_HORIZONTAL; break; case ORIENTATION_UNDEFINED: default: resultOrientation = ORIENTATION_UNDEFINED; break; } setAttribute(TAG_ORIENTATION, Integer.toString(resultOrientation)); } /** * Returns if the current image orientation is flipped. * * @see #getRotationDegrees() */ public boolean isFlipped() { int orientation = getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL); switch (orientation) { case ORIENTATION_FLIP_HORIZONTAL: case ORIENTATION_TRANSVERSE: case ORIENTATION_FLIP_VERTICAL: case ORIENTATION_TRANSPOSE: return true; default: return false; } } /** * Returns the rotation degrees for the current image orientation. If the image is flipped, * i.e., {@link #isFlipped()} returns {@code true}, the rotation degrees will be base on * the assumption that the image is first flipped horizontally (along Y-axis), and then do * the rotation. For example, {@link #ORIENTATION_TRANSPOSE} will be interpreted as flipped * horizontally first, and then rotate 270 degrees clockwise. * * @return The rotation degrees of the image after the horizontal flipping is applied, if any. * * @see #isFlipped() */ public int getRotationDegrees() { int orientation = getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL); switch (orientation) { case ORIENTATION_ROTATE_90: case ORIENTATION_TRANSVERSE: return 90; case ORIENTATION_ROTATE_180: case ORIENTATION_FLIP_VERTICAL: return 180; case ORIENTATION_ROTATE_270: case ORIENTATION_TRANSPOSE: return 270; case ORIENTATION_UNDEFINED: case ORIENTATION_NORMAL: case ORIENTATION_FLIP_HORIZONTAL: default: return 0; } } /** * Update the values of the tags in the tag groups if any value for the tag already was stored. * * @param tag the name of the tag. * @param value the value of the tag in a form of {@link ExifAttribute}. * @return Returns {@code true} if updating is placed. */ private boolean updateAttribute(String tag, ExifAttribute value) { boolean updated = false; for (int i = 0 ; i < EXIF_TAGS.length; ++i) { if (mAttributes[i].containsKey(tag)) { mAttributes[i].put(tag, value); updated = true; } } return updated; } /** * Remove any values of the specified tag. * * @param tag the name of the tag. */ private void removeAttribute(String tag) { for (int i = 0 ; i < EXIF_TAGS.length; ++i) { mAttributes[i].remove(tag); } } /** * This function decides which parser to read the image data according to the given input stream * type and the content of the input stream. In each case, it reads the first three bytes to * determine whether the image data format is JPEG or not. */ private void loadAttributes(@NonNull InputStream in) throws IOException { try { // Initialize mAttributes. for (int i = 0; i < EXIF_TAGS.length; ++i) { mAttributes[i] = new HashMap<>(); } // Check file type in = new BufferedInputStream(in, SIGNATURE_CHECK_SIZE); mMimeType = getMimeType((BufferedInputStream) in); // Create byte-ordered input stream ByteOrderedDataInputStream inputStream = new ByteOrderedDataInputStream(in); switch (mMimeType) { case IMAGE_TYPE_JPEG: { getJpegAttributes(inputStream, 0, IFD_TYPE_PRIMARY); // 0 is offset break; } case IMAGE_TYPE_RAF: { getRafAttributes(inputStream); break; } case IMAGE_TYPE_ORF: { getOrfAttributes(inputStream); break; } case IMAGE_TYPE_RW2: { getRw2Attributes(inputStream); break; } case IMAGE_TYPE_ARW: case IMAGE_TYPE_CR2: case IMAGE_TYPE_DNG: case IMAGE_TYPE_NEF: case IMAGE_TYPE_NRW: case IMAGE_TYPE_PEF: case IMAGE_TYPE_SRW: case IMAGE_TYPE_UNKNOWN: { getRawAttributes(inputStream); break; } default: { break; } } // Set thumbnail image offset and length setThumbnailData(inputStream); mIsSupportedFile = true; } catch (IOException e) { // Ignore exceptions in order to keep the compatibility with the old versions of // ExifInterface. mIsSupportedFile = false; if (DEBUG) { Log.w(TAG, "Invalid image: ExifInterface got an unsupported image format file" + "(ExifInterface supports JPEG and some RAW image formats only) " + "or a corrupted JPEG file to ExifInterface.", e); } } finally { addDefaultValuesForCompatibility(); if (DEBUG) { printAttributes(); } } } // Prints out attributes for debugging. private void printAttributes() { for (int i = 0; i < mAttributes.length; ++i) { Log.d(TAG, "The size of tag group[" + i + "]: " + mAttributes[i].size()); for (Map.Entry<String, ExifAttribute> entry : mAttributes[i].entrySet()) { final ExifAttribute tagValue = entry.getValue(); Log.d(TAG, "tagName: " + entry.getKey() + ", tagType: " + tagValue.toString() + ", tagValue: '" + tagValue.getStringValue(mExifByteOrder) + "'"); } } } /** * Save the tag data into the original image file. This is expensive because it involves * copying all the data from one file to another and deleting the old file and renaming the * other. It's best to use {@link #setAttribute(String,String)} to set all attributes to write * and make a single call rather than multiple calls for each attribute. * <p> * This method is only supported for JPEG files. * </p> */ public void saveAttributes() throws IOException { if (!mIsSupportedFile || mMimeType != IMAGE_TYPE_JPEG) { throw new IOException("ExifInterface only supports saving attributes on JPEG formats."); } if (mFilename == null) { throw new IOException( "ExifInterface does not support saving attributes for the current input."); } // Keep the thumbnail in memory mThumbnailBytes = getThumbnail(); File tempFile = new File(mFilename + ".tmp"); File originalFile = new File(mFilename); if (!originalFile.renameTo(tempFile)) { throw new IOException("Could not rename to " + tempFile.getAbsolutePath()); } FileInputStream in = null; FileOutputStream out = null; try { // Save the new file. in = new FileInputStream(tempFile); out = new FileOutputStream(mFilename); saveJpegAttributes(in, out); } finally { closeQuietly(in); closeQuietly(out); tempFile.delete(); } // Discard the thumbnail in memory mThumbnailBytes = null; } /** * Returns true if the image file has a thumbnail. */ public boolean hasThumbnail() { return mHasThumbnail; } /** * Returns the JPEG compressed thumbnail inside the image file, or {@code null} if there is no * JPEG compressed thumbnail. * The returned data can be decoded using * {@link android.graphics.BitmapFactory#decodeByteArray(byte[],int,int)} */ @Nullable public byte[] getThumbnail() { if (mThumbnailCompression == DATA_JPEG || mThumbnailCompression == DATA_JPEG_COMPRESSED) { return getThumbnailBytes(); } return null; } /** * Returns the thumbnail bytes inside the image file, regardless of the compression type of the * thumbnail image. */ @Nullable public byte[] getThumbnailBytes() { if (!mHasThumbnail) { return null; } if (mThumbnailBytes != null) { return mThumbnailBytes; } // Read the thumbnail. InputStream in = null; try { if (mAssetInputStream != null) { in = mAssetInputStream; if (in.markSupported()) { in.reset(); } else { Log.d(TAG, "Cannot read thumbnail from inputstream without mark/reset support"); return null; } } else if (mFilename != null) { in = new FileInputStream(mFilename); } if (in == null) { // Should not be reached this. throw new FileNotFoundException(); } if (in.skip(mThumbnailOffset) != mThumbnailOffset) { throw new IOException("Corrupted image"); } byte[] buffer = new byte[mThumbnailLength]; if (in.read(buffer) != mThumbnailLength) { throw new IOException("Corrupted image"); } mThumbnailBytes = buffer; return buffer; } catch (IOException e) { // Couldn't get a thumbnail image. Log.d(TAG, "Encountered exception while getting thumbnail", e); } finally { closeQuietly(in); } return null; } /** * Creates and returns a Bitmap object of the thumbnail image based on the byte array and the * thumbnail compression value, or {@code null} if the compression type is unsupported. */ @Nullable public Bitmap getThumbnailBitmap() { if (!mHasThumbnail) { return null; } else if (mThumbnailBytes == null) { mThumbnailBytes = getThumbnailBytes(); } if (mThumbnailCompression == DATA_JPEG || mThumbnailCompression == DATA_JPEG_COMPRESSED) { return BitmapFactory.decodeByteArray(mThumbnailBytes, 0, mThumbnailLength); } else if (mThumbnailCompression == DATA_UNCOMPRESSED) { int[] rgbValues = new int[mThumbnailBytes.length / 3]; byte alpha = (byte) 0xff000000; for (int i = 0; i < rgbValues.length; i++) { rgbValues[i] = alpha + (mThumbnailBytes[3 * i] << 16) + (mThumbnailBytes[3 * i + 1] << 8) + mThumbnailBytes[3 * i + 2]; } ExifAttribute imageLengthAttribute = (ExifAttribute) mAttributes[IFD_TYPE_THUMBNAIL].get(TAG_IMAGE_LENGTH); ExifAttribute imageWidthAttribute = (ExifAttribute) mAttributes[IFD_TYPE_THUMBNAIL].get(TAG_IMAGE_WIDTH); if (imageLengthAttribute != null && imageWidthAttribute != null) { int imageLength = imageLengthAttribute.getIntValue(mExifByteOrder); int imageWidth = imageWidthAttribute.getIntValue(mExifByteOrder); return Bitmap.createBitmap( rgbValues, imageWidth, imageLength, Bitmap.Config.ARGB_8888); } } return null; } /** * Returns true if thumbnail image is JPEG Compressed, or false if either thumbnail image does * not exist or thumbnail image is uncompressed. */ public boolean isThumbnailCompressed() { return mThumbnailCompression == DATA_JPEG || mThumbnailCompression == DATA_JPEG_COMPRESSED; } /** * Returns the offset and length of thumbnail inside the image file, or * {@code null} if there is no thumbnail. * * @return two-element array, the offset in the first value, and length in * the second, or {@code null} if no thumbnail was found. */ @Nullable public long[] getThumbnailRange() { if (!mHasThumbnail) { return null; } long[] range = new long[2]; range[0] = mThumbnailOffset; range[1] = mThumbnailLength; return range; } /** * Stores the latitude and longitude value in a float array. The first element is the latitude, * and the second element is the longitude. Returns false if the Exif tags are not available. * * @deprecated Use {@link #getLatLong()} instead. */ @Deprecated public boolean getLatLong(float output[]) { double[] latLong = getLatLong(); if (latLong == null) { return false; } output[0] = (float) latLong[0]; output[1] = (float) latLong[1]; return true; } /** * Gets the latitude and longitude values. * <p> * If there are valid latitude and longitude values in the image, this method returns a double * array where the first element is the latitude and the second element is the longitude. * Otherwise, it returns null. */ @Nullable public double[] getLatLong() { String latValue = getAttribute(TAG_GPS_LATITUDE); String latRef = getAttribute(TAG_GPS_LATITUDE_REF); String lngValue = getAttribute(TAG_GPS_LONGITUDE); String lngRef = getAttribute(TAG_GPS_LONGITUDE_REF); if (latValue != null && latRef != null && lngValue != null && lngRef != null) { try { double latitude = convertRationalLatLonToDouble(latValue, latRef); double longitude = convertRationalLatLonToDouble(lngValue, lngRef); return new double[] {latitude, longitude}; } catch (IllegalArgumentException e) { Log.w(TAG, "Latitude/longitude values are not parseable. " + String.format("latValue=%s, latRef=%s, lngValue=%s, lngRef=%s", latValue, latRef, lngValue, lngRef)); } } return null; } /** * Sets the GPS-related information. It will set GPS processing method, latitude and longitude * values, GPS timestamp, and speed information at the same time. * * @param location the {@link Location} object returned by GPS service. */ public void setGpsInfo(Location location) { if (location == null) { return; } setAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD, location.getProvider()); setLatLong(location.getLatitude(), location.getLongitude()); setAltitude(location.getAltitude()); // Location objects store speeds in m/sec. Translates it to km/hr here. setAttribute(TAG_GPS_SPEED_REF, "K"); setAttribute(TAG_GPS_SPEED, new Rational(location.getSpeed() * TimeUnit.HOURS.toSeconds(1) / 1000).toString()); String[] dateTime = sFormatter.format(new Date(location.getTime())).split("\\s+"); setAttribute(ExifInterface.TAG_GPS_DATESTAMP, dateTime[0]); setAttribute(ExifInterface.TAG_GPS_TIMESTAMP, dateTime[1]); } /** * Sets the latitude and longitude values. * * @param latitude the decimal value of latitude. Must be a valid double value between -90.0 and * 90.0. * @param longitude the decimal value of longitude. Must be a valid double value between -180.0 * and 180.0. * @throws IllegalArgumentException If {@code latitude} or {@code longitude} is outside the * specified range. */ public void setLatLong(double latitude, double longitude) { if (latitude < -90.0 || latitude > 90.0 || Double.isNaN(latitude)) { throw new IllegalArgumentException("Latitude value " + latitude + " is not valid."); } if (longitude < -180.0 || longitude > 180.0 || Double.isNaN(longitude)) { throw new IllegalArgumentException("Longitude value " + longitude + " is not valid."); } setAttribute(TAG_GPS_LATITUDE_REF, latitude >= 0 ? "N" : "S"); setAttribute(TAG_GPS_LATITUDE, convertDecimalDegree(Math.abs(latitude))); setAttribute(TAG_GPS_LONGITUDE_REF, longitude >= 0 ? "E" : "W"); setAttribute(TAG_GPS_LONGITUDE, convertDecimalDegree(Math.abs(longitude))); } /** * Return the altitude in meters. If the exif tag does not exist, return * <var>defaultValue</var>. * * @param defaultValue the value to return if the tag is not available. */ public double getAltitude(double defaultValue) { double altitude = getAttributeDouble(TAG_GPS_ALTITUDE, -1); int ref = getAttributeInt(TAG_GPS_ALTITUDE_REF, -1); if (altitude >= 0 && ref >= 0) { return (altitude * ((ref == 1) ? -1 : 1)); } else { return defaultValue; } } /** * Sets the altitude in meters. */ public void setAltitude(double altitude) { String ref = altitude >= 0 ? "0" : "1"; setAttribute(TAG_GPS_ALTITUDE, new Rational(Math.abs(altitude)).toString()); setAttribute(TAG_GPS_ALTITUDE_REF, ref); } /** * Set the date time value. * * @param timeStamp number of milliseconds since Jan. 1, 1970, midnight local time. * @hide */ public void setDateTime(long timeStamp) { long sub = timeStamp % 1000; setAttribute(TAG_DATETIME, sFormatter.format(new Date(timeStamp))); setAttribute(TAG_SUBSEC_TIME, Long.toString(sub)); } /** * Returns number of milliseconds since Jan. 1, 1970, midnight local time. * Returns -1 if the date time information if not available. * @hide */ public long getDateTime() { String dateTimeString = getAttribute(TAG_DATETIME); if (dateTimeString == null || !sNonZeroTimePattern.matcher(dateTimeString).matches()) return -1; ParsePosition pos = new ParsePosition(0); try { // The exif field is in local time. Parsing it as if it is UTC will yield time // since 1/1/1970 local time Date datetime = sFormatter.parse(dateTimeString, pos); if (datetime == null) return -1; long msecs = datetime.getTime(); String subSecs = getAttribute(TAG_SUBSEC_TIME); if (subSecs != null) { try { long sub = Long.parseLong(subSecs); while (sub > 1000) { sub /= 10; } msecs += sub; } catch (NumberFormatException e) { // Ignored } } return msecs; } catch (IllegalArgumentException e) { return -1; } } /** * Returns number of milliseconds since Jan. 1, 1970, midnight UTC. * Returns -1 if the date time information if not available. * @hide */ public long getGpsDateTime() { String date = getAttribute(TAG_GPS_DATESTAMP); String time = getAttribute(TAG_GPS_TIMESTAMP); if (date == null || time == null || (!sNonZeroTimePattern.matcher(date).matches() && !sNonZeroTimePattern.matcher(time).matches())) { return -1; } String dateTimeString = date + ' ' + time; ParsePosition pos = new ParsePosition(0); try { Date datetime = sFormatter.parse(dateTimeString, pos); if (datetime == null) return -1; return datetime.getTime(); } catch (IllegalArgumentException e) { return -1; } } private static double convertRationalLatLonToDouble(String rationalString, String ref) { try { String [] parts = rationalString.split(","); String [] pair; pair = parts[0].split("/"); double degrees = Double.parseDouble(pair[0].trim()) / Double.parseDouble(pair[1].trim()); pair = parts[1].split("/"); double minutes = Double.parseDouble(pair[0].trim()) / Double.parseDouble(pair[1].trim()); pair = parts[2].split("/"); double seconds = Double.parseDouble(pair[0].trim()) / Double.parseDouble(pair[1].trim()); double result = degrees + (minutes / 60.0) + (seconds / 3600.0); if ((ref.equals("S") || ref.equals("W"))) { return -result; } else if (ref.equals("N") || ref.equals("E")) { return result; } else { // Not valid throw new IllegalArgumentException(); } } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { // Not valid throw new IllegalArgumentException(); } } private String convertDecimalDegree(double decimalDegree) { long degrees = (long) decimalDegree; long minutes = (long) ((decimalDegree - degrees) * 60.0); long seconds = Math.round((decimalDegree - degrees - minutes / 60.0) * 3600.0 * 1e7); return degrees + "/1," + minutes + "/1," + seconds + "/10000000"; } // Checks the type of image file private int getMimeType(BufferedInputStream in) throws IOException { in.mark(SIGNATURE_CHECK_SIZE); byte[] signatureCheckBytes = new byte[SIGNATURE_CHECK_SIZE]; if (in.read(signatureCheckBytes) != SIGNATURE_CHECK_SIZE) { throw new EOFException(); } in.reset(); if (isJpegFormat(signatureCheckBytes)) { return IMAGE_TYPE_JPEG; } else if (isRafFormat(signatureCheckBytes)) { return IMAGE_TYPE_RAF; } else if (isOrfFormat(signatureCheckBytes)) { return IMAGE_TYPE_ORF; } else if (isRw2Format(signatureCheckBytes)) { return IMAGE_TYPE_RW2; } // Certain file formats (PEF) are identified in readImageFileDirectory() return IMAGE_TYPE_UNKNOWN; } /** * This method looks at the first 3 bytes to determine if this file is a JPEG file. * See http://www.media.mit.edu/pia/Research/deepview/exif.html, "JPEG format and Marker" */ private static boolean isJpegFormat(byte[] signatureCheckBytes) throws IOException { for (int i = 0; i < JPEG_SIGNATURE.length; i++) { if (signatureCheckBytes[i] != JPEG_SIGNATURE[i]) { return false; } } return true; } /** * This method looks at the first 15 bytes to determine if this file is a RAF file. * There is no official specification for RAF files from Fuji, but there is an online archive of * image file specifications: * http://fileformats.archiveteam.org/wiki/Fujifilm_RAF */ private boolean isRafFormat(byte[] signatureCheckBytes) throws IOException { byte[] rafSignatureBytes = RAF_SIGNATURE.getBytes(Charset.defaultCharset()); for (int i = 0; i < rafSignatureBytes.length; i++) { if (signatureCheckBytes[i] != rafSignatureBytes[i]) { return false; } } return true; } /** * ORF has a similar structure to TIFF but it contains a different signature at the TIFF Header. * This method looks at the 2 bytes following the Byte Order bytes to determine if this file is * an ORF file. * There is no official specification for ORF files from Olympus, but there is an online archive * of image file specifications: * http://fileformats.archiveteam.org/wiki/Olympus_ORF */ private boolean isOrfFormat(byte[] signatureCheckBytes) throws IOException { ByteOrderedDataInputStream signatureInputStream = new ByteOrderedDataInputStream(signatureCheckBytes); // Read byte order mExifByteOrder = readByteOrder(signatureInputStream); // Set byte order signatureInputStream.setByteOrder(mExifByteOrder); short orfSignature = signatureInputStream.readShort(); signatureInputStream.close(); return orfSignature == ORF_SIGNATURE_1 || orfSignature == ORF_SIGNATURE_2; } /** * RW2 is TIFF-based, but stores 0x55 signature byte instead of 0x42 at the header * See http://lclevy.free.fr/raw/ */ private boolean isRw2Format(byte[] signatureCheckBytes) throws IOException { ByteOrderedDataInputStream signatureInputStream = new ByteOrderedDataInputStream(signatureCheckBytes); // Read byte order mExifByteOrder = readByteOrder(signatureInputStream); // Set byte order signatureInputStream.setByteOrder(mExifByteOrder); short signatureByte = signatureInputStream.readShort(); signatureInputStream.close(); return signatureByte == RW2_SIGNATURE; } /** * Loads EXIF attributes from a JPEG input stream. * * @param in The input stream that starts with the JPEG data. * @param jpegOffset The offset value in input stream for JPEG data. * @param imageType The image type from which to retrieve metadata. Use IFD_TYPE_PRIMARY for * primary image, IFD_TYPE_PREVIEW for preview image, and * IFD_TYPE_THUMBNAIL for thumbnail image. * @throws IOException If the data contains invalid JPEG markers, offsets, or length values. */ private void getJpegAttributes(ByteOrderedDataInputStream in, int jpegOffset, int imageType) throws IOException { // See JPEG File Interchange Format Specification, "JFIF Specification" if (DEBUG) { Log.d(TAG, "getJpegAttributes starting with: " + in); } // JPEG uses Big Endian by default. See https://people.cs.umass.edu/~verts/cs32/endian.html in.setByteOrder(ByteOrder.BIG_ENDIAN); // Skip to JPEG data in.seek(jpegOffset); int bytesRead = jpegOffset; byte marker; if ((marker = in.readByte()) != MARKER) { throw new IOException("Invalid marker: " + Integer.toHexString(marker & 0xff)); } ++bytesRead; if (in.readByte() != MARKER_SOI) { throw new IOException("Invalid marker: " + Integer.toHexString(marker & 0xff)); } ++bytesRead; while (true) { marker = in.readByte(); if (marker != MARKER) { throw new IOException("Invalid marker:" + Integer.toHexString(marker & 0xff)); } ++bytesRead; marker = in.readByte(); if (DEBUG) { Log.d(TAG, "Found JPEG segment indicator: " + Integer.toHexString(marker & 0xff)); } ++bytesRead; // EOI indicates the end of an image and in case of SOS, JPEG image stream starts and // the image data will terminate right after. if (marker == MARKER_EOI || marker == MARKER_SOS) { break; } int length = in.readUnsignedShort() - 2; bytesRead += 2; if (DEBUG) { Log.d(TAG, "JPEG segment: " + Integer.toHexString(marker & 0xff) + " (length: " + (length + 2) + ")"); } if (length < 0) { throw new IOException("Invalid length"); } switch (marker) { case MARKER_APP1: { if (DEBUG) { Log.d(TAG, "MARKER_APP1"); } if (length < 6) { // Skip if it's not an EXIF APP1 segment. break; } byte[] identifier = new byte[6]; if (in.read(identifier) != 6) { throw new IOException("Invalid exif"); } bytesRead += 6; length -= 6; if (!Arrays.equals(identifier, IDENTIFIER_EXIF_APP1)) { // Skip if it's not an EXIF APP1 segment. break; } if (length <= 0) { throw new IOException("Invalid exif"); } if (DEBUG) { Log.d(TAG, "readExifSegment with a byte array (length: " + length + ")"); } // Save offset values for createJpegThumbnailBitmap() function mExifOffset = bytesRead; byte[] bytes = new byte[length]; if (in.read(bytes) != length) { throw new IOException("Invalid exif"); } bytesRead += length; length = 0; readExifSegment(bytes, imageType); break; } case MARKER_COM: { byte[] bytes = new byte[length]; if (in.read(bytes) != length) { throw new IOException("Invalid exif"); } length = 0; if (getAttribute(TAG_USER_COMMENT) == null) { mAttributes[IFD_TYPE_EXIF].put(TAG_USER_COMMENT, ExifAttribute.createString( new String(bytes, ASCII))); } break; } case MARKER_SOF0: case MARKER_SOF1: case MARKER_SOF2: case MARKER_SOF3: case MARKER_SOF5: case MARKER_SOF6: case MARKER_SOF7: case MARKER_SOF9: case MARKER_SOF10: case MARKER_SOF11: case MARKER_SOF13: case MARKER_SOF14: case MARKER_SOF15: { if (in.skipBytes(1) != 1) { throw new IOException("Invalid SOFx"); } mAttributes[imageType].put(TAG_IMAGE_LENGTH, ExifAttribute.createULong( in.readUnsignedShort(), mExifByteOrder)); mAttributes[imageType].put(TAG_IMAGE_WIDTH, ExifAttribute.createULong( in.readUnsignedShort(), mExifByteOrder)); length -= 5; break; } default: { break; } } if (length < 0) { throw new IOException("Invalid length"); } if (in.skipBytes(length) != length) { throw new IOException("Invalid JPEG segment"); } bytesRead += length; } // Restore original byte order in.setByteOrder(mExifByteOrder); } private void getRawAttributes(ByteOrderedDataInputStream in) throws IOException { // Parse TIFF Headers. See JEITA CP-3451C Section 4.5.2. Table 1. parseTiffHeaders(in, in.available()); // Read TIFF image file directories. See JEITA CP-3451C Section 4.5.2. Figure 6. readImageFileDirectory(in, IFD_TYPE_PRIMARY); // Update ImageLength/Width tags for all image data. updateImageSizeValues(in, IFD_TYPE_PRIMARY); updateImageSizeValues(in, IFD_TYPE_PREVIEW); updateImageSizeValues(in, IFD_TYPE_THUMBNAIL); // Check if each image data is in valid position. validateImages(in); if (mMimeType == IMAGE_TYPE_PEF) { // PEF files contain a MakerNote data, which contains the data for ColorSpace tag. // See http://lclevy.free.fr/raw/ and piex.cc PefGetPreviewData() ExifAttribute makerNoteAttribute = (ExifAttribute) mAttributes[IFD_TYPE_EXIF].get(TAG_MAKER_NOTE); if (makerNoteAttribute != null) { // Create an ordered DataInputStream for MakerNote ByteOrderedDataInputStream makerNoteDataInputStream = new ByteOrderedDataInputStream(makerNoteAttribute.bytes); makerNoteDataInputStream.setByteOrder(mExifByteOrder); // Seek to MakerNote data makerNoteDataInputStream.seek(PEF_MAKER_NOTE_SKIP_SIZE); // Read IFD data from MakerNote readImageFileDirectory(makerNoteDataInputStream, IFD_TYPE_PEF); // Update ColorSpace tag ExifAttribute colorSpaceAttribute = (ExifAttribute) mAttributes[IFD_TYPE_PEF].get(TAG_COLOR_SPACE); if (colorSpaceAttribute != null) { mAttributes[IFD_TYPE_EXIF].put(TAG_COLOR_SPACE, colorSpaceAttribute); } } } } /** * RAF files contains a JPEG and a CFA data. * The JPEG contains two images, a preview and a thumbnail, while the CFA contains a RAW image. * This method looks at the first 160 bytes of a RAF file to retrieve the offset and length * values for the JPEG and CFA data. * Using that data, it parses the JPEG data to retrieve the preview and thumbnail image data, * then parses the CFA metadata to retrieve the primary image length/width values. * For data format details, see http://fileformats.archiveteam.org/wiki/Fujifilm_RAF */ private void getRafAttributes(ByteOrderedDataInputStream in) throws IOException { // Retrieve offset & length values in.skipBytes(RAF_OFFSET_TO_JPEG_IMAGE_OFFSET); byte[] jpegOffsetBytes = new byte[4]; byte[] cfaHeaderOffsetBytes = new byte[4]; in.read(jpegOffsetBytes); // Skip JPEG length value since it is not needed in.skipBytes(RAF_JPEG_LENGTH_VALUE_SIZE); in.read(cfaHeaderOffsetBytes); int rafJpegOffset = ByteBuffer.wrap(jpegOffsetBytes).getInt(); int rafCfaHeaderOffset = ByteBuffer.wrap(cfaHeaderOffsetBytes).getInt(); // Retrieve JPEG image metadata getJpegAttributes(in, rafJpegOffset, IFD_TYPE_PREVIEW); // Skip to CFA header offset. in.seek(rafCfaHeaderOffset); // Retrieve primary image length/width values, if TAG_RAF_IMAGE_SIZE exists in.setByteOrder(ByteOrder.BIG_ENDIAN); int numberOfDirectoryEntry = in.readInt(); if (DEBUG) { Log.d(TAG, "numberOfDirectoryEntry: " + numberOfDirectoryEntry); } // CFA stores some metadata about the RAW image. Since CFA uses proprietary tags, can only // find and retrieve image size information tags, while skipping others. // See piex.cc RafGetDimension() for (int i = 0; i < numberOfDirectoryEntry; ++i) { int tagNumber = in.readUnsignedShort(); int numberOfBytes = in.readUnsignedShort(); if (tagNumber == TAG_RAF_IMAGE_SIZE.number) { int imageLength = in.readShort(); int imageWidth = in.readShort(); ExifAttribute imageLengthAttribute = ExifAttribute.createUShort(imageLength, mExifByteOrder); ExifAttribute imageWidthAttribute = ExifAttribute.createUShort(imageWidth, mExifByteOrder); mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH, imageLengthAttribute); mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH, imageWidthAttribute); if (DEBUG) { Log.d(TAG, "Updated to length: " + imageLength + ", width: " + imageWidth); } return; } in.skipBytes(numberOfBytes); } } /** * ORF files contains a primary image data and a MakerNote data that contains preview/thumbnail * images. Both data takes the form of IFDs and can therefore be read with the * readImageFileDirectory() method. * This method reads all the necessary data and updates the primary/preview/thumbnail image * information according to the GetOlympusPreviewImage() method in piex.cc. * For data format details, see the following: * http://fileformats.archiveteam.org/wiki/Olympus_ORF * https://libopenraw.freedesktop.org/wiki/Olympus_ORF */ private void getOrfAttributes(ByteOrderedDataInputStream in) throws IOException { // Retrieve primary image data // Other Exif data will be located in the Makernote. getRawAttributes(in); // Additionally retrieve preview/thumbnail information from MakerNote tag, which contains // proprietary tags and therefore does not have offical documentation // See GetOlympusPreviewImage() in piex.cc & http://www.exiv2.org/tags-olympus.html ExifAttribute makerNoteAttribute = (ExifAttribute) mAttributes[IFD_TYPE_EXIF].get(TAG_MAKER_NOTE); if (makerNoteAttribute != null) { // Create an ordered DataInputStream for MakerNote ByteOrderedDataInputStream makerNoteDataInputStream = new ByteOrderedDataInputStream(makerNoteAttribute.bytes); makerNoteDataInputStream.setByteOrder(mExifByteOrder); // There are two types of headers for Olympus MakerNotes // See http://www.exiv2.org/makernote.html#R1 byte[] makerNoteHeader1Bytes = new byte[ORF_MAKER_NOTE_HEADER_1.length]; makerNoteDataInputStream.readFully(makerNoteHeader1Bytes); makerNoteDataInputStream.seek(0); byte[] makerNoteHeader2Bytes = new byte[ORF_MAKER_NOTE_HEADER_2.length]; makerNoteDataInputStream.readFully(makerNoteHeader2Bytes); // Skip the corresponding amount of bytes for each header type if (Arrays.equals(makerNoteHeader1Bytes, ORF_MAKER_NOTE_HEADER_1)) { makerNoteDataInputStream.seek(ORF_MAKER_NOTE_HEADER_1_SIZE); } else if (Arrays.equals(makerNoteHeader2Bytes, ORF_MAKER_NOTE_HEADER_2)) { makerNoteDataInputStream.seek(ORF_MAKER_NOTE_HEADER_2_SIZE); } // Read IFD data from MakerNote readImageFileDirectory(makerNoteDataInputStream, IFD_TYPE_ORF_MAKER_NOTE); // Retrieve & update preview image offset & length values ExifAttribute imageStartAttribute = (ExifAttribute) mAttributes[IFD_TYPE_ORF_CAMERA_SETTINGS].get(TAG_ORF_PREVIEW_IMAGE_START); ExifAttribute imageLengthAttribute = (ExifAttribute) mAttributes[IFD_TYPE_ORF_CAMERA_SETTINGS].get(TAG_ORF_PREVIEW_IMAGE_LENGTH); if (imageStartAttribute != null && imageLengthAttribute != null) { mAttributes[IFD_TYPE_PREVIEW].put(TAG_JPEG_INTERCHANGE_FORMAT, imageStartAttribute); mAttributes[IFD_TYPE_PREVIEW].put(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, imageLengthAttribute); } // TODO: Check this behavior in other ORF files // Retrieve primary image length & width values // See piex.cc GetOlympusPreviewImage() ExifAttribute aspectFrameAttribute = (ExifAttribute) mAttributes[IFD_TYPE_ORF_IMAGE_PROCESSING].get(TAG_ORF_ASPECT_FRAME); if (aspectFrameAttribute != null) { int[] aspectFrameValues = (int[]) aspectFrameAttribute.getValue(mExifByteOrder); if (aspectFrameValues == null || aspectFrameValues.length != 4) { Log.w(TAG, "Invalid aspect frame values. frame=" + Arrays.toString(aspectFrameValues)); return; } if (aspectFrameValues[2] > aspectFrameValues[0] && aspectFrameValues[3] > aspectFrameValues[1]) { int primaryImageWidth = aspectFrameValues[2] - aspectFrameValues[0] + 1; int primaryImageLength = aspectFrameValues[3] - aspectFrameValues[1] + 1; // Swap width & length values if (primaryImageWidth < primaryImageLength) { primaryImageWidth += primaryImageLength; primaryImageLength = primaryImageWidth - primaryImageLength; primaryImageWidth -= primaryImageLength; } ExifAttribute primaryImageWidthAttribute = ExifAttribute.createUShort(primaryImageWidth, mExifByteOrder); ExifAttribute primaryImageLengthAttribute = ExifAttribute.createUShort(primaryImageLength, mExifByteOrder); mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH, primaryImageWidthAttribute); mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH, primaryImageLengthAttribute); } } } } // RW2 contains the primary image data in IFD0 and the preview and/or thumbnail image data in // the JpgFromRaw tag // See https://libopenraw.freedesktop.org/wiki/Panasonic_RAW/ and piex.cc Rw2GetPreviewData() private void getRw2Attributes(ByteOrderedDataInputStream in) throws IOException { // Retrieve primary image data getRawAttributes(in); // Retrieve preview and/or thumbnail image data ExifAttribute jpgFromRawAttribute = (ExifAttribute) mAttributes[IFD_TYPE_PRIMARY].get(TAG_RW2_JPG_FROM_RAW); if (jpgFromRawAttribute != null) { getJpegAttributes(in, mRw2JpgFromRawOffset, IFD_TYPE_PREVIEW); } // Set ISO tag value if necessary ExifAttribute rw2IsoAttribute = (ExifAttribute) mAttributes[IFD_TYPE_PRIMARY].get(TAG_RW2_ISO); ExifAttribute exifIsoAttribute = (ExifAttribute) mAttributes[IFD_TYPE_EXIF].get(TAG_PHOTOGRAPHIC_SENSITIVITY); if (rw2IsoAttribute != null && exifIsoAttribute == null) { // Place this attribute only if it doesn't exist mAttributes[IFD_TYPE_EXIF].put(TAG_PHOTOGRAPHIC_SENSITIVITY, rw2IsoAttribute); } } // Stores a new JPEG image with EXIF attributes into a given output stream. private void saveJpegAttributes(InputStream inputStream, OutputStream outputStream) throws IOException { // See JPEG File Interchange Format Specification, "JFIF Specification" if (DEBUG) { Log.d(TAG, "saveJpegAttributes starting with (inputStream: " + inputStream + ", outputStream: " + outputStream + ")"); } DataInputStream dataInputStream = new DataInputStream(inputStream); ByteOrderedDataOutputStream dataOutputStream = new ByteOrderedDataOutputStream(outputStream, ByteOrder.BIG_ENDIAN); if (dataInputStream.readByte() != MARKER) { throw new IOException("Invalid marker"); } dataOutputStream.writeByte(MARKER); if (dataInputStream.readByte() != MARKER_SOI) { throw new IOException("Invalid marker"); } dataOutputStream.writeByte(MARKER_SOI); // Write EXIF APP1 segment dataOutputStream.writeByte(MARKER); dataOutputStream.writeByte(MARKER_APP1); writeExifSegment(dataOutputStream, 6); byte[] bytes = new byte[4096]; while (true) { byte marker = dataInputStream.readByte(); if (marker != MARKER) { throw new IOException("Invalid marker"); } marker = dataInputStream.readByte(); switch (marker) { case MARKER_APP1: { int length = dataInputStream.readUnsignedShort() - 2; if (length < 0) { throw new IOException("Invalid length"); } byte[] identifier = new byte[6]; if (length >= 6) { if (dataInputStream.read(identifier) != 6) { throw new IOException("Invalid exif"); } if (Arrays.equals(identifier, IDENTIFIER_EXIF_APP1)) { // Skip the original EXIF APP1 segment. if (dataInputStream.skipBytes(length - 6) != length - 6) { throw new IOException("Invalid length"); } break; } } // Copy non-EXIF APP1 segment. dataOutputStream.writeByte(MARKER); dataOutputStream.writeByte(marker); dataOutputStream.writeUnsignedShort(length + 2); if (length >= 6) { length -= 6; dataOutputStream.write(identifier); } int read; while (length > 0 && (read = dataInputStream.read( bytes, 0, Math.min(length, bytes.length))) >= 0) { dataOutputStream.write(bytes, 0, read); length -= read; } break; } case MARKER_EOI: case MARKER_SOS: { dataOutputStream.writeByte(MARKER); dataOutputStream.writeByte(marker); // Copy all the remaining data copy(dataInputStream, dataOutputStream); return; } default: { // Copy JPEG segment dataOutputStream.writeByte(MARKER); dataOutputStream.writeByte(marker); int length = dataInputStream.readUnsignedShort(); dataOutputStream.writeUnsignedShort(length); length -= 2; if (length < 0) { throw new IOException("Invalid length"); } int read; while (length > 0 && (read = dataInputStream.read( bytes, 0, Math.min(length, bytes.length))) >= 0) { dataOutputStream.write(bytes, 0, read); length -= read; } break; } } } } // Reads the given EXIF byte area and save its tag data into attributes. private void readExifSegment(byte[] exifBytes, int imageType) throws IOException { ByteOrderedDataInputStream dataInputStream = new ByteOrderedDataInputStream(exifBytes); // Parse TIFF Headers. See JEITA CP-3451C Section 4.5.2. Table 1. parseTiffHeaders(dataInputStream, exifBytes.length); // Read TIFF image file directories. See JEITA CP-3451C Section 4.5.2. Figure 6. readImageFileDirectory(dataInputStream, imageType); } private void addDefaultValuesForCompatibility() { // If DATETIME tag has no value, then set the value to DATETIME_ORIGINAL tag's. String valueOfDateTimeOriginal = getAttribute(TAG_DATETIME_ORIGINAL); if (valueOfDateTimeOriginal != null && getAttribute(TAG_DATETIME) == null) { mAttributes[IFD_TYPE_PRIMARY].put(TAG_DATETIME, ExifAttribute.createString(valueOfDateTimeOriginal)); } // Add the default value. if (getAttribute(TAG_IMAGE_WIDTH) == null) { mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH, ExifAttribute.createULong(0, mExifByteOrder)); } if (getAttribute(TAG_IMAGE_LENGTH) == null) { mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH, ExifAttribute.createULong(0, mExifByteOrder)); } if (getAttribute(TAG_ORIENTATION) == null) { mAttributes[IFD_TYPE_PRIMARY].put(TAG_ORIENTATION, ExifAttribute.createULong(0, mExifByteOrder)); } if (getAttribute(TAG_LIGHT_SOURCE) == null) { mAttributes[IFD_TYPE_EXIF].put(TAG_LIGHT_SOURCE, ExifAttribute.createULong(0, mExifByteOrder)); } } private ByteOrder readByteOrder(ByteOrderedDataInputStream dataInputStream) throws IOException { // Read byte order. short byteOrder = dataInputStream.readShort(); switch (byteOrder) { case BYTE_ALIGN_II: if (DEBUG) { Log.d(TAG, "readExifSegment: Byte Align II"); } return ByteOrder.LITTLE_ENDIAN; case BYTE_ALIGN_MM: if (DEBUG) { Log.d(TAG, "readExifSegment: Byte Align MM"); } return ByteOrder.BIG_ENDIAN; default: throw new IOException("Invalid byte order: " + Integer.toHexString(byteOrder)); } } private void parseTiffHeaders(ByteOrderedDataInputStream dataInputStream, int exifBytesLength) throws IOException { // Read byte order mExifByteOrder = readByteOrder(dataInputStream); // Set byte order dataInputStream.setByteOrder(mExifByteOrder); // Check start code int startCode = dataInputStream.readUnsignedShort(); if (mMimeType != IMAGE_TYPE_ORF && mMimeType != IMAGE_TYPE_RW2 && startCode != START_CODE) { throw new IOException("Invalid start code: " + Integer.toHexString(startCode)); } // Read and skip to first ifd offset int firstIfdOffset = dataInputStream.readInt(); if (firstIfdOffset < 8 || firstIfdOffset >= exifBytesLength) { throw new IOException("Invalid first Ifd offset: " + firstIfdOffset); } firstIfdOffset -= 8; if (firstIfdOffset > 0) { if (dataInputStream.skipBytes(firstIfdOffset) != firstIfdOffset) { throw new IOException("Couldn't jump to first Ifd: " + firstIfdOffset); } } } // Reads image file directory, which is a tag group in EXIF. private void readImageFileDirectory(ByteOrderedDataInputStream dataInputStream, @IfdType int ifdType) throws IOException { if (dataInputStream.mPosition + 2 > dataInputStream.mLength) { // Return if there is no data from the offset. return; } // See TIFF 6.0 Section 2: TIFF Structure, Figure 1. short numberOfDirectoryEntry = dataInputStream.readShort(); if (DEBUG) { Log.d(TAG, "numberOfDirectoryEntry: " + numberOfDirectoryEntry); } if (dataInputStream.mPosition + 12 * numberOfDirectoryEntry > dataInputStream.mLength) { // Return if the size of entries is too big. return; } // See TIFF 6.0 Section 2: TIFF Structure, "Image File Directory". for (short i = 0; i < numberOfDirectoryEntry; ++i) { int tagNumber = dataInputStream.readUnsignedShort(); int dataFormat = dataInputStream.readUnsignedShort(); int numberOfComponents = dataInputStream.readInt(); // Next four bytes is for data offset or value. long nextEntryOffset = dataInputStream.peek() + 4; // Look up a corresponding tag from tag number ExifTag tag = (ExifTag) sExifTagMapsForReading[ifdType].get(tagNumber); if (DEBUG) { Log.d(TAG, String.format("ifdType: %d, tagNumber: %d, tagName: %s, dataFormat: %d, " + "numberOfComponents: %d", ifdType, tagNumber, tag != null ? tag.name : null, dataFormat, numberOfComponents)); } long byteCount = 0; boolean valid = false; if (tag == null) { Log.w(TAG, "Skip the tag entry since tag number is not defined: " + tagNumber); } else if (dataFormat <= 0 || dataFormat >= IFD_FORMAT_BYTES_PER_FORMAT.length) { Log.w(TAG, "Skip the tag entry since data format is invalid: " + dataFormat); } else if (!tag.isFormatCompatible(dataFormat)) { Log.w(TAG, "Skip the tag entry since data format (" + IFD_FORMAT_NAMES[dataFormat] + ") is unexpected for tag: " + tag.name); } else { if (dataFormat == IFD_FORMAT_UNDEFINED) { dataFormat = tag.primaryFormat; } byteCount = (long) numberOfComponents * IFD_FORMAT_BYTES_PER_FORMAT[dataFormat]; if (byteCount < 0 || byteCount > Integer.MAX_VALUE) { Log.w(TAG, "Skip the tag entry since the number of components is invalid: " + numberOfComponents); } else { valid = true; } } if (!valid) { dataInputStream.seek(nextEntryOffset); continue; } // Read a value from data field or seek to the value offset which is stored in data // field if the size of the entry value is bigger than 4. if (byteCount > 4) { int offset = dataInputStream.readInt(); if (DEBUG) { Log.d(TAG, "seek to data offset: " + offset); } if (mMimeType == IMAGE_TYPE_ORF) { if (TAG_MAKER_NOTE.equals(tag.name)) { // Save offset value for reading thumbnail mOrfMakerNoteOffset = offset; } else if (ifdType == IFD_TYPE_ORF_MAKER_NOTE && TAG_ORF_THUMBNAIL_IMAGE.equals(tag.name)) { // Retrieve & update values for thumbnail offset and length values for ORF mOrfThumbnailOffset = offset; mOrfThumbnailLength = numberOfComponents; ExifAttribute compressionAttribute = ExifAttribute.createUShort(DATA_JPEG, mExifByteOrder); ExifAttribute jpegInterchangeFormatAttribute = ExifAttribute.createULong(mOrfThumbnailOffset, mExifByteOrder); ExifAttribute jpegInterchangeFormatLengthAttribute = ExifAttribute.createULong(mOrfThumbnailLength, mExifByteOrder); mAttributes[IFD_TYPE_THUMBNAIL].put(TAG_COMPRESSION, compressionAttribute); mAttributes[IFD_TYPE_THUMBNAIL].put(TAG_JPEG_INTERCHANGE_FORMAT, jpegInterchangeFormatAttribute); mAttributes[IFD_TYPE_THUMBNAIL].put(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, jpegInterchangeFormatLengthAttribute); } } else if (mMimeType == IMAGE_TYPE_RW2) { if (TAG_RW2_JPG_FROM_RAW.equals(tag.name)) { mRw2JpgFromRawOffset = offset; } } if (offset + byteCount <= dataInputStream.mLength) { dataInputStream.seek(offset); } else { // Skip if invalid data offset. Log.w(TAG, "Skip the tag entry since data offset is invalid: " + offset); dataInputStream.seek(nextEntryOffset); continue; } } // Recursively parse IFD when a IFD pointer tag appears. Integer nextIfdType = sExifPointerTagMap.get(tagNumber); if (DEBUG) { Log.d(TAG, "nextIfdType: " + nextIfdType + " byteCount: " + byteCount); } if (nextIfdType != null) { long offset = -1L; // Get offset from data field switch (dataFormat) { case IFD_FORMAT_USHORT: { offset = dataInputStream.readUnsignedShort(); break; } case IFD_FORMAT_SSHORT: { offset = dataInputStream.readShort(); break; } case IFD_FORMAT_ULONG: { offset = dataInputStream.readUnsignedInt(); break; } case IFD_FORMAT_SLONG: case IFD_FORMAT_IFD: { offset = dataInputStream.readInt(); break; } default: { // Nothing to do break; } } if (DEBUG) { Log.d(TAG, String.format("Offset: %d, tagName: %s", offset, tag.name)); } if (offset > 0L && offset < dataInputStream.mLength) { dataInputStream.seek(offset); readImageFileDirectory(dataInputStream, nextIfdType); } else { Log.w(TAG, "Skip jump into the IFD since its offset is invalid: " + offset); } dataInputStream.seek(nextEntryOffset); continue; } byte[] bytes = new byte[(int) byteCount]; dataInputStream.readFully(bytes); ExifAttribute attribute = new ExifAttribute(dataFormat, numberOfComponents, bytes); mAttributes[ifdType].put(tag.name, attribute); // DNG files have a DNG Version tag specifying the version of specifications that the // image file is following. // See http://fileformats.archiveteam.org/wiki/DNG if (TAG_DNG_VERSION.equals(tag.name)) { mMimeType = IMAGE_TYPE_DNG; } // PEF files have a Make or Model tag that begins with "PENTAX" or a compression tag // that is 65535. // See http://fileformats.archiveteam.org/wiki/Pentax_PEF if (((TAG_MAKE.equals(tag.name) || TAG_MODEL.equals(tag.name)) && attribute.getStringValue(mExifByteOrder).contains(PEF_SIGNATURE)) || (TAG_COMPRESSION.equals(tag.name) && attribute.getIntValue(mExifByteOrder) == 65535)) { mMimeType = IMAGE_TYPE_PEF; } // Seek to next tag offset if (dataInputStream.peek() != nextEntryOffset) { dataInputStream.seek(nextEntryOffset); } } if (dataInputStream.peek() + 4 <= dataInputStream.mLength) { int nextIfdOffset = dataInputStream.readInt(); if (DEBUG) { Log.d(TAG, String.format("nextIfdOffset: %d", nextIfdOffset)); } // The next IFD offset needs to be bigger than 8 // since the first IFD offset is at least 8. if (nextIfdOffset > 8 && nextIfdOffset < dataInputStream.mLength) { dataInputStream.seek(nextIfdOffset); if (mAttributes[IFD_TYPE_THUMBNAIL].isEmpty()) { // Do not overwrite thumbnail IFD data if it alreay exists. readImageFileDirectory(dataInputStream, IFD_TYPE_THUMBNAIL); } else if (mAttributes[IFD_TYPE_PREVIEW].isEmpty()) { readImageFileDirectory(dataInputStream, IFD_TYPE_PREVIEW); } } } } /** * JPEG compressed images do not contain IMAGE_LENGTH & IMAGE_WIDTH tags. * This value uses JpegInterchangeFormat(JPEG data offset) value, and calls getJpegAttributes() * to locate SOF(Start of Frame) marker and update the image length & width values. * See JEITA CP-3451C Table 5 and Section 4.8.1. B. */ private void retrieveJpegImageSize(ByteOrderedDataInputStream in, int imageType) throws IOException { // Check if image already has IMAGE_LENGTH & IMAGE_WIDTH values ExifAttribute imageLengthAttribute = (ExifAttribute) mAttributes[imageType].get(TAG_IMAGE_LENGTH); ExifAttribute imageWidthAttribute = (ExifAttribute) mAttributes[imageType].get(TAG_IMAGE_WIDTH); if (imageLengthAttribute == null || imageWidthAttribute == null) { // Find if offset for JPEG data exists ExifAttribute jpegInterchangeFormatAttribute = (ExifAttribute) mAttributes[imageType].get(TAG_JPEG_INTERCHANGE_FORMAT); if (jpegInterchangeFormatAttribute != null) { int jpegInterchangeFormat = jpegInterchangeFormatAttribute.getIntValue(mExifByteOrder); // Searches for SOF marker in JPEG data and updates IMAGE_LENGTH & IMAGE_WIDTH tags getJpegAttributes(in, jpegInterchangeFormat, imageType); } } } // Sets thumbnail offset & length attributes based on JpegInterchangeFormat or StripOffsets tags private void setThumbnailData(ByteOrderedDataInputStream in) throws IOException { HashMap thumbnailData = mAttributes[IFD_TYPE_THUMBNAIL]; ExifAttribute compressionAttribute = (ExifAttribute) thumbnailData.get(TAG_COMPRESSION); if (compressionAttribute != null) { mThumbnailCompression = compressionAttribute.getIntValue(mExifByteOrder); switch (mThumbnailCompression) { case DATA_JPEG: { handleThumbnailFromJfif(in, thumbnailData); break; } case DATA_UNCOMPRESSED: case DATA_JPEG_COMPRESSED: { if (isSupportedDataType(thumbnailData)) { handleThumbnailFromStrips(in, thumbnailData); } break; } } } else { // Thumbnail data may not contain Compression tag value mThumbnailCompression = DATA_JPEG; handleThumbnailFromJfif(in, thumbnailData); } } // Check JpegInterchangeFormat(JFIF) tags to retrieve thumbnail offset & length values // and reads the corresponding bytes if stream does not support seek function private void handleThumbnailFromJfif(ByteOrderedDataInputStream in, HashMap thumbnailData) throws IOException { ExifAttribute jpegInterchangeFormatAttribute = (ExifAttribute) thumbnailData.get(TAG_JPEG_INTERCHANGE_FORMAT); ExifAttribute jpegInterchangeFormatLengthAttribute = (ExifAttribute) thumbnailData.get(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH); if (jpegInterchangeFormatAttribute != null && jpegInterchangeFormatLengthAttribute != null) { int thumbnailOffset = jpegInterchangeFormatAttribute.getIntValue(mExifByteOrder); int thumbnailLength = jpegInterchangeFormatLengthAttribute.getIntValue(mExifByteOrder); // The following code limits the size of thumbnail size not to overflow EXIF data area. thumbnailLength = Math.min(thumbnailLength, in.available() - thumbnailOffset); if (mMimeType == IMAGE_TYPE_JPEG || mMimeType == IMAGE_TYPE_RAF || mMimeType == IMAGE_TYPE_RW2) { thumbnailOffset += mExifOffset; } else if (mMimeType == IMAGE_TYPE_ORF) { // Update offset value since RAF files have IFD data preceding MakerNote data. thumbnailOffset += mOrfMakerNoteOffset; } if (DEBUG) { Log.d(TAG, "Setting thumbnail attributes with offset: " + thumbnailOffset + ", length: " + thumbnailLength); } if (thumbnailOffset > 0 && thumbnailLength > 0) { mHasThumbnail = true; mThumbnailOffset = thumbnailOffset; mThumbnailLength = thumbnailLength; if (mFilename == null && mAssetInputStream == null) { // Save the thumbnail in memory if the input doesn't support reading again. byte[] thumbnailBytes = new byte[thumbnailLength]; in.seek(thumbnailOffset); in.readFully(thumbnailBytes); mThumbnailBytes = thumbnailBytes; } } } } // Check StripOffsets & StripByteCounts tags to retrieve thumbnail offset & length values private void handleThumbnailFromStrips(ByteOrderedDataInputStream in, HashMap thumbnailData) throws IOException { ExifAttribute stripOffsetsAttribute = (ExifAttribute) thumbnailData.get(TAG_STRIP_OFFSETS); ExifAttribute stripByteCountsAttribute = (ExifAttribute) thumbnailData.get(TAG_STRIP_BYTE_COUNTS); if (stripOffsetsAttribute != null && stripByteCountsAttribute != null) { long[] stripOffsets = convertToLongArray(stripOffsetsAttribute.getValue(mExifByteOrder)); long[] stripByteCounts = convertToLongArray(stripByteCountsAttribute.getValue(mExifByteOrder)); if (stripOffsets == null) { Log.w(TAG, "stripOffsets should not be null."); return; } if (stripByteCounts == null) { Log.w(TAG, "stripByteCounts should not be null."); return; } long totalStripByteCount = 0; for (long byteCount : stripByteCounts) { totalStripByteCount += byteCount; } // Set thumbnail byte array data for non-consecutive strip bytes byte[] totalStripBytes = new byte[(int) totalStripByteCount]; int bytesRead = 0; int bytesAdded = 0; for (int i = 0; i < stripOffsets.length; i++) { int stripOffset = (int) stripOffsets[i]; int stripByteCount = (int) stripByteCounts[i]; // Skip to offset int skipBytes = stripOffset - bytesRead; if (skipBytes < 0) { Log.d(TAG, "Invalid strip offset value"); } in.seek(skipBytes); bytesRead += skipBytes; // Read strip bytes byte[] stripBytes = new byte[stripByteCount]; in.read(stripBytes); bytesRead += stripByteCount; // Add bytes to array System.arraycopy(stripBytes, 0, totalStripBytes, bytesAdded, stripBytes.length); bytesAdded += stripBytes.length; } mHasThumbnail = true; mThumbnailBytes = totalStripBytes; mThumbnailLength = totalStripBytes.length; } } // Check if thumbnail data type is currently supported or not private boolean isSupportedDataType(HashMap thumbnailData) throws IOException { ExifAttribute bitsPerSampleAttribute = (ExifAttribute) thumbnailData.get(TAG_BITS_PER_SAMPLE); if (bitsPerSampleAttribute != null) { int[] bitsPerSampleValue = (int[]) bitsPerSampleAttribute.getValue(mExifByteOrder); if (Arrays.equals(BITS_PER_SAMPLE_RGB, bitsPerSampleValue)) { return true; } // See DNG Specification 1.4.0.0. Section 3, Compression. if (mMimeType == IMAGE_TYPE_DNG) { ExifAttribute photometricInterpretationAttribute = (ExifAttribute) thumbnailData.get(TAG_PHOTOMETRIC_INTERPRETATION); if (photometricInterpretationAttribute != null) { int photometricInterpretationValue = photometricInterpretationAttribute.getIntValue(mExifByteOrder); if ((photometricInterpretationValue == PHOTOMETRIC_INTERPRETATION_BLACK_IS_ZERO && Arrays.equals(bitsPerSampleValue, BITS_PER_SAMPLE_GREYSCALE_2)) || ((photometricInterpretationValue == PHOTOMETRIC_INTERPRETATION_YCBCR) && (Arrays.equals(bitsPerSampleValue, BITS_PER_SAMPLE_RGB)))) { return true; } else { // TODO: Add support for lossless Huffman JPEG data } } } } if (DEBUG) { Log.d(TAG, "Unsupported data type value"); } return false; } // Returns true if the image length and width values are <= 512. // See Section 4.8 of http://standardsproposals.bsigroup.com/Home/getPDF/567 private boolean isThumbnail(HashMap map) throws IOException { ExifAttribute imageLengthAttribute = (ExifAttribute) map.get(TAG_IMAGE_LENGTH); ExifAttribute imageWidthAttribute = (ExifAttribute) map.get(TAG_IMAGE_WIDTH); if (imageLengthAttribute != null && imageWidthAttribute != null) { int imageLengthValue = imageLengthAttribute.getIntValue(mExifByteOrder); int imageWidthValue = imageWidthAttribute.getIntValue(mExifByteOrder); if (imageLengthValue <= MAX_THUMBNAIL_SIZE && imageWidthValue <= MAX_THUMBNAIL_SIZE) { return true; } } return false; } // Validate primary, preview, thumbnail image data by comparing image size private void validateImages(InputStream in) throws IOException { // Swap images based on size (primary > preview > thumbnail) swapBasedOnImageSize(IFD_TYPE_PRIMARY, IFD_TYPE_PREVIEW); swapBasedOnImageSize(IFD_TYPE_PRIMARY, IFD_TYPE_THUMBNAIL); swapBasedOnImageSize(IFD_TYPE_PREVIEW, IFD_TYPE_THUMBNAIL); // Check if image has PixelXDimension/PixelYDimension tags, which contain valid image // sizes, excluding padding at the right end or bottom end of the image to make sure that // the values are multiples of 64. See JEITA CP-3451C Table 5 and Section 4.8.1. B. ExifAttribute pixelXDimAttribute = (ExifAttribute) mAttributes[IFD_TYPE_EXIF].get(TAG_PIXEL_X_DIMENSION); ExifAttribute pixelYDimAttribute = (ExifAttribute) mAttributes[IFD_TYPE_EXIF].get(TAG_PIXEL_Y_DIMENSION); if (pixelXDimAttribute != null && pixelYDimAttribute != null) { mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH, pixelXDimAttribute); mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH, pixelYDimAttribute); } // Check whether thumbnail image exists and whether preview image satisfies the thumbnail // image requirements if (mAttributes[IFD_TYPE_THUMBNAIL].isEmpty()) { if (isThumbnail(mAttributes[IFD_TYPE_PREVIEW])) { mAttributes[IFD_TYPE_THUMBNAIL] = mAttributes[IFD_TYPE_PREVIEW]; mAttributes[IFD_TYPE_PREVIEW] = new HashMap<>(); } } // Check if the thumbnail image satisfies the thumbnail size requirements if (!isThumbnail(mAttributes[IFD_TYPE_THUMBNAIL])) { Log.d(TAG, "No image meets the size requirements of a thumbnail image."); } } /** * If image is uncompressed, ImageWidth/Length tags are used to store size info. * However, uncompressed images often store extra pixels around the edges of the final image, * which results in larger values for TAG_IMAGE_WIDTH and TAG_IMAGE_LENGTH tags. * This method corrects those tag values by checking first the values of TAG_DEFAULT_CROP_SIZE * See DNG Specification 1.4.0.0. Section 4. (DefaultCropSize) * * If image is a RW2 file, valid image sizes are stored in SensorBorder tags. * See tiff_parser.cc GetFullDimension32() * */ private void updateImageSizeValues(ByteOrderedDataInputStream in, int imageType) throws IOException { // Uncompressed image valid image size values ExifAttribute defaultCropSizeAttribute = (ExifAttribute) mAttributes[imageType].get(TAG_DEFAULT_CROP_SIZE); // RW2 image valid image size values ExifAttribute topBorderAttribute = (ExifAttribute) mAttributes[imageType].get(TAG_RW2_SENSOR_TOP_BORDER); ExifAttribute leftBorderAttribute = (ExifAttribute) mAttributes[imageType].get(TAG_RW2_SENSOR_LEFT_BORDER); ExifAttribute bottomBorderAttribute = (ExifAttribute) mAttributes[imageType].get(TAG_RW2_SENSOR_BOTTOM_BORDER); ExifAttribute rightBorderAttribute = (ExifAttribute) mAttributes[imageType].get(TAG_RW2_SENSOR_RIGHT_BORDER); if (defaultCropSizeAttribute != null) { // Update for uncompressed image ExifAttribute defaultCropSizeXAttribute, defaultCropSizeYAttribute; if (defaultCropSizeAttribute.format == IFD_FORMAT_URATIONAL) { Rational[] defaultCropSizeValue = (Rational[]) defaultCropSizeAttribute.getValue(mExifByteOrder); if (defaultCropSizeValue == null || defaultCropSizeValue.length != 2) { Log.w(TAG, "Invalid crop size values. cropSize=" + Arrays.toString(defaultCropSizeValue)); return; } defaultCropSizeXAttribute = ExifAttribute.createURational(defaultCropSizeValue[0], mExifByteOrder); defaultCropSizeYAttribute = ExifAttribute.createURational(defaultCropSizeValue[1], mExifByteOrder); } else { int[] defaultCropSizeValue = (int[]) defaultCropSizeAttribute.getValue(mExifByteOrder); if (defaultCropSizeValue == null || defaultCropSizeValue.length != 2) { Log.w(TAG, "Invalid crop size values. cropSize=" + Arrays.toString(defaultCropSizeValue)); return; } defaultCropSizeXAttribute = ExifAttribute.createUShort(defaultCropSizeValue[0], mExifByteOrder); defaultCropSizeYAttribute = ExifAttribute.createUShort(defaultCropSizeValue[1], mExifByteOrder); } mAttributes[imageType].put(TAG_IMAGE_WIDTH, defaultCropSizeXAttribute); mAttributes[imageType].put(TAG_IMAGE_LENGTH, defaultCropSizeYAttribute); } else if (topBorderAttribute != null && leftBorderAttribute != null && bottomBorderAttribute != null && rightBorderAttribute != null) { // Update for RW2 image int topBorderValue = topBorderAttribute.getIntValue(mExifByteOrder); int bottomBorderValue = bottomBorderAttribute.getIntValue(mExifByteOrder); int rightBorderValue = rightBorderAttribute.getIntValue(mExifByteOrder); int leftBorderValue = leftBorderAttribute.getIntValue(mExifByteOrder); if (bottomBorderValue > topBorderValue && rightBorderValue > leftBorderValue) { int length = bottomBorderValue - topBorderValue; int width = rightBorderValue - leftBorderValue; ExifAttribute imageLengthAttribute = ExifAttribute.createUShort(length, mExifByteOrder); ExifAttribute imageWidthAttribute = ExifAttribute.createUShort(width, mExifByteOrder); mAttributes[imageType].put(TAG_IMAGE_LENGTH, imageLengthAttribute); mAttributes[imageType].put(TAG_IMAGE_WIDTH, imageWidthAttribute); } } else { retrieveJpegImageSize(in, imageType); } } // Writes an Exif segment into the given output stream. private int writeExifSegment(ByteOrderedDataOutputStream dataOutputStream, int exifOffsetFromBeginning) throws IOException { // The following variables are for calculating each IFD tag group size in bytes. int[] ifdOffsets = new int[EXIF_TAGS.length]; int[] ifdDataSizes = new int[EXIF_TAGS.length]; // Remove IFD pointer tags (we'll re-add it later.) for (ExifTag tag : EXIF_POINTER_TAGS) { removeAttribute(tag.name); } // Remove old thumbnail data removeAttribute(JPEG_INTERCHANGE_FORMAT_TAG.name); removeAttribute(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name); // Remove null value tags. for (int ifdType = 0; ifdType < EXIF_TAGS.length; ++ifdType) { for (Object obj : mAttributes[ifdType].entrySet().toArray()) { final Map.Entry entry = (Map.Entry) obj; if (entry.getValue() == null) { mAttributes[ifdType].remove(entry.getKey()); } } } // Add IFD pointer tags. The next offset of primary image TIFF IFD will have thumbnail IFD // offset when there is one or more tags in the thumbnail IFD. if (!mAttributes[IFD_TYPE_EXIF].isEmpty()) { mAttributes[IFD_TYPE_PRIMARY].put(EXIF_POINTER_TAGS[1].name, ExifAttribute.createULong(0, mExifByteOrder)); } if (!mAttributes[IFD_TYPE_GPS].isEmpty()) { mAttributes[IFD_TYPE_PRIMARY].put(EXIF_POINTER_TAGS[2].name, ExifAttribute.createULong(0, mExifByteOrder)); } if (!mAttributes[IFD_TYPE_INTEROPERABILITY].isEmpty()) { mAttributes[IFD_TYPE_EXIF].put(EXIF_POINTER_TAGS[3].name, ExifAttribute.createULong(0, mExifByteOrder)); } if (mHasThumbnail) { mAttributes[IFD_TYPE_THUMBNAIL].put(JPEG_INTERCHANGE_FORMAT_TAG.name, ExifAttribute.createULong(0, mExifByteOrder)); mAttributes[IFD_TYPE_THUMBNAIL].put(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name, ExifAttribute.createULong(mThumbnailLength, mExifByteOrder)); } // Calculate IFD group data area sizes. IFD group data area is assigned to save the entry // value which has a bigger size than 4 bytes. for (int i = 0; i < EXIF_TAGS.length; ++i) { int sum = 0; for (Map.Entry<String, ExifAttribute> entry : mAttributes[i].entrySet()) { final ExifAttribute exifAttribute = entry.getValue(); final int size = exifAttribute.size(); if (size > 4) { sum += size; } } ifdDataSizes[i] += sum; } // Calculate IFD offsets. int position = 8; for (int ifdType = 0; ifdType < EXIF_TAGS.length; ++ifdType) { if (!mAttributes[ifdType].isEmpty()) { ifdOffsets[ifdType] = position; position += 2 + mAttributes[ifdType].size() * 12 + 4 + ifdDataSizes[ifdType]; } } if (mHasThumbnail) { int thumbnailOffset = position; mAttributes[IFD_TYPE_THUMBNAIL].put(JPEG_INTERCHANGE_FORMAT_TAG.name, ExifAttribute.createULong(thumbnailOffset, mExifByteOrder)); mThumbnailOffset = exifOffsetFromBeginning + thumbnailOffset; position += mThumbnailLength; } // Calculate the total size int totalSize = position + 8; // eight bytes is for header part. if (DEBUG) { Log.d(TAG, "totalSize length: " + totalSize); for (int i = 0; i < EXIF_TAGS.length; ++i) { Log.d(TAG, String.format("index: %d, offsets: %d, tag count: %d, data sizes: %d", i, ifdOffsets[i], mAttributes[i].size(), ifdDataSizes[i])); } } // Update IFD pointer tags with the calculated offsets. if (!mAttributes[IFD_TYPE_EXIF].isEmpty()) { mAttributes[IFD_TYPE_PRIMARY].put(EXIF_POINTER_TAGS[1].name, ExifAttribute.createULong(ifdOffsets[IFD_TYPE_EXIF], mExifByteOrder)); } if (!mAttributes[IFD_TYPE_GPS].isEmpty()) { mAttributes[IFD_TYPE_PRIMARY].put(EXIF_POINTER_TAGS[2].name, ExifAttribute.createULong(ifdOffsets[IFD_TYPE_GPS], mExifByteOrder)); } if (!mAttributes[IFD_TYPE_INTEROPERABILITY].isEmpty()) { mAttributes[IFD_TYPE_EXIF].put(EXIF_POINTER_TAGS[3].name, ExifAttribute.createULong( ifdOffsets[IFD_TYPE_INTEROPERABILITY], mExifByteOrder)); } // Write TIFF Headers. See JEITA CP-3451C Section 4.5.2. Table 1. dataOutputStream.writeUnsignedShort(totalSize); dataOutputStream.write(IDENTIFIER_EXIF_APP1); dataOutputStream.writeShort(mExifByteOrder == ByteOrder.BIG_ENDIAN ? BYTE_ALIGN_MM : BYTE_ALIGN_II); dataOutputStream.setByteOrder(mExifByteOrder); dataOutputStream.writeUnsignedShort(START_CODE); dataOutputStream.writeUnsignedInt(IFD_OFFSET); // Write IFD groups. See JEITA CP-3451C Section 4.5.8. Figure 9. for (int ifdType = 0; ifdType < EXIF_TAGS.length; ++ifdType) { if (!mAttributes[ifdType].isEmpty()) { // See JEITA CP-3451C Section 4.6.2: IFD structure. // Write entry count dataOutputStream.writeUnsignedShort(mAttributes[ifdType].size()); // Write entry info int dataOffset = ifdOffsets[ifdType] + 2 + mAttributes[ifdType].size() * 12 + 4; for (Map.Entry<String, ExifAttribute> entry : mAttributes[ifdType].entrySet()) { // Convert tag name to tag number. final ExifTag tag = sExifTagMapsForWriting[ifdType].get(entry.getKey()); final int tagNumber = tag.number; final ExifAttribute attribute = entry.getValue(); final int size = attribute.size(); dataOutputStream.writeUnsignedShort(tagNumber); dataOutputStream.writeUnsignedShort(attribute.format); dataOutputStream.writeInt(attribute.numberOfComponents); if (size > 4) { dataOutputStream.writeUnsignedInt(dataOffset); dataOffset += size; } else { dataOutputStream.write(attribute.bytes); // Fill zero up to 4 bytes if (size < 4) { for (int i = size; i < 4; ++i) { dataOutputStream.writeByte(0); } } } } // Write the next offset. It writes the offset of thumbnail IFD if there is one or // more tags in the thumbnail IFD when the current IFD is the primary image TIFF // IFD; Otherwise 0. if (ifdType == 0 && !mAttributes[IFD_TYPE_THUMBNAIL].isEmpty()) { dataOutputStream.writeUnsignedInt(ifdOffsets[IFD_TYPE_THUMBNAIL]); } else { dataOutputStream.writeUnsignedInt(0); } // Write values of data field exceeding 4 bytes after the next offset. for (Map.Entry<String, ExifAttribute> entry : mAttributes[ifdType].entrySet()) { ExifAttribute attribute = entry.getValue(); if (attribute.bytes.length > 4) { dataOutputStream.write(attribute.bytes, 0, attribute.bytes.length); } } } } // Write thumbnail if (mHasThumbnail) { dataOutputStream.write(getThumbnailBytes()); } // Reset the byte order to big endian in order to write remaining parts of the JPEG file. dataOutputStream.setByteOrder(ByteOrder.BIG_ENDIAN); return totalSize; } /** * Determines the data format of EXIF entry value. * * @param entryValue The value to be determined. * @return Returns two data formats gussed as a pair in integer. If there is no two candidate data formats for the given entry value, returns {@code -1} in the second of the pair. */ private static Pair<Integer, Integer> guessDataFormat(String entryValue) { // See TIFF 6.0 Section 2, "Image File Directory". // Take the first component if there are more than one component. if (entryValue.contains(",")) { String[] entryValues = entryValue.split(","); Pair<Integer, Integer> dataFormat = guessDataFormat(entryValues[0]); if (dataFormat.first == IFD_FORMAT_STRING) { return dataFormat; } for (int i = 1; i < entryValues.length; ++i) { final Pair<Integer, Integer> guessDataFormat = guessDataFormat(entryValues[i]); int first = -1, second = -1; if (guessDataFormat.first.equals(dataFormat.first) || guessDataFormat.second.equals(dataFormat.first)) { first = dataFormat.first; } if (dataFormat.second != -1 && (guessDataFormat.first.equals(dataFormat.second) || guessDataFormat.second.equals(dataFormat.second))) { second = dataFormat.second; } if (first == -1 && second == -1) { return new Pair<>(IFD_FORMAT_STRING, -1); } if (first == -1) { dataFormat = new Pair<>(second, -1); continue; } if (second == -1) { dataFormat = new Pair<>(first, -1); continue; } } return dataFormat; } if (entryValue.contains("/")) { String[] rationalNumber = entryValue.split("/"); if (rationalNumber.length == 2) { try { long numerator = (long) Double.parseDouble(rationalNumber[0]); long denominator = (long) Double.parseDouble(rationalNumber[1]); if (numerator < 0L || denominator < 0L) { return new Pair<>(IFD_FORMAT_SRATIONAL, -1); } if (numerator > Integer.MAX_VALUE || denominator > Integer.MAX_VALUE) { return new Pair<>(IFD_FORMAT_URATIONAL, -1); } return new Pair<>(IFD_FORMAT_SRATIONAL, IFD_FORMAT_URATIONAL); } catch (NumberFormatException e) { // Ignored } } return new Pair<>(IFD_FORMAT_STRING, -1); } try { Long longValue = Long.parseLong(entryValue); if (longValue >= 0 && longValue <= 65535) { return new Pair<>(IFD_FORMAT_USHORT, IFD_FORMAT_ULONG); } if (longValue < 0) { return new Pair<>(IFD_FORMAT_SLONG, -1); } return new Pair<>(IFD_FORMAT_ULONG, -1); } catch (NumberFormatException e) { // Ignored } try { Double.parseDouble(entryValue); return new Pair<>(IFD_FORMAT_DOUBLE, -1); } catch (NumberFormatException e) { // Ignored } return new Pair<>(IFD_FORMAT_STRING, -1); } // An input stream to parse EXIF data area, which can be written in either little or big endian // order. private static class ByteOrderedDataInputStream extends InputStream implements DataInput { private static final ByteOrder LITTLE_ENDIAN = ByteOrder.LITTLE_ENDIAN; private static final ByteOrder BIG_ENDIAN = ByteOrder.BIG_ENDIAN; private DataInputStream mDataInputStream; private ByteOrder mByteOrder = ByteOrder.BIG_ENDIAN; private final int mLength; private int mPosition; public ByteOrderedDataInputStream(InputStream in) throws IOException { mDataInputStream = new DataInputStream(in); mLength = mDataInputStream.available(); mPosition = 0; mDataInputStream.mark(mLength); } public ByteOrderedDataInputStream(byte[] bytes) throws IOException { this(new ByteArrayInputStream(bytes)); } public void setByteOrder(ByteOrder byteOrder) { mByteOrder = byteOrder; } public void seek(long byteCount) throws IOException { if (mPosition > byteCount) { mPosition = 0; mDataInputStream.reset(); mDataInputStream.mark(mLength); } else { byteCount -= mPosition; } if (skipBytes((int) byteCount) != (int) byteCount) { throw new IOException("Couldn't seek up to the byteCount"); } } public int peek() { return mPosition; } @Override public int available() throws IOException { return mDataInputStream.available(); } @Override public int read() throws IOException { ++mPosition; return mDataInputStream.read(); } @Override public int read(byte[] b, int off, int len) throws IOException { int bytesRead = mDataInputStream.read(b, off, len); mPosition += bytesRead; return bytesRead; } @Override public int readUnsignedByte() throws IOException { ++mPosition; return mDataInputStream.readUnsignedByte(); } @Override public String readLine() throws IOException { Log.d(TAG, "Currently unsupported"); return null; } @Override public boolean readBoolean() throws IOException { ++mPosition; return mDataInputStream.readBoolean(); } @Override public char readChar() throws IOException { mPosition += 2; return mDataInputStream.readChar(); } @Override public String readUTF() throws IOException { mPosition += 2; return mDataInputStream.readUTF(); } @Override public void readFully(byte[] buffer, int offset, int length) throws IOException { mPosition += length; if (mPosition > mLength) { throw new EOFException(); } if (mDataInputStream.read(buffer, offset, length) != length) { throw new IOException("Couldn't read up to the length of buffer"); } } @Override public void readFully(byte[] buffer) throws IOException { mPosition += buffer.length; if (mPosition > mLength) { throw new EOFException(); } if (mDataInputStream.read(buffer, 0, buffer.length) != buffer.length) { throw new IOException("Couldn't read up to the length of buffer"); } } @Override public byte readByte() throws IOException { ++mPosition; if (mPosition > mLength) { throw new EOFException(); } int ch = mDataInputStream.read(); if (ch < 0) { throw new EOFException(); } return (byte) ch; } @Override public short readShort() throws IOException { mPosition += 2; if (mPosition > mLength) { throw new EOFException(); } int ch1 = mDataInputStream.read(); int ch2 = mDataInputStream.read(); if ((ch1 | ch2) < 0) { throw new EOFException(); } if (mByteOrder == LITTLE_ENDIAN) { return (short) ((ch2 << 8) + (ch1)); } else if (mByteOrder == BIG_ENDIAN) { return (short) ((ch1 << 8) + (ch2)); } throw new IOException("Invalid byte order: " + mByteOrder); } @Override public int readInt() throws IOException { mPosition += 4; if (mPosition > mLength) { throw new EOFException(); } int ch1 = mDataInputStream.read(); int ch2 = mDataInputStream.read(); int ch3 = mDataInputStream.read(); int ch4 = mDataInputStream.read(); if ((ch1 | ch2 | ch3 | ch4) < 0) { throw new EOFException(); } if (mByteOrder == LITTLE_ENDIAN) { return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + ch1); } else if (mByteOrder == BIG_ENDIAN) { return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + ch4); } throw new IOException("Invalid byte order: " + mByteOrder); } @Override public int skipBytes(int byteCount) throws IOException { int totalSkip = Math.min(byteCount, mLength - mPosition); int skipped = 0; while (skipped < totalSkip) { skipped += mDataInputStream.skipBytes(totalSkip - skipped); } mPosition += skipped; return skipped; } @Override public int readUnsignedShort() throws IOException { mPosition += 2; if (mPosition > mLength) { throw new EOFException(); } int ch1 = mDataInputStream.read(); int ch2 = mDataInputStream.read(); if ((ch1 | ch2) < 0) { throw new EOFException(); } if (mByteOrder == LITTLE_ENDIAN) { return ((ch2 << 8) + (ch1)); } else if (mByteOrder == BIG_ENDIAN) { return ((ch1 << 8) + (ch2)); } throw new IOException("Invalid byte order: " + mByteOrder); } public long readUnsignedInt() throws IOException { return readInt() & 0xffffffffL; } @Override public long readLong() throws IOException { mPosition += 8; if (mPosition > mLength) { throw new EOFException(); } int ch1 = mDataInputStream.read(); int ch2 = mDataInputStream.read(); int ch3 = mDataInputStream.read(); int ch4 = mDataInputStream.read(); int ch5 = mDataInputStream.read(); int ch6 = mDataInputStream.read(); int ch7 = mDataInputStream.read(); int ch8 = mDataInputStream.read(); if ((ch1 | ch2 | ch3 | ch4 | ch5 | ch6 | ch7 | ch8) < 0) { throw new EOFException(); } if (mByteOrder == LITTLE_ENDIAN) { return (((long) ch8 << 56) + ((long) ch7 << 48) + ((long) ch6 << 40) + ((long) ch5 << 32) + ((long) ch4 << 24) + ((long) ch3 << 16) + ((long) ch2 << 8) + (long) ch1); } else if (mByteOrder == BIG_ENDIAN) { return (((long) ch1 << 56) + ((long) ch2 << 48) + ((long) ch3 << 40) + ((long) ch4 << 32) + ((long) ch5 << 24) + ((long) ch6 << 16) + ((long) ch7 << 8) + (long) ch8); } throw new IOException("Invalid byte order: " + mByteOrder); } @Override public float readFloat() throws IOException { return Float.intBitsToFloat(readInt()); } @Override public double readDouble() throws IOException { return Double.longBitsToDouble(readLong()); } } // An output stream to write EXIF data area, which can be written in either little or big endian // order. private static class ByteOrderedDataOutputStream extends FilterOutputStream { private final OutputStream mOutputStream; private ByteOrder mByteOrder; public ByteOrderedDataOutputStream(OutputStream out, ByteOrder byteOrder) { super(out); mOutputStream = out; mByteOrder = byteOrder; } public void setByteOrder(ByteOrder byteOrder) { mByteOrder = byteOrder; } @Override public void write(byte[] bytes) throws IOException { mOutputStream.write(bytes); } @Override public void write(byte[] bytes, int offset, int length) throws IOException { mOutputStream.write(bytes, offset, length); } public void writeByte(int val) throws IOException { mOutputStream.write(val); } public void writeShort(short val) throws IOException { if (mByteOrder == ByteOrder.LITTLE_ENDIAN) { mOutputStream.write((val >>> 0) & 0xFF); mOutputStream.write((val >>> 8) & 0xFF); } else if (mByteOrder == ByteOrder.BIG_ENDIAN) { mOutputStream.write((val >>> 8) & 0xFF); mOutputStream.write((val >>> 0) & 0xFF); } } public void writeInt(int val) throws IOException { if (mByteOrder == ByteOrder.LITTLE_ENDIAN) { mOutputStream.write((val >>> 0) & 0xFF); mOutputStream.write((val >>> 8) & 0xFF); mOutputStream.write((val >>> 16) & 0xFF); mOutputStream.write((val >>> 24) & 0xFF); } else if (mByteOrder == ByteOrder.BIG_ENDIAN) { mOutputStream.write((val >>> 24) & 0xFF); mOutputStream.write((val >>> 16) & 0xFF); mOutputStream.write((val >>> 8) & 0xFF); mOutputStream.write((val >>> 0) & 0xFF); } } public void writeUnsignedShort(int val) throws IOException { writeShort((short) val); } public void writeUnsignedInt(long val) throws IOException { writeInt((int) val); } } // Swaps image data based on image size private void swapBasedOnImageSize(@IfdType int firstIfdType, @IfdType int secondIfdType) throws IOException { if (mAttributes[firstIfdType].isEmpty() || mAttributes[secondIfdType].isEmpty()) { if (DEBUG) { Log.d(TAG, "Cannot perform swap since only one image data exists"); } return; } ExifAttribute firstImageLengthAttribute = (ExifAttribute) mAttributes[firstIfdType].get(TAG_IMAGE_LENGTH); ExifAttribute firstImageWidthAttribute = (ExifAttribute) mAttributes[firstIfdType].get(TAG_IMAGE_WIDTH); ExifAttribute secondImageLengthAttribute = (ExifAttribute) mAttributes[secondIfdType].get(TAG_IMAGE_LENGTH); ExifAttribute secondImageWidthAttribute = (ExifAttribute) mAttributes[secondIfdType].get(TAG_IMAGE_WIDTH); if (firstImageLengthAttribute == null || firstImageWidthAttribute == null) { if (DEBUG) { Log.d(TAG, "First image does not contain valid size information"); } } else if (secondImageLengthAttribute == null || secondImageWidthAttribute == null) { if (DEBUG) { Log.d(TAG, "Second image does not contain valid size information"); } } else { int firstImageLengthValue = firstImageLengthAttribute.getIntValue(mExifByteOrder); int firstImageWidthValue = firstImageWidthAttribute.getIntValue(mExifByteOrder); int secondImageLengthValue = secondImageLengthAttribute.getIntValue(mExifByteOrder); int secondImageWidthValue = secondImageWidthAttribute.getIntValue(mExifByteOrder); if (firstImageLengthValue < secondImageLengthValue && firstImageWidthValue < secondImageWidthValue) { HashMap<String, ExifAttribute> tempMap = mAttributes[firstIfdType]; mAttributes[firstIfdType] = mAttributes[secondIfdType]; mAttributes[secondIfdType] = tempMap; } } } /** * Closes 'closeable', ignoring any checked exceptions. Does nothing if 'closeable' is null. */ private static void closeQuietly(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (RuntimeException rethrown) { throw rethrown; } catch (Exception ignored) { } } } /** * Copies all of the bytes from {@code in} to {@code out}. Neither stream is closed. * Returns the total number of bytes transferred. */ private static int copy(InputStream in, OutputStream out) throws IOException { int total = 0; byte[] buffer = new byte[8192]; int c; while ((c = in.read(buffer)) != -1) { total += c; out.write(buffer, 0, c); } return total; } /** * Convert given int[] to long[]. If long[] is given, just return it. * Return null for other types of input. */ private static long[] convertToLongArray(Object inputObj) { if (inputObj instanceof int[]) { int[] input = (int[]) inputObj; long[] result = new long[input.length]; for (int i = 0; i < input.length; i++) { result[i] = input[i]; } return result; } else if (inputObj instanceof long[]) { return (long[]) inputObj; } return null; } }
exifinterface/src/android/support/media/ExifInterface.java
/* * Copyright (C) 2007 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 android.support.media; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.Location; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import android.util.Log; import android.util.Pair; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.Closeable; import java.io.DataInput; import java.io.DataInputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * This is a class for reading and writing Exif tags in a JPEG file or a RAW image file. * <p> * Supported formats are: JPEG, DNG, CR2, NEF, NRW, ARW, RW2, ORF, PEF, SRW and RAF. * <p> * Attribute mutation is supported for JPEG image files. */ public class ExifInterface { private static final String TAG = "ExifInterface"; private static final boolean DEBUG = false; // The Exif tag names. See JEITA CP-3451C specifications (Exif 2.3) Section 3-8. // A. Tags related to image data structure /** * <p>The number of columns of image data, equal to the number of pixels per row. In JPEG * compressed data, this tag shall not be used because a JPEG marker is used instead of it.</p> * * <ul> * <li>Tag = 256</li> * <li>Type = Unsigned short or Unsigned long</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_IMAGE_WIDTH = "ImageWidth"; /** * <p>The number of rows of image data. In JPEG compressed data, this tag shall not be used * because a JPEG marker is used instead of it.</p> * * <ul> * <li>Tag = 257</li> * <li>Type = Unsigned short or Unsigned long</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_IMAGE_LENGTH = "ImageLength"; /** * <p>The number of bits per image component. In this standard each component of the image is * 8 bits, so the value for this tag is 8. See also {@link #TAG_SAMPLES_PER_PIXEL}. In JPEG * compressed data, this tag shall not be used because a JPEG marker is used instead of it.</p> * * <ul> * <li>Tag = 258</li> * <li>Type = Unsigned short</li> * <li>Count = 3</li> * <li>Default = {@link #BITS_PER_SAMPLE_RGB}</li> * </ul> */ public static final String TAG_BITS_PER_SAMPLE = "BitsPerSample"; /** * <p>The compression scheme used for the image data. When a primary image is JPEG compressed, * this designation is not necessary. So, this tag shall not be recorded. When thumbnails use * JPEG compression, this tag value is set to 6.</p> * * <ul> * <li>Tag = 259</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> * * @see #DATA_UNCOMPRESSED * @see #DATA_JPEG */ public static final String TAG_COMPRESSION = "Compression"; /** * <p>The pixel composition. In JPEG compressed data, this tag shall not be used because a JPEG * marker is used instead of it.</p> * * <ul> * <li>Tag = 262</li> * <li>Type = SHORT</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> * * @see #PHOTOMETRIC_INTERPRETATION_RGB * @see #PHOTOMETRIC_INTERPRETATION_YCBCR */ public static final String TAG_PHOTOMETRIC_INTERPRETATION = "PhotometricInterpretation"; /** * <p>The image orientation viewed in terms of rows and columns.</p> * * <ul> * <li>Tag = 274</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #ORIENTATION_NORMAL}</li> * </ul> * * @see #ORIENTATION_UNDEFINED * @see #ORIENTATION_NORMAL * @see #ORIENTATION_FLIP_HORIZONTAL * @see #ORIENTATION_ROTATE_180 * @see #ORIENTATION_FLIP_VERTICAL * @see #ORIENTATION_TRANSPOSE * @see #ORIENTATION_ROTATE_90 * @see #ORIENTATION_TRANSVERSE * @see #ORIENTATION_ROTATE_270 */ public static final String TAG_ORIENTATION = "Orientation"; /** * <p>The number of components per pixel. Since this standard applies to RGB and YCbCr images, * the value set for this tag is 3. In JPEG compressed data, this tag shall not be used because * a JPEG marker is used instead of it.</p> * * <ul> * <li>Tag = 277</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = 3</li> * </ul> */ public static final String TAG_SAMPLES_PER_PIXEL = "SamplesPerPixel"; /** * <p>Indicates whether pixel components are recorded in chunky or planar format. In JPEG * compressed data, this tag shall not be used because a JPEG marker is used instead of it. * If this field does not exist, the TIFF default, {@link #FORMAT_CHUNKY}, is assumed.</p> * * <ul> * <li>Tag = 284</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * </ul> * * @see #FORMAT_CHUNKY * @see #FORMAT_PLANAR */ public static final String TAG_PLANAR_CONFIGURATION = "PlanarConfiguration"; /** * <p>The sampling ratio of chrominance components in relation to the luminance component. * In JPEG compressed data a JPEG marker is used instead of this tag. So, this tag shall not * be recorded.</p> * * <ul> * <li>Tag = 530</li> * <li>Type = Unsigned short</li> * <li>Count = 2</li> * <ul> * <li>[2, 1] = YCbCr4:2:2</li> * <li>[2, 2] = YCbCr4:2:0</li> * <li>Other = reserved</li> * </ul> * </ul> */ public static final String TAG_Y_CB_CR_SUB_SAMPLING = "YCbCrSubSampling"; /** * <p>The position of chrominance components in relation to the luminance component. This field * is designated only for JPEG compressed data or uncompressed YCbCr data. The TIFF default is * {@link #Y_CB_CR_POSITIONING_CENTERED}; but when Y:Cb:Cr = 4:2:2 it is recommended in this * standard that {@link #Y_CB_CR_POSITIONING_CO_SITED} be used to record data, in order to * improve the image quality when viewed on TV systems. When this field does not exist, * the reader shall assume the TIFF default. In the case of Y:Cb:Cr = 4:2:0, the TIFF default * ({@link #Y_CB_CR_POSITIONING_CENTERED}) is recommended. If the Exif/DCF reader does not * have the capability of supporting both kinds of positioning, it shall follow the TIFF * default regardless of the value in this field. It is preferable that readers can support * both centered and co-sited positioning.</p> * * <ul> * <li>Tag = 531</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #Y_CB_CR_POSITIONING_CENTERED}</li> * </ul> * * @see #Y_CB_CR_POSITIONING_CENTERED * @see #Y_CB_CR_POSITIONING_CO_SITED */ public static final String TAG_Y_CB_CR_POSITIONING = "YCbCrPositioning"; /** * <p>The number of pixels per {@link #TAG_RESOLUTION_UNIT} in the {@link #TAG_IMAGE_WIDTH} * direction. When the image resolution is unknown, 72 [dpi] shall be designated.</p> * * <ul> * <li>Tag = 282</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = 72</li> * </ul> * * @see #TAG_Y_RESOLUTION * @see #TAG_RESOLUTION_UNIT */ public static final String TAG_X_RESOLUTION = "XResolution"; /** * <p>The number of pixels per {@link #TAG_RESOLUTION_UNIT} in the {@link #TAG_IMAGE_WIDTH} * direction. The same value as {@link #TAG_X_RESOLUTION} shall be designated.</p> * * <ul> * <li>Tag = 283</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = 72</li> * </ul> * * @see #TAG_X_RESOLUTION * @see #TAG_RESOLUTION_UNIT */ public static final String TAG_Y_RESOLUTION = "YResolution"; /** * <p>The unit for measuring {@link #TAG_X_RESOLUTION} and {@link #TAG_Y_RESOLUTION}. The same * unit is used for both {@link #TAG_X_RESOLUTION} and {@link #TAG_Y_RESOLUTION}. If the image * resolution is unknown, {@link #RESOLUTION_UNIT_INCHES} shall be designated.</p> * * <ul> * <li>Tag = 296</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #RESOLUTION_UNIT_INCHES}</li> * </ul> * * @see #RESOLUTION_UNIT_INCHES * @see #RESOLUTION_UNIT_CENTIMETERS * @see #TAG_X_RESOLUTION * @see #TAG_Y_RESOLUTION */ public static final String TAG_RESOLUTION_UNIT = "ResolutionUnit"; // B. Tags related to recording offset /** * <p>For each strip, the byte offset of that strip. It is recommended that this be selected * so the number of strip bytes does not exceed 64 KBytes.In the case of JPEG compressed data, * this designation is not necessary. So, this tag shall not be recorded.</p> * * <ul> * <li>Tag = 273</li> * <li>Type = Unsigned short or Unsigned long</li> * <li>Count = StripsPerImage (for {@link #FORMAT_CHUNKY}) * or {@link #TAG_SAMPLES_PER_PIXEL} * StripsPerImage * (for {@link #FORMAT_PLANAR})</li> * <li>Default = None</li> * </ul> * * <p>StripsPerImage = floor(({@link #TAG_IMAGE_LENGTH} + {@link #TAG_ROWS_PER_STRIP} - 1) * / {@link #TAG_ROWS_PER_STRIP})</p> * * @see #TAG_ROWS_PER_STRIP * @see #TAG_STRIP_BYTE_COUNTS */ public static final String TAG_STRIP_OFFSETS = "StripOffsets"; /** * <p>The number of rows per strip. This is the number of rows in the image of one strip when * an image is divided into strips. In the case of JPEG compressed data, this designation is * not necessary. So, this tag shall not be recorded.</p> * * <ul> * <li>Tag = 278</li> * <li>Type = Unsigned short or Unsigned long</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> * * @see #TAG_STRIP_OFFSETS * @see #TAG_STRIP_BYTE_COUNTS */ public static final String TAG_ROWS_PER_STRIP = "RowsPerStrip"; /** * <p>The total number of bytes in each strip. In the case of JPEG compressed data, this * designation is not necessary. So, this tag shall not be recorded.</p> * * <ul> * <li>Tag = 279</li> * <li>Type = Unsigned short or Unsigned long</li> * <li>Count = StripsPerImage (when using {@link #FORMAT_CHUNKY}) * or {@link #TAG_SAMPLES_PER_PIXEL} * StripsPerImage * (when using {@link #FORMAT_PLANAR})</li> * <li>Default = None</li> * </ul> * * <p>StripsPerImage = floor(({@link #TAG_IMAGE_LENGTH} + {@link #TAG_ROWS_PER_STRIP} - 1) * / {@link #TAG_ROWS_PER_STRIP})</p> */ public static final String TAG_STRIP_BYTE_COUNTS = "StripByteCounts"; /** * <p>The offset to the start byte (SOI) of JPEG compressed thumbnail data. This shall not be * used for primary image JPEG data.</p> * * <ul> * <li>Tag = 513</li> * <li>Type = Unsigned long</li> * <li>Default = None</li> * </ul> */ public static final String TAG_JPEG_INTERCHANGE_FORMAT = "JPEGInterchangeFormat"; /** * <p>The number of bytes of JPEG compressed thumbnail data. This is not used for primary image * JPEG data. JPEG thumbnails are not divided but are recorded as a continuous JPEG bitstream * from SOI to EOI. APPn and COM markers should not be recorded. Compressed thumbnails shall be * recorded in no more than 64 KBytes, including all other data to be recorded in APP1.</p> * * <ul> * <li>Tag = 514</li> * <li>Type = Unsigned long</li> * <li>Default = None</li> * </ul> */ public static final String TAG_JPEG_INTERCHANGE_FORMAT_LENGTH = "JPEGInterchangeFormatLength"; // C. Tags related to Image Data Characteristics /** * <p>A transfer function for the image, described in tabular style. Normally this tag need not * be used, since color space is specified in {@link #TAG_COLOR_SPACE}.</p> * * <ul> * <li>Tag = 301</li> * <li>Type = Unsigned short</li> * <li>Count = 3 * 256</li> * <li>Default = None</li> * </ul> */ public static final String TAG_TRANSFER_FUNCTION = "TransferFunction"; /** * <p>The chromaticity of the white point of the image. Normally this tag need not be used, * since color space is specified in {@link #TAG_COLOR_SPACE}.</p> * * <ul> * <li>Tag = 318</li> * <li>Type = Unsigned rational</li> * <li>Count = 2</li> * <li>Default = None</li> * </ul> */ public static final String TAG_WHITE_POINT = "WhitePoint"; /** * <p>The chromaticity of the three primary colors of the image. Normally this tag need not * be used, since color space is specified in {@link #TAG_COLOR_SPACE}.</p> * * <ul> * <li>Tag = 319</li> * <li>Type = Unsigned rational</li> * <li>Count = 6</li> * <li>Default = None</li> * </ul> */ public static final String TAG_PRIMARY_CHROMATICITIES = "PrimaryChromaticities"; /** * <p>The matrix coefficients for transformation from RGB to YCbCr image data. About * the default value, please refer to JEITA CP-3451C Spec, Annex D.</p> * * <ul> * <li>Tag = 529</li> * <li>Type = Unsigned rational</li> * <li>Count = 3</li> * </ul> */ public static final String TAG_Y_CB_CR_COEFFICIENTS = "YCbCrCoefficients"; /** * <p>The reference black point value and reference white point value. No defaults are given * in TIFF, but the values below are given as defaults here. The color space is declared in * a color space information tag, with the default being the value that gives the optimal image * characteristics Interoperability these conditions</p> * * <ul> * <li>Tag = 532</li> * <li>Type = RATIONAL</li> * <li>Count = 6</li> * <li>Default = [0, 255, 0, 255, 0, 255] (when {@link #TAG_PHOTOMETRIC_INTERPRETATION} * is {@link #PHOTOMETRIC_INTERPRETATION_RGB}) * or [0, 255, 0, 128, 0, 128] (when {@link #TAG_PHOTOMETRIC_INTERPRETATION} * is {@link #PHOTOMETRIC_INTERPRETATION_YCBCR})</li> * </ul> */ public static final String TAG_REFERENCE_BLACK_WHITE = "ReferenceBlackWhite"; // D. Other tags /** * <p>The date and time of image creation. In this standard it is the date and time the file * was changed. The format is "YYYY:MM:DD HH:MM:SS" with time shown in 24-hour format, and * the date and time separated by one blank character ({@code 0x20}). When the date and time * are unknown, all the character spaces except colons (":") should be filled with blank * characters, or else the Interoperability field should be filled with blank characters. * The character string length is 20 Bytes including NULL for termination. When the field is * left blank, it is treated as unknown.</p> * * <ul> * <li>Tag = 306</li> * <li>Type = String</li> * <li>Length = 19</li> * <li>Default = None</li> * </ul> */ public static final String TAG_DATETIME = "DateTime"; /** * <p>An ASCII string giving the title of the image. It is possible to be added a comment * such as "1988 company picnic" or the like. Two-byte character codes cannot be used. When * a 2-byte code is necessary, {@link #TAG_USER_COMMENT} is to be used.</p> * * <ul> * <li>Tag = 270</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_IMAGE_DESCRIPTION = "ImageDescription"; /** * <p>The manufacturer of the recording equipment. This is the manufacturer of the DSC, * scanner, video digitizer or other equipment that generated the image. When the field is left * blank, it is treated as unknown.</p> * * <ul> * <li>Tag = 271</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_MAKE = "Make"; /** * <p>The model name or model number of the equipment. This is the model name of number of * the DSC, scanner, video digitizer or other equipment that generated the image. When * the field is left blank, it is treated as unknown.</p> * * <ul> * <li>Tag = 272</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_MODEL = "Model"; /** * <p>This tag records the name and version of the software or firmware of the camera or image * input device used to generate the image. The detailed format is not specified, but it is * recommended that the example shown below be followed. When the field is left blank, it is * treated as unknown.</p> * * <p>Ex.) "Exif Software Version 1.00a".</p> * * <ul> * <li>Tag = 305</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_SOFTWARE = "Software"; /** * <p>This tag records the name of the camera owner, photographer or image creator. * The detailed format is not specified, but it is recommended that the information be written * as in the example below for ease of Interoperability. When the field is left blank, it is * treated as unknown.</p> * * <p>Ex.) "Camera owner, John Smith; Photographer, Michael Brown; Image creator, * Ken James"</p> * * <ul> * <li>Tag = 315</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_ARTIST = "Artist"; /** * <p>Copyright information. In this standard the tag is used to indicate both the photographer * and editor copyrights. It is the copyright notice of the person or organization claiming * rights to the image. The Interoperability copyright statement including date and rights * should be written in this field; e.g., "Copyright, John Smith, 19xx. All rights reserved." * In this standard the field records both the photographer and editor copyrights, with each * recorded in a separate part of the statement. When there is a clear distinction between * the photographer and editor copyrights, these are to be written in the order of photographer * followed by editor copyright, separated by NULL (in this case, since the statement also ends * with a NULL, there are two NULL codes) (see example 1). When only the photographer copyright * is given, it is terminated by one NULL code (see example 2). When only the editor copyright * is given, the photographer copyright part consists of one space followed by a terminating * NULL code, then the editor copyright is given (see example 3). When the field is left blank, * it is treated as unknown.</p> * * <p>Ex. 1) When both the photographer copyright and editor copyright are given. * <ul><li>Photographer copyright + NULL + editor copyright + NULL</li></ul></p> * <p>Ex. 2) When only the photographer copyright is given. * <ul><li>Photographer copyright + NULL</li></ul></p> * <p>Ex. 3) When only the editor copyright is given. * <ul><li>Space ({@code 0x20}) + NULL + editor copyright + NULL</li></ul></p> * * <ul> * <li>Tag = 315</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_COPYRIGHT = "Copyright"; // Exif IFD Attribute Information // A. Tags related to version /** * <p>The version of this standard supported. Nonexistence of this field is taken to mean * nonconformance to the standard. In according with conformance to this standard, this tag * shall be recorded like "0230” as 4-byte ASCII.</p> * * <ul> * <li>Tag = 36864</li> * <li>Type = Undefined</li> * <li>Length = 4</li> * <li>Default = "0230"</li> * </ul> */ public static final String TAG_EXIF_VERSION = "ExifVersion"; /** * <p>The Flashpix format version supported by a FPXR file. If the FPXR function supports * Flashpix format Ver. 1.0, this is indicated similarly to {@link #TAG_EXIF_VERSION} by * recording "0100" as 4-byte ASCII.</p> * * <ul> * <li>Tag = 40960</li> * <li>Type = Undefined</li> * <li>Length = 4</li> * <li>Default = "0100"</li> * </ul> */ public static final String TAG_FLASHPIX_VERSION = "FlashpixVersion"; // B. Tags related to image data characteristics /** * <p>The color space information tag is always recorded as the color space specifier. * Normally {@link #COLOR_SPACE_S_RGB} is used to define the color space based on the PC * monitor conditions and environment. If a color space other than {@link #COLOR_SPACE_S_RGB} * is used, {@link #COLOR_SPACE_UNCALIBRATED} is set. Image data recorded as * {@link #COLOR_SPACE_UNCALIBRATED} may be treated as {@link #COLOR_SPACE_S_RGB} when it is * converted to Flashpix.</p> * * <ul> * <li>Tag = 40961</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * </ul> * * @see #COLOR_SPACE_S_RGB * @see #COLOR_SPACE_UNCALIBRATED */ public static final String TAG_COLOR_SPACE = "ColorSpace"; /** * <p>Indicates the value of coefficient gamma. The formula of transfer function used for image * reproduction is expressed as follows.</p> * * <p>(Reproduced value) = (Input value) ^ gamma</p> * * <p>Both reproduced value and input value indicate normalized value, whose minimum value is * 0 and maximum value is 1.</p> * * <ul> * <li>Tag = 42240</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GAMMA = "Gamma"; // C. Tags related to image configuration /** * <p>Information specific to compressed data. When a compressed file is recorded, the valid * width of the meaningful image shall be recorded in this tag, whether or not there is padding * data or a restart marker. This tag shall not exist in an uncompressed file.</p> * * <ul> * <li>Tag = 40962</li> * <li>Type = Unsigned short or Unsigned long</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_PIXEL_X_DIMENSION = "PixelXDimension"; /** * <p>Information specific to compressed data. When a compressed file is recorded, the valid * height of the meaningful image shall be recorded in this tag, whether or not there is * padding data or a restart marker. This tag shall not exist in an uncompressed file. * Since data padding is unnecessary in the vertical direction, the number of lines recorded * in this valid image height tag will in fact be the same as that recorded in the SOF.</p> * * <ul> * <li>Tag = 40963</li> * <li>Type = Unsigned short or Unsigned long</li> * <li>Count = 1</li> * </ul> */ public static final String TAG_PIXEL_Y_DIMENSION = "PixelYDimension"; /** * <p>Information specific to compressed data. The channels of each component are arranged * in order from the 1st component to the 4th. For uncompressed data the data arrangement is * given in the {@link #TAG_PHOTOMETRIC_INTERPRETATION}. However, since * {@link #TAG_PHOTOMETRIC_INTERPRETATION} can only express the order of Y, Cb and Cr, this tag * is provided for cases when compressed data uses components other than Y, Cb, and Cr and to * enable support of other sequences.</p> * * <ul> * <li>Tag = 37121</li> * <li>Type = Undefined</li> * <li>Length = 4</li> * <li>Default = 4 5 6 0 (if RGB uncompressed) or 1 2 3 0 (other cases)</li> * <ul> * <li>0 = does not exist</li> * <li>1 = Y</li> * <li>2 = Cb</li> * <li>3 = Cr</li> * <li>4 = R</li> * <li>5 = G</li> * <li>6 = B</li> * <li>other = reserved</li> * </ul> * </ul> */ public static final String TAG_COMPONENTS_CONFIGURATION = "ComponentsConfiguration"; /** * <p>Information specific to compressed data. The compression mode used for a compressed image * is indicated in unit bits per pixel.</p> * * <ul> * <li>Tag = 37122</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_COMPRESSED_BITS_PER_PIXEL = "CompressedBitsPerPixel"; // D. Tags related to user information /** * <p>A tag for manufacturers of Exif/DCF writers to record any desired information. * The contents are up to the manufacturer, but this tag shall not be used for any other than * its intended purpose.</p> * * <ul> * <li>Tag = 37500</li> * <li>Type = Undefined</li> * <li>Default = None</li> * </ul> */ public static final String TAG_MAKER_NOTE = "MakerNote"; /** * <p>A tag for Exif users to write keywords or comments on the image besides those in * {@link #TAG_IMAGE_DESCRIPTION}, and without the character code limitations of it.</p> * * <ul> * <li>Tag = 37510</li> * <li>Type = Undefined</li> * <li>Default = None</li> * </ul> */ public static final String TAG_USER_COMMENT = "UserComment"; // E. Tags related to related file information /** * <p>This tag is used to record the name of an audio file related to the image data. The only * relational information recorded here is the Exif audio file name and extension (an ASCII * string consisting of 8 characters + '.' + 3 characters). The path is not recorded.</p> * * <p>When using this tag, audio files shall be recorded in conformance to the Exif audio * format. Writers can also store the data such as Audio within APP2 as Flashpix extension * stream data. Audio files shall be recorded in conformance to the Exif audio format.</p> * * <ul> * <li>Tag = 40964</li> * <li>Type = String</li> * <li>Length = 12</li> * <li>Default = None</li> * </ul> */ public static final String TAG_RELATED_SOUND_FILE = "RelatedSoundFile"; // F. Tags related to date and time /** * <p>The date and time when the original image data was generated. For a DSC the date and time * the picture was taken are recorded. The format is "YYYY:MM:DD HH:MM:SS" with time shown in * 24-hour format, and the date and time separated by one blank character ({@code 0x20}). * When the date and time are unknown, all the character spaces except colons (":") should be * filled with blank characters, or else the Interoperability field should be filled with blank * characters. When the field is left blank, it is treated as unknown.</p> * * <ul> * <li>Tag = 36867</li> * <li>Type = String</li> * <li>Length = 19</li> * <li>Default = None</li> * </ul> */ public static final String TAG_DATETIME_ORIGINAL = "DateTimeOriginal"; /** * <p>The date and time when the image was stored as digital data. If, for example, an image * was captured by DSC and at the same time the file was recorded, then * {@link #TAG_DATETIME_ORIGINAL} and this tag will have the same contents. The format is * "YYYY:MM:DD HH:MM:SS" with time shown in 24-hour format, and the date and time separated by * one blank character ({@code 0x20}). When the date and time are unknown, all the character * spaces except colons (":")should be filled with blank characters, or else * the Interoperability field should be filled with blank characters. When the field is left * blank, it is treated as unknown.</p> * * <ul> * <li>Tag = 36868</li> * <li>Type = String</li> * <li>Length = 19</li> * <li>Default = None</li> * </ul> */ public static final String TAG_DATETIME_DIGITIZED = "DateTimeDigitized"; /** * <p>A tag used to record fractions of seconds for {@link #TAG_DATETIME}.</p> * * <ul> * <li>Tag = 37520</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_SUBSEC_TIME = "SubSecTime"; /** * <p>A tag used to record fractions of seconds for {@link #TAG_DATETIME_ORIGINAL}.</p> * * <ul> * <li>Tag = 37521</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_SUBSEC_TIME_ORIGINAL = "SubSecTimeOriginal"; /** * <p>A tag used to record fractions of seconds for {@link #TAG_DATETIME_DIGITIZED}.</p> * * <ul> * <li>Tag = 37522</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_SUBSEC_TIME_DIGITIZED = "SubSecTimeDigitized"; // G. Tags related to picture-taking condition /** * <p>Exposure time, given in seconds.</p> * * <ul> * <li>Tag = 33434</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_EXPOSURE_TIME = "ExposureTime"; /** * <p>The F number.</p> * * <ul> * <li>Tag = 33437</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_F_NUMBER = "FNumber"; /** * <p>TThe class of the program used by the camera to set exposure when the picture is taken. * The tag values are as follows.</p> * * <ul> * <li>Tag = 34850</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #EXPOSURE_PROGRAM_NOT_DEFINED}</li> * </ul> * * @see #EXPOSURE_PROGRAM_NOT_DEFINED * @see #EXPOSURE_PROGRAM_MANUAL * @see #EXPOSURE_PROGRAM_NORMAL * @see #EXPOSURE_PROGRAM_APERTURE_PRIORITY * @see #EXPOSURE_PROGRAM_SHUTTER_PRIORITY * @see #EXPOSURE_PROGRAM_CREATIVE * @see #EXPOSURE_PROGRAM_ACTION * @see #EXPOSURE_PROGRAM_PORTRAIT_MODE * @see #EXPOSURE_PROGRAM_LANDSCAPE_MODE */ public static final String TAG_EXPOSURE_PROGRAM = "ExposureProgram"; /** * <p>Indicates the spectral sensitivity of each channel of the camera used. The tag value is * an ASCII string compatible with the standard developed by the ASTM Technical committee.</p> * * <ul> * <li>Tag = 34852</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_SPECTRAL_SENSITIVITY = "SpectralSensitivity"; /** * @deprecated Use {@link #TAG_PHOTOGRAPHIC_SENSITIVITY} instead. * @see #TAG_PHOTOGRAPHIC_SENSITIVITY */ @Deprecated public static final String TAG_ISO_SPEED_RATINGS = "ISOSpeedRatings"; /** * <p>This tag indicates the sensitivity of the camera or input device when the image was shot. * More specifically, it indicates one of the following values that are parameters defined in * ISO 12232: standard output sensitivity (SOS), recommended exposure index (REI), or ISO * speed. Accordingly, if a tag corresponding to a parameter that is designated by * {@link #TAG_SENSITIVITY_TYPE} is recorded, the values of the tag and of this tag are * the same. However, if the value is 65535 or higher, the value of this tag shall be 65535. * When recording this tag, {@link #TAG_SENSITIVITY_TYPE} should also be recorded. In addition, * while “Count = Any”, only 1 count should be used when recording this tag.</p> * * <ul> * <li>Tag = 34855</li> * <li>Type = Unsigned short</li> * <li>Count = Any</li> * <li>Default = None</li> * </ul> */ public static final String TAG_PHOTOGRAPHIC_SENSITIVITY = "PhotographicSensitivity"; /** * <p>Indicates the Opto-Electric Conversion Function (OECF) specified in ISO 14524. OECF is * the relationship between the camera optical input and the image values.</p> * * <ul> * <li>Tag = 34856</li> * <li>Type = Undefined</li> * <li>Default = None</li> * </ul> */ public static final String TAG_OECF = "OECF"; /** * <p>This tag indicates which one of the parameters of ISO12232 is * {@link #TAG_PHOTOGRAPHIC_SENSITIVITY}. Although it is an optional tag, it should be recorded * when {@link #TAG_PHOTOGRAPHIC_SENSITIVITY} is recorded.</p> * * <ul> * <li>Tag = 34864</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> * * @see #SENSITIVITY_TYPE_UNKNOWN * @see #SENSITIVITY_TYPE_SOS * @see #SENSITIVITY_TYPE_REI * @see #SENSITIVITY_TYPE_ISO_SPEED * @see #SENSITIVITY_TYPE_SOS_AND_REI * @see #SENSITIVITY_TYPE_SOS_AND_ISO * @see #SENSITIVITY_TYPE_REI_AND_ISO * @see #SENSITIVITY_TYPE_SOS_AND_REI_AND_ISO */ public static final String TAG_SENSITIVITY_TYPE = "SensitivityType"; /** * <p>This tag indicates the standard output sensitivity value of a camera or input device * defined in ISO 12232. When recording this tag, {@link #TAG_PHOTOGRAPHIC_SENSITIVITY} and * {@link #TAG_SENSITIVITY_TYPE} shall also be recorded.</p> * * <ul> * <li>Tag = 34865</li> * <li>Type = Unsigned long</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_STANDARD_OUTPUT_SENSITIVITY = "StandardOutputSensitivity"; /** * <p>This tag indicates the recommended exposure index value of a camera or input device * defined in ISO 12232. When recording this tag, {@link #TAG_PHOTOGRAPHIC_SENSITIVITY} and * {@link #TAG_SENSITIVITY_TYPE} shall also be recorded.</p> * * <ul> * <li>Tag = 34866</li> * <li>Type = Unsigned long</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_RECOMMENDED_EXPOSURE_INDEX = "RecommendedExposureIndex"; /** * <p>This tag indicates the ISO speed value of a camera or input device that is defined in * ISO 12232. When recording this tag, {@link #TAG_PHOTOGRAPHIC_SENSITIVITY} and * {@link #TAG_SENSITIVITY_TYPE} shall also be recorded.</p> * * <ul> * <li>Tag = 34867</li> * <li>Type = Unsigned long</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_ISO_SPEED = "ISOSpeed"; /** * <p>This tag indicates the ISO speed latitude yyy value of a camera or input device that is * defined in ISO 12232. However, this tag shall not be recorded without {@link #TAG_ISO_SPEED} * and {@link #TAG_ISO_SPEED_LATITUDE_ZZZ}.</p> * * <ul> * <li>Tag = 34868</li> * <li>Type = Unsigned long</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_ISO_SPEED_LATITUDE_YYY = "ISOSpeedLatitudeyyy"; /** * <p>This tag indicates the ISO speed latitude zzz value of a camera or input device that is * defined in ISO 12232. However, this tag shall not be recorded without {@link #TAG_ISO_SPEED} * and {@link #TAG_ISO_SPEED_LATITUDE_YYY}.</p> * * <ul> * <li>Tag = 34869</li> * <li>Type = Unsigned long</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_ISO_SPEED_LATITUDE_ZZZ = "ISOSpeedLatitudezzz"; /** * <p>Shutter speed. The unit is the APEX setting.</p> * * <ul> * <li>Tag = 37377</li> * <li>Type = Signed rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_SHUTTER_SPEED_VALUE = "ShutterSpeedValue"; /** * <p>The lens aperture. The unit is the APEX value.</p> * * <ul> * <li>Tag = 37378</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_APERTURE_VALUE = "ApertureValue"; /** * <p>The value of brightness. The unit is the APEX value. Ordinarily it is given in the range * of -99.99 to 99.99. Note that if the numerator of the recorded value is 0xFFFFFFFF, * Unknown shall be indicated.</p> * * <ul> * <li>Tag = 37379</li> * <li>Type = Signed rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_BRIGHTNESS_VALUE = "BrightnessValue"; /** * <p>The exposure bias. The unit is the APEX value. Ordinarily it is given in the range of * -99.99 to 99.99.</p> * * <ul> * <li>Tag = 37380</li> * <li>Type = Signed rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_EXPOSURE_BIAS_VALUE = "ExposureBiasValue"; /** * <p>The smallest F number of the lens. The unit is the APEX value. Ordinarily it is given * in the range of 00.00 to 99.99, but it is not limited to this range.</p> * * <ul> * <li>Tag = 37381</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_MAX_APERTURE_VALUE = "MaxApertureValue"; /** * <p>The distance to the subject, given in meters. Note that if the numerator of the recorded * value is 0xFFFFFFFF, Infinity shall be indicated; and if the numerator is 0, Distance * unknown shall be indicated.</p> * * <ul> * <li>Tag = 37382</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_SUBJECT_DISTANCE = "SubjectDistance"; /** * <p>The metering mode.</p> * * <ul> * <li>Tag = 37383</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #METERING_MODE_UNKNOWN}</li> * </ul> * * @see #METERING_MODE_UNKNOWN * @see #METERING_MODE_AVERAGE * @see #METERING_MODE_CENTER_WEIGHT_AVERAGE * @see #METERING_MODE_SPOT * @see #METERING_MODE_MULTI_SPOT * @see #METERING_MODE_PATTERN * @see #METERING_MODE_PARTIAL * @see #METERING_MODE_OTHER */ public static final String TAG_METERING_MODE = "MeteringMode"; /** * <p>The kind of light source.</p> * * <ul> * <li>Tag = 37384</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #LIGHT_SOURCE_UNKNOWN}</li> * </ul> * * @see #LIGHT_SOURCE_UNKNOWN * @see #LIGHT_SOURCE_DAYLIGHT * @see #LIGHT_SOURCE_FLUORESCENT * @see #LIGHT_SOURCE_TUNGSTEN * @see #LIGHT_SOURCE_FLASH * @see #LIGHT_SOURCE_FINE_WEATHER * @see #LIGHT_SOURCE_CLOUDY_WEATHER * @see #LIGHT_SOURCE_SHADE * @see #LIGHT_SOURCE_DAYLIGHT_FLUORESCENT * @see #LIGHT_SOURCE_DAY_WHITE_FLUORESCENT * @see #LIGHT_SOURCE_COOL_WHITE_FLUORESCENT * @see #LIGHT_SOURCE_WHITE_FLUORESCENT * @see #LIGHT_SOURCE_WARM_WHITE_FLUORESCENT * @see #LIGHT_SOURCE_STANDARD_LIGHT_A * @see #LIGHT_SOURCE_STANDARD_LIGHT_B * @see #LIGHT_SOURCE_STANDARD_LIGHT_C * @see #LIGHT_SOURCE_D55 * @see #LIGHT_SOURCE_D65 * @see #LIGHT_SOURCE_D75 * @see #LIGHT_SOURCE_D50 * @see #LIGHT_SOURCE_ISO_STUDIO_TUNGSTEN * @see #LIGHT_SOURCE_OTHER */ public static final String TAG_LIGHT_SOURCE = "LightSource"; /** * <p>This tag indicates the status of flash when the image was shot. Bit 0 indicates the flash * firing status, bits 1 and 2 indicate the flash return status, bits 3 and 4 indicate * the flash mode, bit 5 indicates whether the flash function is present, and bit 6 indicates * "red eye" mode.</p> * * <ul> * <li>Tag = 37385</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * </ul> * * @see #FLAG_FLASH_FIRED * @see #FLAG_FLASH_RETURN_LIGHT_NOT_DETECTED * @see #FLAG_FLASH_RETURN_LIGHT_DETECTED * @see #FLAG_FLASH_MODE_COMPULSORY_FIRING * @see #FLAG_FLASH_MODE_COMPULSORY_SUPPRESSION * @see #FLAG_FLASH_MODE_AUTO * @see #FLAG_FLASH_NO_FLASH_FUNCTION * @see #FLAG_FLASH_RED_EYE_SUPPORTED */ public static final String TAG_FLASH = "Flash"; /** * <p>This tag indicates the location and area of the main subject in the overall scene.</p> * * <ul> * <li>Tag = 37396</li> * <li>Type = Unsigned short</li> * <li>Count = 2 or 3 or 4</li> * <li>Default = None</li> * </ul> * * <p>The subject location and area are defined by Count values as follows.</p> * * <ul> * <li>Count = 2 Indicates the location of the main subject as coordinates. The first value * is the X coordinate and the second is the Y coordinate.</li> * <li>Count = 3 The area of the main subject is given as a circle. The circular area is * expressed as center coordinates and diameter. The first value is * the center X coordinate, the second is the center Y coordinate, and * the third is the diameter.</li> * <li>Count = 4 The area of the main subject is given as a rectangle. The rectangular * area is expressed as center coordinates and area dimensions. The first * value is the center X coordinate, the second is the center Y coordinate, * the third is the width of the area, and the fourth is the height of * the area.</li> * </ul> * * <p>Note that the coordinate values, width, and height are expressed in relation to the upper * left as origin, prior to rotation processing as per {@link #TAG_ORIENTATION}.</p> */ public static final String TAG_SUBJECT_AREA = "SubjectArea"; /** * <p>The actual focal length of the lens, in mm. Conversion is not made to the focal length * of a 35mm film camera.</p> * * <ul> * <li>Tag = 37386</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_FOCAL_LENGTH = "FocalLength"; /** * <p>Indicates the strobe energy at the time the image is captured, as measured in Beam Candle * Power Seconds (BCPS).</p> * * <ul> * <li>Tag = 41483</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_FLASH_ENERGY = "FlashEnergy"; /** * <p>This tag records the camera or input device spatial frequency table and SFR values in * the direction of image width, image height, and diagonal direction, as specified in * ISO 12233.</p> * * <ul> * <li>Tag = 41484</li> * <li>Type = Undefined</li> * <li>Default = None</li> * </ul> */ public static final String TAG_SPATIAL_FREQUENCY_RESPONSE = "SpatialFrequencyResponse"; /** * <p>Indicates the number of pixels in the image width (X) direction per * {@link #TAG_FOCAL_PLANE_RESOLUTION_UNIT} on the camera focal plane.</p> * * <ul> * <li>Tag = 41486</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_FOCAL_PLANE_X_RESOLUTION = "FocalPlaneXResolution"; /** * <p>Indicates the number of pixels in the image height (Y) direction per * {@link #TAG_FOCAL_PLANE_RESOLUTION_UNIT} on the camera focal plane.</p> * * <ul> * <li>Tag = 41487</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_FOCAL_PLANE_Y_RESOLUTION = "FocalPlaneYResolution"; /** * <p>Indicates the unit for measuring {@link #TAG_FOCAL_PLANE_X_RESOLUTION} and * {@link #TAG_FOCAL_PLANE_Y_RESOLUTION}. This value is the same as * {@link #TAG_RESOLUTION_UNIT}.</p> * * <ul> * <li>Tag = 41488</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #RESOLUTION_UNIT_INCHES}</li> * </ul> * * @see #TAG_RESOLUTION_UNIT * @see #RESOLUTION_UNIT_INCHES * @see #RESOLUTION_UNIT_CENTIMETERS */ public static final String TAG_FOCAL_PLANE_RESOLUTION_UNIT = "FocalPlaneResolutionUnit"; /** * <p>Indicates the location of the main subject in the scene. The value of this tag represents * the pixel at the center of the main subject relative to the left edge, prior to rotation * processing as per {@link #TAG_ORIENTATION}. The first value indicates the X column number * and second indicates the Y row number. When a camera records the main subject location, * it is recommended that {@link #TAG_SUBJECT_AREA} be used instead of this tag.</p> * * <ul> * <li>Tag = 41492</li> * <li>Type = Unsigned short</li> * <li>Count = 2</li> * <li>Default = None</li> * </ul> */ public static final String TAG_SUBJECT_LOCATION = "SubjectLocation"; /** * <p>Indicates the exposure index selected on the camera or input device at the time the image * is captured.</p> * * <ul> * <li>Tag = 41493</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_EXPOSURE_INDEX = "ExposureIndex"; /** * <p>Indicates the image sensor type on the camera or input device.</p> * * <ul> * <li>Tag = 41495</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> * * @see #SENSOR_TYPE_NOT_DEFINED * @see #SENSOR_TYPE_ONE_CHIP * @see #SENSOR_TYPE_TWO_CHIP * @see #SENSOR_TYPE_THREE_CHIP * @see #SENSOR_TYPE_COLOR_SEQUENTIAL * @see #SENSOR_TYPE_TRILINEAR * @see #SENSOR_TYPE_COLOR_SEQUENTIAL_LINEAR */ public static final String TAG_SENSING_METHOD = "SensingMethod"; /** * <p>Indicates the image source. If a DSC recorded the image, this tag value always shall * be set to {@link #FILE_SOURCE_DSC}.</p> * * <ul> * <li>Tag = 41728</li> * <li>Type = Undefined</li> * <li>Length = 1</li> * <li>Default = {@link #FILE_SOURCE_DSC}</li> * </ul> * * @see #FILE_SOURCE_OTHER * @see #FILE_SOURCE_TRANSPARENT_SCANNER * @see #FILE_SOURCE_REFLEX_SCANNER * @see #FILE_SOURCE_DSC */ public static final String TAG_FILE_SOURCE = "FileSource"; /** * <p>Indicates the type of scene. If a DSC recorded the image, this tag value shall always * be set to {@link #SCENE_TYPE_DIRECTLY_PHOTOGRAPHED}.</p> * * <ul> * <li>Tag = 41729</li> * <li>Type = Undefined</li> * <li>Length = 1</li> * <li>Default = 1</li> * </ul> * * @see #SCENE_TYPE_DIRECTLY_PHOTOGRAPHED */ public static final String TAG_SCENE_TYPE = "SceneType"; /** * <p>Indicates the color filter array (CFA) geometric pattern of the image sensor when * a one-chip color area sensor is used. It does not apply to all sensing methods.</p> * * <ul> * <li>Tag = 41730</li> * <li>Type = Undefined</li> * <li>Default = None</li> * </ul> * * @see #TAG_SENSING_METHOD * @see #SENSOR_TYPE_ONE_CHIP */ public static final String TAG_CFA_PATTERN = "CFAPattern"; /** * <p>This tag indicates the use of special processing on image data, such as rendering geared * to output. When special processing is performed, the Exif/DCF reader is expected to disable * or minimize any further processing.</p> * * <ul> * <li>Tag = 41985</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #RENDERED_PROCESS_NORMAL}</li> * </ul> * * @see #RENDERED_PROCESS_NORMAL * @see #RENDERED_PROCESS_CUSTOM */ public static final String TAG_CUSTOM_RENDERED = "CustomRendered"; /** * <p>This tag indicates the exposure mode set when the image was shot. * In {@link #EXPOSURE_MODE_AUTO_BRACKET}, the camera shoots a series of frames of the same * scene at different exposure settings.</p> * * <ul> * <li>Tag = 41986</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> * * @see #EXPOSURE_MODE_AUTO * @see #EXPOSURE_MODE_MANUAL * @see #EXPOSURE_MODE_AUTO_BRACKET */ public static final String TAG_EXPOSURE_MODE = "ExposureMode"; /** * <p>This tag indicates the white balance mode set when the image was shot.</p> * * <ul> * <li>Tag = 41987</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> * * @see #WHITEBALANCE_AUTO * @see #WHITEBALANCE_MANUAL */ public static final String TAG_WHITE_BALANCE = "WhiteBalance"; /** * <p>This tag indicates the digital zoom ratio when the image was shot. If the numerator of * the recorded value is 0, this indicates that digital zoom was not used.</p> * * <ul> * <li>Tag = 41988</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_DIGITAL_ZOOM_RATIO = "DigitalZoomRatio"; /** * <p>This tag indicates the equivalent focal length assuming a 35mm film camera, in mm. * A value of 0 means the focal length is unknown. Note that this tag differs from * {@link #TAG_FOCAL_LENGTH}.</p> * * <ul> * <li>Tag = 41989</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_FOCAL_LENGTH_IN_35MM_FILM = "FocalLengthIn35mmFilm"; /** * <p>This tag indicates the type of scene that was shot. It may also be used to record * the mode in which the image was shot. Note that this differs from * {@link #TAG_SCENE_TYPE}.</p> * * <ul> * <li>Tag = 41990</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = 0</li> * </ul> * * @see #SCENE_CAPTURE_TYPE_STANDARD * @see #SCENE_CAPTURE_TYPE_LANDSCAPE * @see #SCENE_CAPTURE_TYPE_PORTRAIT * @see #SCENE_CAPTURE_TYPE_NIGHT */ public static final String TAG_SCENE_CAPTURE_TYPE = "SceneCaptureType"; /** * <p>This tag indicates the degree of overall image gain adjustment.</p> * * <ul> * <li>Tag = 41991</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> * * @see #GAIN_CONTROL_NONE * @see #GAIN_CONTROL_LOW_GAIN_UP * @see #GAIN_CONTROL_HIGH_GAIN_UP * @see #GAIN_CONTROL_LOW_GAIN_DOWN * @see #GAIN_CONTROL_HIGH_GAIN_DOWN */ public static final String TAG_GAIN_CONTROL = "GainControl"; /** * <p>This tag indicates the direction of contrast processing applied by the camera when * the image was shot.</p> * * <ul> * <li>Tag = 41992</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #CONTRAST_NORMAL}</li> * </ul> * * @see #CONTRAST_NORMAL * @see #CONTRAST_SOFT * @see #CONTRAST_HARD */ public static final String TAG_CONTRAST = "Contrast"; /** * <p>This tag indicates the direction of saturation processing applied by the camera when * the image was shot.</p> * * <ul> * <li>Tag = 41993</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #SATURATION_NORMAL}</li> * </ul> * * @see #SATURATION_NORMAL * @see #SATURATION_LOW * @see #SATURATION_HIGH */ public static final String TAG_SATURATION = "Saturation"; /** * <p>This tag indicates the direction of sharpness processing applied by the camera when * the image was shot.</p> * * <ul> * <li>Tag = 41994</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = {@link #SHARPNESS_NORMAL}</li> * </ul> * * @see #SHARPNESS_NORMAL * @see #SHARPNESS_SOFT * @see #SHARPNESS_HARD */ public static final String TAG_SHARPNESS = "Sharpness"; /** * <p>This tag indicates information on the picture-taking conditions of a particular camera * model. The tag is used only to indicate the picture-taking conditions in the Exif/DCF * reader.</p> * * <ul> * <li>Tag = 41995</li> * <li>Type = Undefined</li> * <li>Default = None</li> * </ul> */ public static final String TAG_DEVICE_SETTING_DESCRIPTION = "DeviceSettingDescription"; /** * <p>This tag indicates the distance to the subject.</p> * * <ul> * <li>Tag = 41996</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> * * @see #SUBJECT_DISTANCE_RANGE_UNKNOWN * @see #SUBJECT_DISTANCE_RANGE_MACRO * @see #SUBJECT_DISTANCE_RANGE_CLOSE_VIEW * @see #SUBJECT_DISTANCE_RANGE_DISTANT_VIEW */ public static final String TAG_SUBJECT_DISTANCE_RANGE = "SubjectDistanceRange"; // H. Other tags /** * <p>This tag indicates an identifier assigned uniquely to each image. It is recorded as * an ASCII string equivalent to hexadecimal notation and 128-bit fixed length.</p> * * <ul> * <li>Tag = 42016</li> * <li>Type = String</li> * <li>Length = 32</li> * <li>Default = None</li> * </ul> */ public static final String TAG_IMAGE_UNIQUE_ID = "ImageUniqueID"; /** * <p>This tag records the owner of a camera used in photography as an ASCII string.</p> * * <ul> * <li>Tag = 42032</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_CAMARA_OWNER_NAME = "CameraOwnerName"; /** * <p>This tag records the serial number of the body of the camera that was used in photography * as an ASCII string.</p> * * <ul> * <li>Tag = 42033</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_BODY_SERIAL_NUMBER = "BodySerialNumber"; /** * <p>This tag notes minimum focal length, maximum focal length, minimum F number in the * minimum focal length, and minimum F number in the maximum focal length, which are * specification information for the lens that was used in photography. When the minimum * F number is unknown, the notation is 0/0.</p> * * <ul> * <li>Tag = 42034</li> * <li>Type = Unsigned rational</li> * <li>Count = 4</li> * <li>Default = None</li> * <ul> * <li>Value 1 := Minimum focal length (unit: mm)</li> * <li>Value 2 : = Maximum focal length (unit: mm)</li> * <li>Value 3 : = Minimum F number in the minimum focal length</li> * <li>Value 4 : = Minimum F number in the maximum focal length</li> * </ul> * </ul> */ public static final String TAG_LENS_SPECIFICATION = "LensSpecification"; /** * <p>This tag records the lens manufacturer as an ASCII string.</p> * * <ul> * <li>Tag = 42035</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_LENS_MAKE = "LensMake"; /** * <p>This tag records the lens’s model name and model number as an ASCII string.</p> * * <ul> * <li>Tag = 42036</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_LENS_MODEL = "LensModel"; /** * <p>This tag records the serial number of the interchangeable lens that was used in * photography as an ASCII string.</p> * * <ul> * <li>Tag = 42037</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_LENS_SERIAL_NUMBER = "LensSerialNumber"; // GPS Attribute Information /** * <p>Indicates the version of GPS Info IFD. The version is given as 2.3.0.0. This tag is * mandatory when GPS-related tags are present. Note that this tag is written as a different * byte than {@link #TAG_EXIF_VERSION}.</p> * * <ul> * <li>Tag = 0</li> * <li>Type = Byte</li> * <li>Count = 4</li> * <li>Default = 2.3.0.0</li> * <ul> * <li>2300 = Version 2.3</li> * <li>Other = reserved</li> * </ul> * </ul> */ public static final String TAG_GPS_VERSION_ID = "GPSVersionID"; /** * <p>Indicates whether the latitude is north or south latitude.</p> * * <ul> * <li>Tag = 1</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = None</li> * </ul> * * @see #LATITUDE_NORTH * @see #LATITUDE_SOUTH */ public static final String TAG_GPS_LATITUDE_REF = "GPSLatitudeRef"; /** * <p>Indicates the latitude. The latitude is expressed as three RATIONAL values giving * the degrees, minutes, and seconds, respectively. If latitude is expressed as degrees, * minutes and seconds, a typical format would be dd/1,mm/1,ss/1. When degrees and minutes are * used and, for example, fractions of minutes are given up to two decimal places, the format * would be dd/1,mmmm/100,0/1.</p> * * <ul> * <li>Tag = 2</li> * <li>Type = Unsigned rational</li> * <li>Count = 3</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_LATITUDE = "GPSLatitude"; /** * <p>Indicates whether the longitude is east or west longitude.</p> * * <ul> * <li>Tag = 3</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = None</li> * </ul> * * @see #LONGITUDE_EAST * @see #LONGITUDE_WEST */ public static final String TAG_GPS_LONGITUDE_REF = "GPSLongitudeRef"; /** * <p>Indicates the longitude. The longitude is expressed as three RATIONAL values giving * the degrees, minutes, and seconds, respectively. If longitude is expressed as degrees, * minutes and seconds, a typical format would be ddd/1,mm/1,ss/1. When degrees and minutes * are used and, for example, fractions of minutes are given up to two decimal places, * the format would be ddd/1,mmmm/100,0/1.</p> * * <ul> * <li>Tag = 4</li> * <li>Type = Unsigned rational</li> * <li>Count = 3</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_LONGITUDE = "GPSLongitude"; /** * <p>Indicates the altitude used as the reference altitude. If the reference is sea level * and the altitude is above sea level, 0 is given. If the altitude is below sea level, * a value of 1 is given and the altitude is indicated as an absolute value in * {@link #TAG_GPS_ALTITUDE}.</p> * * <ul> * <li>Tag = 5</li> * <li>Type = Byte</li> * <li>Count = 1</li> * <li>Default = 0</li> * </ul> * * @see #ALTITUDE_ABOVE_SEA_LEVEL * @see #ALTITUDE_BELOW_SEA_LEVEL */ public static final String TAG_GPS_ALTITUDE_REF = "GPSAltitudeRef"; /** * <p>Indicates the altitude based on the reference in {@link #TAG_GPS_ALTITUDE_REF}. * The reference unit is meters.</p> * * <ul> * <li>Tag = 6</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_ALTITUDE = "GPSAltitude"; /** * <p>Indicates the time as UTC (Coordinated Universal Time). TimeStamp is expressed as three * unsigned rational values giving the hour, minute, and second.</p> * * <ul> * <li>Tag = 7</li> * <li>Type = Unsigned rational</li> * <li>Count = 3</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_TIMESTAMP = "GPSTimeStamp"; /** * <p>Indicates the GPS satellites used for measurements. This tag may be used to describe * the number of satellites, their ID number, angle of elevation, azimuth, SNR and other * information in ASCII notation. The format is not specified. If the GPS receiver is incapable * of taking measurements, value of the tag shall be set to {@code null}.</p> * * <ul> * <li>Tag = 8</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_SATELLITES = "GPSSatellites"; /** * <p>Indicates the status of the GPS receiver when the image is recorded. 'A' means * measurement is in progress, and 'V' means the measurement is interrupted.</p> * * <ul> * <li>Tag = 9</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = None</li> * </ul> * * @see #GPS_MEASUREMENT_IN_PROGRESS * @see #GPS_MEASUREMENT_INTERRUPTED */ public static final String TAG_GPS_STATUS = "GPSStatus"; /** * <p>Indicates the GPS measurement mode. Originally it was defined for GPS, but it may * be used for recording a measure mode to record the position information provided from * a mobile base station or wireless LAN as well as GPS.</p> * * <ul> * <li>Tag = 10</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = None</li> * </ul> * * @see #GPS_MEASUREMENT_2D * @see #GPS_MEASUREMENT_3D */ public static final String TAG_GPS_MEASURE_MODE = "GPSMeasureMode"; /** * <p>Indicates the GPS DOP (data degree of precision). An HDOP value is written during * two-dimensional measurement, and PDOP during three-dimensional measurement.</p> * * <ul> * <li>Tag = 11</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_DOP = "GPSDOP"; /** * <p>Indicates the unit used to express the GPS receiver speed of movement.</p> * * <ul> * <li>Tag = 12</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = {@link #GPS_SPEED_KILOMETERS_PER_HOUR}</li> * </ul> * * @see #GPS_SPEED_KILOMETERS_PER_HOUR * @see #GPS_SPEED_MILES_PER_HOUR * @see #GPS_SPEED_KNOTS */ public static final String TAG_GPS_SPEED_REF = "GPSSpeedRef"; /** * <p>Indicates the speed of GPS receiver movement.</p> * * <ul> * <li>Tag = 13</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_SPEED = "GPSSpeed"; /** * <p>Indicates the reference for giving the direction of GPS receiver movement.</p> * * <ul> * <li>Tag = 14</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = {@link #GPS_DIRECTION_TRUE}</li> * </ul> * * @see #GPS_DIRECTION_TRUE * @see #GPS_DIRECTION_MAGNETIC */ public static final String TAG_GPS_TRACK_REF = "GPSTrackRef"; /** * <p>Indicates the direction of GPS receiver movement. * The range of values is from 0.00 to 359.99.</p> * * <ul> * <li>Tag = 15</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_TRACK = "GPSTrack"; /** * <p>Indicates the reference for giving the direction of the image when it is captured.</p> * * <ul> * <li>Tag = 16</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = {@link #GPS_DIRECTION_TRUE}</li> * </ul> * * @see #GPS_DIRECTION_TRUE * @see #GPS_DIRECTION_MAGNETIC */ public static final String TAG_GPS_IMG_DIRECTION_REF = "GPSImgDirectionRef"; /** * <p>ndicates the direction of the image when it was captured. * The range of values is from 0.00 to 359.99.</p> * * <ul> * <li>Tag = 17</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_IMG_DIRECTION = "GPSImgDirection"; /** * <p>Indicates the geodetic survey data used by the GPS receiver. If the survey data is * restricted to Japan,the value of this tag is 'TOKYO' or 'WGS-84'. If a GPS Info tag is * recorded, it is strongly recommended that this tag be recorded.</p> * * <ul> * <li>Tag = 18</li> * <li>Type = String</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_MAP_DATUM = "GPSMapDatum"; /** * <p>Indicates whether the latitude of the destination point is north or south latitude.</p> * * <ul> * <li>Tag = 19</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = None</li> * </ul> * * @see #LATITUDE_NORTH * @see #LATITUDE_SOUTH */ public static final String TAG_GPS_DEST_LATITUDE_REF = "GPSDestLatitudeRef"; /** * <p>Indicates the latitude of the destination point. The latitude is expressed as three * unsigned rational values giving the degrees, minutes, and seconds, respectively. * If latitude is expressed as degrees, minutes and seconds, a typical format would be * dd/1,mm/1,ss/1. When degrees and minutes are used and, for example, fractions of minutes * are given up to two decimal places, the format would be dd/1, mmmm/100, 0/1.</p> * * <ul> * <li>Tag = 20</li> * <li>Type = Unsigned rational</li> * <li>Count = 3</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_DEST_LATITUDE = "GPSDestLatitude"; /** * <p>Indicates whether the longitude of the destination point is east or west longitude.</p> * * <ul> * <li>Tag = 21</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = None</li> * </ul> * * @see #LONGITUDE_EAST * @see #LONGITUDE_WEST */ public static final String TAG_GPS_DEST_LONGITUDE_REF = "GPSDestLongitudeRef"; /** * <p>Indicates the longitude of the destination point. The longitude is expressed as three * unsigned rational values giving the degrees, minutes, and seconds, respectively. * If longitude is expressed as degrees, minutes and seconds, a typical format would be ddd/1, * mm/1, ss/1. When degrees and minutes are used and, for example, fractions of minutes are * given up to two decimal places, the format would be ddd/1, mmmm/100, 0/1.</p> * * <ul> * <li>Tag = 22</li> * <li>Type = Unsigned rational</li> * <li>Count = 3</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_DEST_LONGITUDE = "GPSDestLongitude"; /** * <p>Indicates the reference used for giving the bearing to the destination point.</p> * * <ul> * <li>Tag = 23</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = {@link #GPS_DIRECTION_TRUE}</li> * </ul> * * @see #GPS_DIRECTION_TRUE * @see #GPS_DIRECTION_MAGNETIC */ public static final String TAG_GPS_DEST_BEARING_REF = "GPSDestBearingRef"; /** * <p>Indicates the bearing to the destination point. * The range of values is from 0.00 to 359.99.</p> * * <ul> * <li>Tag = 24</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_DEST_BEARING = "GPSDestBearing"; /** * <p>Indicates the unit used to express the distance to the destination point.</p> * * <ul> * <li>Tag = 25</li> * <li>Type = String</li> * <li>Length = 1</li> * <li>Default = {@link #GPS_DISTANCE_KILOMETERS}</li> * </ul> * * @see #GPS_DISTANCE_KILOMETERS * @see #GPS_DISTANCE_MILES * @see #GPS_DISTANCE_NAUTICAL_MILES */ public static final String TAG_GPS_DEST_DISTANCE_REF = "GPSDestDistanceRef"; /** * <p>Indicates the distance to the destination point.</p> * * <ul> * <li>Tag = 26</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_DEST_DISTANCE = "GPSDestDistance"; /** * <p>A character string recording the name of the method used for location finding. * The first byte indicates the character code used, and this is followed by the name of * the method.</p> * * <ul> * <li>Tag = 27</li> * <li>Type = Undefined</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_PROCESSING_METHOD = "GPSProcessingMethod"; /** * <p>A character string recording the name of the GPS area. The first byte indicates * the character code used, and this is followed by the name of the GPS area.</p> * * <ul> * <li>Tag = 28</li> * <li>Type = Undefined</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_AREA_INFORMATION = "GPSAreaInformation"; /** * <p>A character string recording date and time information relative to UTC (Coordinated * Universal Time). The format is "YYYY:MM:DD".</p> * * <ul> * <li>Tag = 29</li> * <li>Type = String</li> * <li>Length = 10</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_DATESTAMP = "GPSDateStamp"; /** * <p>Indicates whether differential correction is applied to the GPS receiver.</p> * * <ul> * <li>Tag = 30</li> * <li>Type = Unsigned short</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> * * @see #GPS_MEASUREMENT_NO_DIFFERENTIAL * @see #GPS_MEASUREMENT_DIFFERENTIAL_CORRECTED */ public static final String TAG_GPS_DIFFERENTIAL = "GPSDifferential"; /** * <p>This tag indicates horizontal positioning errors in meters.</p> * * <ul> * <li>Tag = 31</li> * <li>Type = Unsigned rational</li> * <li>Count = 1</li> * <li>Default = None</li> * </ul> */ public static final String TAG_GPS_H_POSITIONING_ERROR = "GPSHPositioningError"; // Interoperability IFD Attribute Information /** * <p>Indicates the identification of the Interoperability rule.</p> * * <ul> * <li>Tag = 1</li> * <li>Type = String</li> * <li>Length = 4</li> * <li>Default = None</li> * <ul> * <li>"R98" = Indicates a file conforming to R98 file specification of Recommended * Exif Interoperability Rules (Exif R 98) or to DCF basic file stipulated * by Design Rule for Camera File System.</li> * <li>"THM" = Indicates a file conforming to DCF thumbnail file stipulated by Design * rule for Camera File System.</li> * <li>“R03” = Indicates a file conforming to DCF Option File stipulated by Design rule * for Camera File System.</li> * </ul> * </ul> */ public static final String TAG_INTEROPERABILITY_INDEX = "InteroperabilityIndex"; /** * @see #TAG_IMAGE_LENGTH */ public static final String TAG_THUMBNAIL_IMAGE_LENGTH = "ThumbnailImageLength"; /** * @see #TAG_IMAGE_WIDTH */ public static final String TAG_THUMBNAIL_IMAGE_WIDTH = "ThumbnailImageWidth"; /** Type is int. DNG Specification 1.4.0.0. Section 4 */ public static final String TAG_DNG_VERSION = "DNGVersion"; /** Type is int. DNG Specification 1.4.0.0. Section 4 */ public static final String TAG_DEFAULT_CROP_SIZE = "DefaultCropSize"; /** Type is undefined. See Olympus MakerNote tags in http://www.exiv2.org/tags-olympus.html. */ public static final String TAG_ORF_THUMBNAIL_IMAGE = "ThumbnailImage"; /** Type is int. See Olympus Camera Settings tags in http://www.exiv2.org/tags-olympus.html. */ public static final String TAG_ORF_PREVIEW_IMAGE_START = "PreviewImageStart"; /** Type is int. See Olympus Camera Settings tags in http://www.exiv2.org/tags-olympus.html. */ public static final String TAG_ORF_PREVIEW_IMAGE_LENGTH = "PreviewImageLength"; /** Type is int. See Olympus Image Processing tags in http://www.exiv2.org/tags-olympus.html. */ public static final String TAG_ORF_ASPECT_FRAME = "AspectFrame"; /** * Type is int. See PanasonicRaw tags in * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html */ public static final String TAG_RW2_SENSOR_BOTTOM_BORDER = "SensorBottomBorder"; /** * Type is int. See PanasonicRaw tags in * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html */ public static final String TAG_RW2_SENSOR_LEFT_BORDER = "SensorLeftBorder"; /** * Type is int. See PanasonicRaw tags in * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html */ public static final String TAG_RW2_SENSOR_RIGHT_BORDER = "SensorRightBorder"; /** * Type is int. See PanasonicRaw tags in * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html */ public static final String TAG_RW2_SENSOR_TOP_BORDER = "SensorTopBorder"; /** * Type is int. See PanasonicRaw tags in * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html */ public static final String TAG_RW2_ISO = "ISO"; /** * Type is undefined. See PanasonicRaw tags in * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html */ public static final String TAG_RW2_JPG_FROM_RAW = "JpgFromRaw"; /** Type is int. See JEITA CP-3451C Spec Section 3: Bilevel Images. */ public static final String TAG_NEW_SUBFILE_TYPE = "NewSubfileType"; /** Type is int. See JEITA CP-3451C Spec Section 3: Bilevel Images. */ public static final String TAG_SUBFILE_TYPE = "SubfileType"; /** * Private tags used for pointing the other IFD offsets. * The types of the following tags are int. * See JEITA CP-3451C Section 4.6.3: Exif-specific IFD. * For SubIFD, see Note 1 of Adobe PageMaker® 6.0 TIFF Technical Notes. */ private static final String TAG_EXIF_IFD_POINTER = "ExifIFDPointer"; private static final String TAG_GPS_INFO_IFD_POINTER = "GPSInfoIFDPointer"; private static final String TAG_INTEROPERABILITY_IFD_POINTER = "InteroperabilityIFDPointer"; private static final String TAG_SUB_IFD_POINTER = "SubIFDPointer"; // Proprietary pointer tags used for ORF files. // See http://www.exiv2.org/tags-olympus.html private static final String TAG_ORF_CAMERA_SETTINGS_IFD_POINTER = "CameraSettingsIFDPointer"; private static final String TAG_ORF_IMAGE_PROCESSING_IFD_POINTER = "ImageProcessingIFDPointer"; // Private tags used for thumbnail information. private static final String TAG_HAS_THUMBNAIL = "HasThumbnail"; private static final String TAG_THUMBNAIL_OFFSET = "ThumbnailOffset"; private static final String TAG_THUMBNAIL_LENGTH = "ThumbnailLength"; private static final String TAG_THUMBNAIL_DATA = "ThumbnailData"; private static final int MAX_THUMBNAIL_SIZE = 512; // Constants used for the Orientation Exif tag. public static final int ORIENTATION_UNDEFINED = 0; public static final int ORIENTATION_NORMAL = 1; /** * Indicates the image is left right reversed mirror. */ public static final int ORIENTATION_FLIP_HORIZONTAL = 2; /** * Indicates the image is rotated by 180 degree clockwise. */ public static final int ORIENTATION_ROTATE_180 = 3; /** * Indicates the image is upside down mirror, it can also be represented by flip * horizontally firstly and rotate 180 degree clockwise. */ public static final int ORIENTATION_FLIP_VERTICAL = 4; /** * Indicates the image is flipped about top-left <--> bottom-right axis, it can also be * represented by flip horizontally firstly and rotate 270 degree clockwise. */ public static final int ORIENTATION_TRANSPOSE = 5; /** * Indicates the image is rotated by 90 degree clockwise. */ public static final int ORIENTATION_ROTATE_90 = 6; /** * Indicates the image is flipped about top-right <--> bottom-left axis, it can also be * represented by flip horizontally firstly and rotate 90 degree clockwise. */ public static final int ORIENTATION_TRANSVERSE = 7; /** * Indicates the image is rotated by 270 degree clockwise. */ public static final int ORIENTATION_ROTATE_270 = 8; private static final List<Integer> ROTATION_ORDER = Arrays.asList(ORIENTATION_NORMAL, ORIENTATION_ROTATE_90, ORIENTATION_ROTATE_180, ORIENTATION_ROTATE_270); private static final List<Integer> FLIPPED_ROTATION_ORDER = Arrays.asList( ORIENTATION_FLIP_HORIZONTAL, ORIENTATION_TRANSVERSE, ORIENTATION_FLIP_VERTICAL, ORIENTATION_TRANSPOSE); /** * The contant used by {@link #TAG_PLANAR_CONFIGURATION} to denote Chunky format. */ public static final short FORMAT_CHUNKY = 1; /** * The contant used by {@link #TAG_PLANAR_CONFIGURATION} to denote Planar format. */ public static final short FORMAT_PLANAR = 2; /** * The contant used by {@link #TAG_Y_CB_CR_POSITIONING} to denote Centered positioning. */ public static final short Y_CB_CR_POSITIONING_CENTERED = 1; /** * The contant used by {@link #TAG_Y_CB_CR_POSITIONING} to denote Co-sited positioning. */ public static final short Y_CB_CR_POSITIONING_CO_SITED = 2; /** * The contant used to denote resolution unit as inches. */ public static final short RESOLUTION_UNIT_INCHES = 2; /** * The contant used to denote resolution unit as centimeters. */ public static final short RESOLUTION_UNIT_CENTIMETERS = 3; /** * The contant used by {@link #TAG_COLOR_SPACE} to denote sRGB color space. */ public static final int COLOR_SPACE_S_RGB = 1; /** * The contant used by {@link #TAG_COLOR_SPACE} to denote Uncalibrated. */ public static final int COLOR_SPACE_UNCALIBRATED = 65535; /** * The contant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is not defined. */ public static final short EXPOSURE_PROGRAM_NOT_DEFINED = 0; /** * The contant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is Manual. */ public static final short EXPOSURE_PROGRAM_MANUAL = 1; /** * The contant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is Normal. */ public static final short EXPOSURE_PROGRAM_NORMAL = 2; /** * The contant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is * Aperture priority. */ public static final short EXPOSURE_PROGRAM_APERTURE_PRIORITY = 3; /** * The contant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is * Shutter priority. */ public static final short EXPOSURE_PROGRAM_SHUTTER_PRIORITY = 4; /** * The contant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is Creative * program (biased toward depth of field). */ public static final short EXPOSURE_PROGRAM_CREATIVE = 5; /** * The contant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is Action * program (biased toward fast shutter speed). */ public static final short EXPOSURE_PROGRAM_ACTION = 6; /** * The contant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is Portrait mode * (for closeup photos with the background out of focus). */ public static final short EXPOSURE_PROGRAM_PORTRAIT_MODE = 7; /** * The contant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is Landscape * mode (for landscape photos with the background in focus). */ public static final short EXPOSURE_PROGRAM_LANDSCAPE_MODE = 8; /** * The contant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is unknown. */ public static final short SENSITIVITY_TYPE_UNKNOWN = 0; /** * The contant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is Standard * output sensitivity (SOS). */ public static final short SENSITIVITY_TYPE_SOS = 1; /** * The contant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is Recommended * exposure index (REI). */ public static final short SENSITIVITY_TYPE_REI = 2; /** * The contant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is ISO speed. */ public static final short SENSITIVITY_TYPE_ISO_SPEED = 3; /** * The contant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is Standard * output sensitivity (SOS) and recommended exposure index (REI). */ public static final short SENSITIVITY_TYPE_SOS_AND_REI = 4; /** * The contant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is Standard * output sensitivity (SOS) and ISO speed. */ public static final short SENSITIVITY_TYPE_SOS_AND_ISO = 5; /** * The contant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is Recommended * exposure index (REI) and ISO speed. */ public static final short SENSITIVITY_TYPE_REI_AND_ISO = 6; /** * The contant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is Standard * output sensitivity (SOS) and recommended exposure index (REI) and ISO speed. */ public static final short SENSITIVITY_TYPE_SOS_AND_REI_AND_ISO = 7; /** * The contant used by {@link #TAG_METERING_MODE} to denote metering mode is unknown. */ public static final short METERING_MODE_UNKNOWN = 0; /** * The contant used by {@link #TAG_METERING_MODE} to denote metering mode is Average. */ public static final short METERING_MODE_AVERAGE = 1; /** * The contant used by {@link #TAG_METERING_MODE} to denote metering mode is * CenterWeightedAverage. */ public static final short METERING_MODE_CENTER_WEIGHT_AVERAGE = 2; /** * The contant used by {@link #TAG_METERING_MODE} to denote metering mode is Spot. */ public static final short METERING_MODE_SPOT = 3; /** * The contant used by {@link #TAG_METERING_MODE} to denote metering mode is MultiSpot. */ public static final short METERING_MODE_MULTI_SPOT = 4; /** * The contant used by {@link #TAG_METERING_MODE} to denote metering mode is Pattern. */ public static final short METERING_MODE_PATTERN = 5; /** * The contant used by {@link #TAG_METERING_MODE} to denote metering mode is Partial. */ public static final short METERING_MODE_PARTIAL = 6; /** * The contant used by {@link #TAG_METERING_MODE} to denote metering mode is other. */ public static final short METERING_MODE_OTHER = 255; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is unknown. */ public static final short LIGHT_SOURCE_UNKNOWN = 0; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Daylight. */ public static final short LIGHT_SOURCE_DAYLIGHT = 1; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Fluorescent. */ public static final short LIGHT_SOURCE_FLUORESCENT = 2; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Tungsten * (incandescent light). */ public static final short LIGHT_SOURCE_TUNGSTEN = 3; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Flash. */ public static final short LIGHT_SOURCE_FLASH = 4; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Fine weather. */ public static final short LIGHT_SOURCE_FINE_WEATHER = 9; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Cloudy weather. */ public static final short LIGHT_SOURCE_CLOUDY_WEATHER = 10; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Shade. */ public static final short LIGHT_SOURCE_SHADE = 11; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Daylight fluorescent * (D 5700 - 7100K). */ public static final short LIGHT_SOURCE_DAYLIGHT_FLUORESCENT = 12; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Day white fluorescent * (N 4600 - 5500K). */ public static final short LIGHT_SOURCE_DAY_WHITE_FLUORESCENT = 13; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Cool white * fluorescent (W 3800 - 4500K). */ public static final short LIGHT_SOURCE_COOL_WHITE_FLUORESCENT = 14; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is White fluorescent * (WW 3250 - 3800K). */ public static final short LIGHT_SOURCE_WHITE_FLUORESCENT = 15; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Warm white * fluorescent (L 2600 - 3250K). */ public static final short LIGHT_SOURCE_WARM_WHITE_FLUORESCENT = 16; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Standard light A. */ public static final short LIGHT_SOURCE_STANDARD_LIGHT_A = 17; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Standard light B. */ public static final short LIGHT_SOURCE_STANDARD_LIGHT_B = 18; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Standard light C. */ public static final short LIGHT_SOURCE_STANDARD_LIGHT_C = 19; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is D55. */ public static final short LIGHT_SOURCE_D55 = 20; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is D65. */ public static final short LIGHT_SOURCE_D65 = 21; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is D75. */ public static final short LIGHT_SOURCE_D75 = 22; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is D50. */ public static final short LIGHT_SOURCE_D50 = 23; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is ISO studio tungsten. */ public static final short LIGHT_SOURCE_ISO_STUDIO_TUNGSTEN = 24; /** * The contant used by {@link #TAG_LIGHT_SOURCE} to denote light source is other. */ public static final short LIGHT_SOURCE_OTHER = 255; /** * The flag used by {@link #TAG_FLASH} to indicate whether the flash is fired. */ public static final short FLAG_FLASH_FIRED = 0b0000_0001; /** * The flag used by {@link #TAG_FLASH} to indicate strobe return light is not detected. */ public static final short FLAG_FLASH_RETURN_LIGHT_NOT_DETECTED = 0b0000_0100; /** * The flag used by {@link #TAG_FLASH} to indicate strobe return light is detected. */ public static final short FLAG_FLASH_RETURN_LIGHT_DETECTED = 0b0000_0110; /** * The flag used by {@link #TAG_FLASH} to indicate the camera's flash mode is Compulsory flash * firing. * * @see #FLAG_FLASH_MODE_COMPULSORY_SUPPRESSION * @see #FLAG_FLASH_MODE_AUTO */ public static final short FLAG_FLASH_MODE_COMPULSORY_FIRING = 0b0000_1000; /** * The flag used by {@link #TAG_FLASH} to indicate the camera's flash mode is Compulsory flash * suppression. * * @see #FLAG_FLASH_MODE_COMPULSORY_FIRING * @see #FLAG_FLASH_MODE_AUTO */ public static final short FLAG_FLASH_MODE_COMPULSORY_SUPPRESSION = 0b0001_0000; /** * The flag used by {@link #TAG_FLASH} to indicate the camera's flash mode is Auto. * * @see #FLAG_FLASH_MODE_COMPULSORY_FIRING * @see #FLAG_FLASH_MODE_COMPULSORY_SUPPRESSION */ public static final short FLAG_FLASH_MODE_AUTO = 0b0001_1000; /** * The flag used by {@link #TAG_FLASH} to indicate no flash function is present. */ public static final short FLAG_FLASH_NO_FLASH_FUNCTION = 0b0010_0000; /** * The flag used by {@link #TAG_FLASH} to indicate red-eye reduction is supported. */ public static final short FLAG_FLASH_RED_EYE_SUPPORTED = 0b0100_0000; /** * The contant used by {@link #TAG_SENSING_METHOD} to denote the image sensor type is not * defined. */ public static final short SENSOR_TYPE_NOT_DEFINED = 1; /** * The contant used by {@link #TAG_SENSING_METHOD} to denote the image sensor type is One-chip * color area sensor. */ public static final short SENSOR_TYPE_ONE_CHIP = 2; /** * The contant used by {@link #TAG_SENSING_METHOD} to denote the image sensor type is Two-chip * color area sensor. */ public static final short SENSOR_TYPE_TWO_CHIP = 3; /** * The contant used by {@link #TAG_SENSING_METHOD} to denote the image sensor type is Three-chip * color area sensor. */ public static final short SENSOR_TYPE_THREE_CHIP = 4; /** * The contant used by {@link #TAG_SENSING_METHOD} to denote the image sensor type is Color * sequential area sensor. */ public static final short SENSOR_TYPE_COLOR_SEQUENTIAL = 5; /** * The contant used by {@link #TAG_SENSING_METHOD} to denote the image sensor type is Trilinear * sensor. */ public static final short SENSOR_TYPE_TRILINEAR = 7; /** * The contant used by {@link #TAG_SENSING_METHOD} to denote the image sensor type is Color * sequential linear sensor. */ public static final short SENSOR_TYPE_COLOR_SEQUENTIAL_LINEAR = 8; /** * The contant used by {@link #TAG_FILE_SOURCE} to denote the source is other. */ public static final short FILE_SOURCE_OTHER = 0; /** * The contant used by {@link #TAG_FILE_SOURCE} to denote the source is scanner of transparent * type. */ public static final short FILE_SOURCE_TRANSPARENT_SCANNER = 1; /** * The contant used by {@link #TAG_FILE_SOURCE} to denote the source is scanner of reflex type. */ public static final short FILE_SOURCE_REFLEX_SCANNER = 2; /** * The contant used by {@link #TAG_FILE_SOURCE} to denote the source is DSC. */ public static final short FILE_SOURCE_DSC = 3; /** * The contant used by {@link #TAG_SCENE_TYPE} to denote the scene is directly photographed. */ public static final short SCENE_TYPE_DIRECTLY_PHOTOGRAPHED = 1; /** * The contant used by {@link #TAG_CUSTOM_RENDERED} to denote no special processing is used. */ public static final short RENDERED_PROCESS_NORMAL = 0; /** * The contant used by {@link #TAG_CUSTOM_RENDERED} to denote special processing is used. */ public static final short RENDERED_PROCESS_CUSTOM = 1; /** * The contant used by {@link #TAG_EXPOSURE_MODE} to denote the exposure mode is Auto. */ public static final short EXPOSURE_MODE_AUTO = 0; /** * The contant used by {@link #TAG_EXPOSURE_MODE} to denote the exposure mode is Manual. */ public static final short EXPOSURE_MODE_MANUAL = 1; /** * The contant used by {@link #TAG_EXPOSURE_MODE} to denote the exposure mode is Auto bracket. */ public static final short EXPOSURE_MODE_AUTO_BRACKET = 2; /** * The contant used by {@link #TAG_WHITE_BALANCE} to denote the white balance is Auto. * * @deprecated Use {@link #WHITE_BALANCE_AUTO} instead. */ @Deprecated public static final int WHITEBALANCE_AUTO = 0; /** * The contant used by {@link #TAG_WHITE_BALANCE} to denote the white balance is Manual. * * @deprecated Use {@link #WHITE_BALANCE_MANUAL} instead. */ @Deprecated public static final int WHITEBALANCE_MANUAL = 1; /** * The contant used by {@link #TAG_WHITE_BALANCE} to denote the white balance is Auto. */ public static final short WHITE_BALANCE_AUTO = 0; /** * The contant used by {@link #TAG_WHITE_BALANCE} to denote the white balance is Manual. */ public static final short WHITE_BALANCE_MANUAL = 1; /** * The contant used by {@link #TAG_SCENE_CAPTURE_TYPE} to denote the scene capture type is * Standard. */ public static final short SCENE_CAPTURE_TYPE_STANDARD = 0; /** * The contant used by {@link #TAG_SCENE_CAPTURE_TYPE} to denote the scene capture type is * Landscape. */ public static final short SCENE_CAPTURE_TYPE_LANDSCAPE = 1; /** * The contant used by {@link #TAG_SCENE_CAPTURE_TYPE} to denote the scene capture type is * Portrait. */ public static final short SCENE_CAPTURE_TYPE_PORTRAIT = 2; /** * The contant used by {@link #TAG_SCENE_CAPTURE_TYPE} to denote the scene capture type is Night * scene. */ public static final short SCENE_CAPTURE_TYPE_NIGHT = 3; /** * The contant used by {@link #TAG_GAIN_CONTROL} to denote none gain adjustment. */ public static final short GAIN_CONTROL_NONE = 0; /** * The contant used by {@link #TAG_GAIN_CONTROL} to denote low gain up. */ public static final short GAIN_CONTROL_LOW_GAIN_UP = 1; /** * The contant used by {@link #TAG_GAIN_CONTROL} to denote high gain up. */ public static final short GAIN_CONTROL_HIGH_GAIN_UP = 2; /** * The contant used by {@link #TAG_GAIN_CONTROL} to denote low gain down. */ public static final short GAIN_CONTROL_LOW_GAIN_DOWN = 3; /** * The contant used by {@link #TAG_GAIN_CONTROL} to denote high gain down. */ public static final short GAIN_CONTROL_HIGH_GAIN_DOWN = 4; /** * The contant used by {@link #TAG_CONTRAST} to denote normal contrast. */ public static final short CONTRAST_NORMAL = 0; /** * The contant used by {@link #TAG_CONTRAST} to denote soft contrast. */ public static final short CONTRAST_SOFT = 1; /** * The contant used by {@link #TAG_CONTRAST} to denote hard contrast. */ public static final short CONTRAST_HARD = 2; /** * The contant used by {@link #TAG_SATURATION} to denote normal saturation. */ public static final short SATURATION_NORMAL = 0; /** * The contant used by {@link #TAG_SATURATION} to denote low saturation. */ public static final short SATURATION_LOW = 0; /** * The contant used by {@link #TAG_SHARPNESS} to denote high saturation. */ public static final short SATURATION_HIGH = 0; /** * The contant used by {@link #TAG_SHARPNESS} to denote normal sharpness. */ public static final short SHARPNESS_NORMAL = 0; /** * The contant used by {@link #TAG_SHARPNESS} to denote soft sharpness. */ public static final short SHARPNESS_SOFT = 1; /** * The contant used by {@link #TAG_SHARPNESS} to denote hard sharpness. */ public static final short SHARPNESS_HARD = 2; /** * The contant used by {@link #TAG_SUBJECT_DISTANCE_RANGE} to denote the subject distance range * is unknown. */ public static final short SUBJECT_DISTANCE_RANGE_UNKNOWN = 0; /** * The contant used by {@link #TAG_SUBJECT_DISTANCE_RANGE} to denote the subject distance range * is Macro. */ public static final short SUBJECT_DISTANCE_RANGE_MACRO = 1; /** * The contant used by {@link #TAG_SUBJECT_DISTANCE_RANGE} to denote the subject distance range * is Close view. */ public static final short SUBJECT_DISTANCE_RANGE_CLOSE_VIEW = 2; /** * The contant used by {@link #TAG_SUBJECT_DISTANCE_RANGE} to denote the subject distance range * is Distant view. */ public static final short SUBJECT_DISTANCE_RANGE_DISTANT_VIEW = 3; /** * The contant used by GPS latitude-related tags to denote the latitude is North latitude. * * @see #TAG_GPS_LATITUDE_REF * @see #TAG_GPS_DEST_LATITUDE_REF */ public static final String LATITUDE_NORTH = "N"; /** * The contant used by GPS latitude-related tags to denote the latitude is South latitude. * * @see #TAG_GPS_LATITUDE_REF * @see #TAG_GPS_DEST_LATITUDE_REF */ public static final String LATITUDE_SOUTH = "S"; /** * The contant used by GPS longitude-related tags to denote the longitude is East longitude. * * @see #TAG_GPS_LONGITUDE_REF * @see #TAG_GPS_DEST_LONGITUDE_REF */ public static final String LONGITUDE_EAST = "E"; /** * The contant used by GPS longitude-related tags to denote the longitude is West longitude. * * @see #TAG_GPS_LONGITUDE_REF * @see #TAG_GPS_DEST_LONGITUDE_REF */ public static final String LONGITUDE_WEST = "W"; /** * The contant used by {@link #TAG_GPS_ALTITUDE_REF} to denote the altitude is above sea level. */ public static final short ALTITUDE_ABOVE_SEA_LEVEL = 0; /** * The contant used by {@link #TAG_GPS_ALTITUDE_REF} to denote the altitude is below sea level. */ public static final short ALTITUDE_BELOW_SEA_LEVEL = 1; /** * The contant used by {@link #TAG_GPS_STATUS} to denote GPS measurement is in progress. */ public static final String GPS_MEASUREMENT_IN_PROGRESS = "A"; /** * The contant used by {@link #TAG_GPS_STATUS} to denote GPS measurement is interrupted. */ public static final String GPS_MEASUREMENT_INTERRUPTED = "V"; /** * The contant used by {@link #TAG_GPS_MEASURE_MODE} to denote GPS measurement is 2-dimensional. */ public static final String GPS_MEASUREMENT_2D = "2"; /** * The contant used by {@link #TAG_GPS_MEASURE_MODE} to denote GPS measurement is 3-dimensional. */ public static final String GPS_MEASUREMENT_3D = "3"; /** * The contant used by {@link #TAG_GPS_SPEED_REF} to denote the speed unit is kilometers per * hour. */ public static final String GPS_SPEED_KILOMETERS_PER_HOUR = "K"; /** * The contant used by {@link #TAG_GPS_SPEED_REF} to denote the speed unit is miles per hour. */ public static final String GPS_SPEED_MILES_PER_HOUR = "M"; /** * The contant used by {@link #TAG_GPS_SPEED_REF} to denote the speed unit is knots. */ public static final String GPS_SPEED_KNOTS = "N"; /** * The contant used by GPS attributes to denote the direction is true direction. */ public static final String GPS_DIRECTION_TRUE = "T"; /** * The contant used by GPS attributes to denote the direction is magnetic direction. */ public static final String GPS_DIRECTION_MAGNETIC = "M"; /** * The contant used by {@link #TAG_GPS_DEST_DISTANCE_REF} to denote the distance unit is * kilometers. */ public static final String GPS_DISTANCE_KILOMETERS = "K"; /** * The contant used by {@link #TAG_GPS_DEST_DISTANCE_REF} to denote the distance unit is miles. */ public static final String GPS_DISTANCE_MILES = "M"; /** * The contant used by {@link #TAG_GPS_DEST_DISTANCE_REF} to denote the distance unit is * nautical miles. */ public static final String GPS_DISTANCE_NAUTICAL_MILES = "N"; /** * The contant used by {@link #TAG_GPS_DIFFERENTIAL} to denote no differential correction is * applied. */ public static final short GPS_MEASUREMENT_NO_DIFFERENTIAL = 0; /** * The contant used by {@link #TAG_GPS_DIFFERENTIAL} to denote differential correction is * applied. */ public static final short GPS_MEASUREMENT_DIFFERENTIAL_CORRECTED = 1; /** * The constant used by {@link #TAG_COMPRESSION} to denote the image is not compressed. */ public static final int DATA_UNCOMPRESSED = 1; /** * The constant used by {@link #TAG_COMPRESSION} to denote the image is huffman compressed. */ public static final int DATA_HUFFMAN_COMPRESSED = 2; /** * The constant used by {@link #TAG_COMPRESSION} to denote the image is JPEG. */ public static final int DATA_JPEG = 6; /** * The constant used by {@link #TAG_COMPRESSION}, see DNG Specification 1.4.0.0. * Section 3, Compression */ public static final int DATA_JPEG_COMPRESSED = 7; /** * The constant used by {@link #TAG_COMPRESSION}, see DNG Specification 1.4.0.0. * Section 3, Compression */ public static final int DATA_DEFLATE_ZIP = 8; /** * The constant used by {@link #TAG_COMPRESSION} to denote the image is pack-bits compressed. */ public static final int DATA_PACK_BITS_COMPRESSED = 32773; /** * The constant used by {@link #TAG_COMPRESSION}, see DNG Specification 1.4.0.0. * Section 3, Compression */ public static final int DATA_LOSSY_JPEG = 34892; /** * The constant used by {@link #TAG_BITS_PER_SAMPLE}. * See JEITA CP-3451C Spec Section 6, Differences from Palette Color Images */ public static final int[] BITS_PER_SAMPLE_RGB = new int[] { 8, 8, 8 }; /** * The constant used by {@link #TAG_BITS_PER_SAMPLE}. * See JEITA CP-3451C Spec Section 4, Differences from Bilevel Images */ public static final int[] BITS_PER_SAMPLE_GREYSCALE_1 = new int[] { 4 }; /** * The constant used by {@link #TAG_BITS_PER_SAMPLE}. * See JEITA CP-3451C Spec Section 4, Differences from Bilevel Images */ public static final int[] BITS_PER_SAMPLE_GREYSCALE_2 = new int[] { 8 }; /** * The constant used by {@link #TAG_PHOTOMETRIC_INTERPRETATION}. */ public static final int PHOTOMETRIC_INTERPRETATION_WHITE_IS_ZERO = 0; /** * The constant used by {@link #TAG_PHOTOMETRIC_INTERPRETATION}. */ public static final int PHOTOMETRIC_INTERPRETATION_BLACK_IS_ZERO = 1; /** * The constant used by {@link #TAG_PHOTOMETRIC_INTERPRETATION}. */ public static final int PHOTOMETRIC_INTERPRETATION_RGB = 2; /** * The constant used by {@link #TAG_PHOTOMETRIC_INTERPRETATION}. */ public static final int PHOTOMETRIC_INTERPRETATION_YCBCR = 6; /** * The constant used by {@link #TAG_NEW_SUBFILE_TYPE}. See JEITA CP-3451C Spec Section 8. */ public static final int ORIGINAL_RESOLUTION_IMAGE = 0; /** * The constant used by {@link #TAG_NEW_SUBFILE_TYPE}. See JEITA CP-3451C Spec Section 8. */ public static final int REDUCED_RESOLUTION_IMAGE = 1; // Maximum size for checking file type signature (see image_type_recognition_lite.cc) private static final int SIGNATURE_CHECK_SIZE = 5000; static final byte[] JPEG_SIGNATURE = new byte[] {(byte) 0xff, (byte) 0xd8, (byte) 0xff}; private static final String RAF_SIGNATURE = "FUJIFILMCCD-RAW"; private static final int RAF_OFFSET_TO_JPEG_IMAGE_OFFSET = 84; private static final int RAF_INFO_SIZE = 160; private static final int RAF_JPEG_LENGTH_VALUE_SIZE = 4; // See http://fileformats.archiveteam.org/wiki/Olympus_ORF private static final short ORF_SIGNATURE_1 = 0x4f52; private static final short ORF_SIGNATURE_2 = 0x5352; // There are two formats for Olympus Makernote Headers. Each has different identifiers and // offsets to the actual data. // See http://www.exiv2.org/makernote.html#R1 private static final byte[] ORF_MAKER_NOTE_HEADER_1 = new byte[] {(byte) 0x4f, (byte) 0x4c, (byte) 0x59, (byte) 0x4d, (byte) 0x50, (byte) 0x00}; // "OLYMP\0" private static final byte[] ORF_MAKER_NOTE_HEADER_2 = new byte[] {(byte) 0x4f, (byte) 0x4c, (byte) 0x59, (byte) 0x4d, (byte) 0x50, (byte) 0x55, (byte) 0x53, (byte) 0x00, (byte) 0x49, (byte) 0x49}; // "OLYMPUS\0II" private static final int ORF_MAKER_NOTE_HEADER_1_SIZE = 8; private static final int ORF_MAKER_NOTE_HEADER_2_SIZE = 12; // See http://fileformats.archiveteam.org/wiki/RW2 private static final short RW2_SIGNATURE = 0x0055; // See http://fileformats.archiveteam.org/wiki/Pentax_PEF private static final String PEF_SIGNATURE = "PENTAX"; // See http://www.exiv2.org/makernote.html#R11 private static final int PEF_MAKER_NOTE_SKIP_SIZE = 6; private static SimpleDateFormat sFormatter; // See Exchangeable image file format for digital still cameras: Exif version 2.2. // The following values are for parsing EXIF data area. There are tag groups in EXIF data area. // They are called "Image File Directory". They have multiple data formats to cover various // image metadata from GPS longitude to camera model name. // Types of Exif byte alignments (see JEITA CP-3451C Section 4.5.2) static final short BYTE_ALIGN_II = 0x4949; // II: Intel order static final short BYTE_ALIGN_MM = 0x4d4d; // MM: Motorola order // TIFF Header Fixed Constant (see JEITA CP-3451C Section 4.5.2) static final byte START_CODE = 0x2a; // 42 private static final int IFD_OFFSET = 8; // Formats for the value in IFD entry (See TIFF 6.0 Section 2, "Image File Directory".) private static final int IFD_FORMAT_BYTE = 1; private static final int IFD_FORMAT_STRING = 2; private static final int IFD_FORMAT_USHORT = 3; private static final int IFD_FORMAT_ULONG = 4; private static final int IFD_FORMAT_URATIONAL = 5; private static final int IFD_FORMAT_SBYTE = 6; private static final int IFD_FORMAT_UNDEFINED = 7; private static final int IFD_FORMAT_SSHORT = 8; private static final int IFD_FORMAT_SLONG = 9; private static final int IFD_FORMAT_SRATIONAL = 10; private static final int IFD_FORMAT_SINGLE = 11; private static final int IFD_FORMAT_DOUBLE = 12; // Format indicating a new IFD entry (See Adobe PageMaker® 6.0 TIFF Technical Notes, "New Tag") private static final int IFD_FORMAT_IFD = 13; // Names for the data formats for debugging purpose. static final String[] IFD_FORMAT_NAMES = new String[] { "", "BYTE", "STRING", "USHORT", "ULONG", "URATIONAL", "SBYTE", "UNDEFINED", "SSHORT", "SLONG", "SRATIONAL", "SINGLE", "DOUBLE" }; // Sizes of the components of each IFD value format static final int[] IFD_FORMAT_BYTES_PER_FORMAT = new int[] { 0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 1 }; private static final byte[] EXIF_ASCII_PREFIX = new byte[] { 0x41, 0x53, 0x43, 0x49, 0x49, 0x0, 0x0, 0x0 }; // A class for indicating EXIF rational type. private static class Rational { public final long numerator; public final long denominator; private Rational(double value) { this((long) (value * 10000), 10000); } private Rational(long numerator, long denominator) { // Handle erroneous case if (denominator == 0) { this.numerator = 0; this.denominator = 1; return; } this.numerator = numerator; this.denominator = denominator; } @Override public String toString() { return numerator + "/" + denominator; } public double calculate() { return (double) numerator / denominator; } } // A class for indicating EXIF attribute. private static class ExifAttribute { public final int format; public final int numberOfComponents; public final byte[] bytes; private ExifAttribute(int format, int numberOfComponents, byte[] bytes) { this.format = format; this.numberOfComponents = numberOfComponents; this.bytes = bytes; } public static ExifAttribute createUShort(int[] values, ByteOrder byteOrder) { final ByteBuffer buffer = ByteBuffer.wrap( new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_USHORT] * values.length]); buffer.order(byteOrder); for (int value : values) { buffer.putShort((short) value); } return new ExifAttribute(IFD_FORMAT_USHORT, values.length, buffer.array()); } public static ExifAttribute createUShort(int value, ByteOrder byteOrder) { return createUShort(new int[] {value}, byteOrder); } public static ExifAttribute createULong(long[] values, ByteOrder byteOrder) { final ByteBuffer buffer = ByteBuffer.wrap( new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_ULONG] * values.length]); buffer.order(byteOrder); for (long value : values) { buffer.putInt((int) value); } return new ExifAttribute(IFD_FORMAT_ULONG, values.length, buffer.array()); } public static ExifAttribute createULong(long value, ByteOrder byteOrder) { return createULong(new long[] {value}, byteOrder); } public static ExifAttribute createSLong(int[] values, ByteOrder byteOrder) { final ByteBuffer buffer = ByteBuffer.wrap( new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_SLONG] * values.length]); buffer.order(byteOrder); for (int value : values) { buffer.putInt(value); } return new ExifAttribute(IFD_FORMAT_SLONG, values.length, buffer.array()); } public static ExifAttribute createSLong(int value, ByteOrder byteOrder) { return createSLong(new int[] {value}, byteOrder); } public static ExifAttribute createByte(String value) { // Exception for GPSAltitudeRef tag if (value.length() == 1 && value.charAt(0) >= '0' && value.charAt(0) <= '1') { final byte[] bytes = new byte[] { (byte) (value.charAt(0) - '0') }; return new ExifAttribute(IFD_FORMAT_BYTE, bytes.length, bytes); } final byte[] ascii = value.getBytes(ASCII); return new ExifAttribute(IFD_FORMAT_BYTE, ascii.length, ascii); } public static ExifAttribute createString(String value) { final byte[] ascii = (value + '\0').getBytes(ASCII); return new ExifAttribute(IFD_FORMAT_STRING, ascii.length, ascii); } public static ExifAttribute createURational(Rational[] values, ByteOrder byteOrder) { final ByteBuffer buffer = ByteBuffer.wrap( new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_URATIONAL] * values.length]); buffer.order(byteOrder); for (Rational value : values) { buffer.putInt((int) value.numerator); buffer.putInt((int) value.denominator); } return new ExifAttribute(IFD_FORMAT_URATIONAL, values.length, buffer.array()); } public static ExifAttribute createURational(Rational value, ByteOrder byteOrder) { return createURational(new Rational[] {value}, byteOrder); } public static ExifAttribute createSRational(Rational[] values, ByteOrder byteOrder) { final ByteBuffer buffer = ByteBuffer.wrap( new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_SRATIONAL] * values.length]); buffer.order(byteOrder); for (Rational value : values) { buffer.putInt((int) value.numerator); buffer.putInt((int) value.denominator); } return new ExifAttribute(IFD_FORMAT_SRATIONAL, values.length, buffer.array()); } public static ExifAttribute createSRational(Rational value, ByteOrder byteOrder) { return createSRational(new Rational[] {value}, byteOrder); } public static ExifAttribute createDouble(double[] values, ByteOrder byteOrder) { final ByteBuffer buffer = ByteBuffer.wrap( new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_DOUBLE] * values.length]); buffer.order(byteOrder); for (double value : values) { buffer.putDouble(value); } return new ExifAttribute(IFD_FORMAT_DOUBLE, values.length, buffer.array()); } public static ExifAttribute createDouble(double value, ByteOrder byteOrder) { return createDouble(new double[] {value}, byteOrder); } @Override public String toString() { return "(" + IFD_FORMAT_NAMES[format] + ", data length:" + bytes.length + ")"; } private Object getValue(ByteOrder byteOrder) { ByteOrderedDataInputStream inputStream = null; try { inputStream = new ByteOrderedDataInputStream(bytes); inputStream.setByteOrder(byteOrder); switch (format) { case IFD_FORMAT_BYTE: case IFD_FORMAT_SBYTE: { // Exception for GPSAltitudeRef tag if (bytes.length == 1 && bytes[0] >= 0 && bytes[0] <= 1) { return new String(new char[] { (char) (bytes[0] + '0') }); } return new String(bytes, ASCII); } case IFD_FORMAT_UNDEFINED: case IFD_FORMAT_STRING: { int index = 0; if (numberOfComponents >= EXIF_ASCII_PREFIX.length) { boolean same = true; for (int i = 0; i < EXIF_ASCII_PREFIX.length; ++i) { if (bytes[i] != EXIF_ASCII_PREFIX[i]) { same = false; break; } } if (same) { index = EXIF_ASCII_PREFIX.length; } } StringBuilder stringBuilder = new StringBuilder(); while (index < numberOfComponents) { int ch = bytes[index]; if (ch == 0) { break; } if (ch >= 32) { stringBuilder.append((char) ch); } else { stringBuilder.append('?'); } ++index; } return stringBuilder.toString(); } case IFD_FORMAT_USHORT: { final int[] values = new int[numberOfComponents]; for (int i = 0; i < numberOfComponents; ++i) { values[i] = inputStream.readUnsignedShort(); } return values; } case IFD_FORMAT_ULONG: { final long[] values = new long[numberOfComponents]; for (int i = 0; i < numberOfComponents; ++i) { values[i] = inputStream.readUnsignedInt(); } return values; } case IFD_FORMAT_URATIONAL: { final Rational[] values = new Rational[numberOfComponents]; for (int i = 0; i < numberOfComponents; ++i) { final long numerator = inputStream.readUnsignedInt(); final long denominator = inputStream.readUnsignedInt(); values[i] = new Rational(numerator, denominator); } return values; } case IFD_FORMAT_SSHORT: { final int[] values = new int[numberOfComponents]; for (int i = 0; i < numberOfComponents; ++i) { values[i] = inputStream.readShort(); } return values; } case IFD_FORMAT_SLONG: { final int[] values = new int[numberOfComponents]; for (int i = 0; i < numberOfComponents; ++i) { values[i] = inputStream.readInt(); } return values; } case IFD_FORMAT_SRATIONAL: { final Rational[] values = new Rational[numberOfComponents]; for (int i = 0; i < numberOfComponents; ++i) { final long numerator = inputStream.readInt(); final long denominator = inputStream.readInt(); values[i] = new Rational(numerator, denominator); } return values; } case IFD_FORMAT_SINGLE: { final double[] values = new double[numberOfComponents]; for (int i = 0; i < numberOfComponents; ++i) { values[i] = inputStream.readFloat(); } return values; } case IFD_FORMAT_DOUBLE: { final double[] values = new double[numberOfComponents]; for (int i = 0; i < numberOfComponents; ++i) { values[i] = inputStream.readDouble(); } return values; } default: return null; } } catch (IOException e) { Log.w(TAG, "IOException occurred during reading a value", e); return null; } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { Log.e(TAG, "IOException occurred while closing InputStream", e); } } } } public double getDoubleValue(ByteOrder byteOrder) { Object value = getValue(byteOrder); if (value == null) { throw new NumberFormatException("NULL can't be converted to a double value"); } if (value instanceof String) { return Double.parseDouble((String) value); } if (value instanceof long[]) { long[] array = (long[]) value; if (array.length == 1) { return array[0]; } throw new NumberFormatException("There are more than one component"); } if (value instanceof int[]) { int[] array = (int[]) value; if (array.length == 1) { return array[0]; } throw new NumberFormatException("There are more than one component"); } if (value instanceof double[]) { double[] array = (double[]) value; if (array.length == 1) { return array[0]; } throw new NumberFormatException("There are more than one component"); } if (value instanceof Rational[]) { Rational[] array = (Rational[]) value; if (array.length == 1) { return array[0].calculate(); } throw new NumberFormatException("There are more than one component"); } throw new NumberFormatException("Couldn't find a double value"); } public int getIntValue(ByteOrder byteOrder) { Object value = getValue(byteOrder); if (value == null) { throw new NumberFormatException("NULL can't be converted to a integer value"); } if (value instanceof String) { return Integer.parseInt((String) value); } if (value instanceof long[]) { long[] array = (long[]) value; if (array.length == 1) { return (int) array[0]; } throw new NumberFormatException("There are more than one component"); } if (value instanceof int[]) { int[] array = (int[]) value; if (array.length == 1) { return array[0]; } throw new NumberFormatException("There are more than one component"); } throw new NumberFormatException("Couldn't find a integer value"); } public String getStringValue(ByteOrder byteOrder) { Object value = getValue(byteOrder); if (value == null) { return null; } if (value instanceof String) { return (String) value; } final StringBuilder stringBuilder = new StringBuilder(); if (value instanceof long[]) { long[] array = (long[]) value; for (int i = 0; i < array.length; ++i) { stringBuilder.append(array[i]); if (i + 1 != array.length) { stringBuilder.append(","); } } return stringBuilder.toString(); } if (value instanceof int[]) { int[] array = (int[]) value; for (int i = 0; i < array.length; ++i) { stringBuilder.append(array[i]); if (i + 1 != array.length) { stringBuilder.append(","); } } return stringBuilder.toString(); } if (value instanceof double[]) { double[] array = (double[]) value; for (int i = 0; i < array.length; ++i) { stringBuilder.append(array[i]); if (i + 1 != array.length) { stringBuilder.append(","); } } return stringBuilder.toString(); } if (value instanceof Rational[]) { Rational[] array = (Rational[]) value; for (int i = 0; i < array.length; ++i) { stringBuilder.append(array[i].numerator); stringBuilder.append('/'); stringBuilder.append(array[i].denominator); if (i + 1 != array.length) { stringBuilder.append(","); } } return stringBuilder.toString(); } return null; } public int size() { return IFD_FORMAT_BYTES_PER_FORMAT[format] * numberOfComponents; } } // A class for indicating EXIF tag. static class ExifTag { public final int number; public final String name; public final int primaryFormat; public final int secondaryFormat; private ExifTag(String name, int number, int format) { this.name = name; this.number = number; this.primaryFormat = format; this.secondaryFormat = -1; } private ExifTag(String name, int number, int primaryFormat, int secondaryFormat) { this.name = name; this.number = number; this.primaryFormat = primaryFormat; this.secondaryFormat = secondaryFormat; } private boolean isFormatCompatible(int format) { if (primaryFormat == IFD_FORMAT_UNDEFINED || format == IFD_FORMAT_UNDEFINED) { return true; } else if (primaryFormat == format || secondaryFormat == format) { return true; } else if ((primaryFormat == IFD_FORMAT_ULONG || secondaryFormat == IFD_FORMAT_ULONG) && format == IFD_FORMAT_USHORT) { return true; } else if ((primaryFormat == IFD_FORMAT_SLONG || secondaryFormat == IFD_FORMAT_SLONG) && format == IFD_FORMAT_SSHORT) { return true; } else if ((primaryFormat == IFD_FORMAT_DOUBLE || secondaryFormat == IFD_FORMAT_DOUBLE) && format == IFD_FORMAT_SINGLE) { return true; } return false; } } // Primary image IFD TIFF tags (See JEITA CP-3451C Section 4.6.8 Tag Support Levels) private static final ExifTag[] IFD_TIFF_TAGS = new ExifTag[] { // For below two, see TIFF 6.0 Spec Section 3: Bilevel Images. new ExifTag(TAG_NEW_SUBFILE_TYPE, 254, IFD_FORMAT_ULONG), new ExifTag(TAG_SUBFILE_TYPE, 255, IFD_FORMAT_ULONG), new ExifTag(TAG_IMAGE_WIDTH, 256, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_IMAGE_LENGTH, 257, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_BITS_PER_SAMPLE, 258, IFD_FORMAT_USHORT), new ExifTag(TAG_COMPRESSION, 259, IFD_FORMAT_USHORT), new ExifTag(TAG_PHOTOMETRIC_INTERPRETATION, 262, IFD_FORMAT_USHORT), new ExifTag(TAG_IMAGE_DESCRIPTION, 270, IFD_FORMAT_STRING), new ExifTag(TAG_MAKE, 271, IFD_FORMAT_STRING), new ExifTag(TAG_MODEL, 272, IFD_FORMAT_STRING), new ExifTag(TAG_STRIP_OFFSETS, 273, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_ORIENTATION, 274, IFD_FORMAT_USHORT), new ExifTag(TAG_SAMPLES_PER_PIXEL, 277, IFD_FORMAT_USHORT), new ExifTag(TAG_ROWS_PER_STRIP, 278, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_STRIP_BYTE_COUNTS, 279, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_X_RESOLUTION, 282, IFD_FORMAT_URATIONAL), new ExifTag(TAG_Y_RESOLUTION, 283, IFD_FORMAT_URATIONAL), new ExifTag(TAG_PLANAR_CONFIGURATION, 284, IFD_FORMAT_USHORT), new ExifTag(TAG_RESOLUTION_UNIT, 296, IFD_FORMAT_USHORT), new ExifTag(TAG_TRANSFER_FUNCTION, 301, IFD_FORMAT_USHORT), new ExifTag(TAG_SOFTWARE, 305, IFD_FORMAT_STRING), new ExifTag(TAG_DATETIME, 306, IFD_FORMAT_STRING), new ExifTag(TAG_ARTIST, 315, IFD_FORMAT_STRING), new ExifTag(TAG_WHITE_POINT, 318, IFD_FORMAT_URATIONAL), new ExifTag(TAG_PRIMARY_CHROMATICITIES, 319, IFD_FORMAT_URATIONAL), // See Adobe PageMaker® 6.0 TIFF Technical Notes, Note 1. new ExifTag(TAG_SUB_IFD_POINTER, 330, IFD_FORMAT_ULONG), new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT, 513, IFD_FORMAT_ULONG), new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 514, IFD_FORMAT_ULONG), new ExifTag(TAG_Y_CB_CR_COEFFICIENTS, 529, IFD_FORMAT_URATIONAL), new ExifTag(TAG_Y_CB_CR_SUB_SAMPLING, 530, IFD_FORMAT_USHORT), new ExifTag(TAG_Y_CB_CR_POSITIONING, 531, IFD_FORMAT_USHORT), new ExifTag(TAG_REFERENCE_BLACK_WHITE, 532, IFD_FORMAT_URATIONAL), new ExifTag(TAG_COPYRIGHT, 33432, IFD_FORMAT_STRING), new ExifTag(TAG_EXIF_IFD_POINTER, 34665, IFD_FORMAT_ULONG), new ExifTag(TAG_GPS_INFO_IFD_POINTER, 34853, IFD_FORMAT_ULONG), // RW2 file tags // See http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html) new ExifTag(TAG_RW2_SENSOR_TOP_BORDER, 4, IFD_FORMAT_ULONG), new ExifTag(TAG_RW2_SENSOR_LEFT_BORDER, 5, IFD_FORMAT_ULONG), new ExifTag(TAG_RW2_SENSOR_BOTTOM_BORDER, 6, IFD_FORMAT_ULONG), new ExifTag(TAG_RW2_SENSOR_RIGHT_BORDER, 7, IFD_FORMAT_ULONG), new ExifTag(TAG_RW2_ISO, 23, IFD_FORMAT_USHORT), new ExifTag(TAG_RW2_JPG_FROM_RAW, 46, IFD_FORMAT_UNDEFINED) }; // Primary image IFD Exif Private tags (See JEITA CP-3451C Section 4.6.8 Tag Support Levels) private static final ExifTag[] IFD_EXIF_TAGS = new ExifTag[] { new ExifTag(TAG_EXPOSURE_TIME, 33434, IFD_FORMAT_URATIONAL), new ExifTag(TAG_F_NUMBER, 33437, IFD_FORMAT_URATIONAL), new ExifTag(TAG_EXPOSURE_PROGRAM, 34850, IFD_FORMAT_USHORT), new ExifTag(TAG_SPECTRAL_SENSITIVITY, 34852, IFD_FORMAT_STRING), new ExifTag(TAG_PHOTOGRAPHIC_SENSITIVITY, 34855, IFD_FORMAT_USHORT), new ExifTag(TAG_OECF, 34856, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_EXIF_VERSION, 36864, IFD_FORMAT_STRING), new ExifTag(TAG_DATETIME_ORIGINAL, 36867, IFD_FORMAT_STRING), new ExifTag(TAG_DATETIME_DIGITIZED, 36868, IFD_FORMAT_STRING), new ExifTag(TAG_COMPONENTS_CONFIGURATION, 37121, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_COMPRESSED_BITS_PER_PIXEL, 37122, IFD_FORMAT_URATIONAL), new ExifTag(TAG_SHUTTER_SPEED_VALUE, 37377, IFD_FORMAT_SRATIONAL), new ExifTag(TAG_APERTURE_VALUE, 37378, IFD_FORMAT_URATIONAL), new ExifTag(TAG_BRIGHTNESS_VALUE, 37379, IFD_FORMAT_SRATIONAL), new ExifTag(TAG_EXPOSURE_BIAS_VALUE, 37380, IFD_FORMAT_SRATIONAL), new ExifTag(TAG_MAX_APERTURE_VALUE, 37381, IFD_FORMAT_URATIONAL), new ExifTag(TAG_SUBJECT_DISTANCE, 37382, IFD_FORMAT_URATIONAL), new ExifTag(TAG_METERING_MODE, 37383, IFD_FORMAT_USHORT), new ExifTag(TAG_LIGHT_SOURCE, 37384, IFD_FORMAT_USHORT), new ExifTag(TAG_FLASH, 37385, IFD_FORMAT_USHORT), new ExifTag(TAG_FOCAL_LENGTH, 37386, IFD_FORMAT_URATIONAL), new ExifTag(TAG_SUBJECT_AREA, 37396, IFD_FORMAT_USHORT), new ExifTag(TAG_MAKER_NOTE, 37500, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_USER_COMMENT, 37510, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_SUBSEC_TIME, 37520, IFD_FORMAT_STRING), new ExifTag(TAG_SUBSEC_TIME_ORIGINAL, 37521, IFD_FORMAT_STRING), new ExifTag(TAG_SUBSEC_TIME_DIGITIZED, 37522, IFD_FORMAT_STRING), new ExifTag(TAG_FLASHPIX_VERSION, 40960, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_COLOR_SPACE, 40961, IFD_FORMAT_USHORT), new ExifTag(TAG_PIXEL_X_DIMENSION, 40962, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_PIXEL_Y_DIMENSION, 40963, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_RELATED_SOUND_FILE, 40964, IFD_FORMAT_STRING), new ExifTag(TAG_INTEROPERABILITY_IFD_POINTER, 40965, IFD_FORMAT_ULONG), new ExifTag(TAG_FLASH_ENERGY, 41483, IFD_FORMAT_URATIONAL), new ExifTag(TAG_SPATIAL_FREQUENCY_RESPONSE, 41484, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_FOCAL_PLANE_X_RESOLUTION, 41486, IFD_FORMAT_URATIONAL), new ExifTag(TAG_FOCAL_PLANE_Y_RESOLUTION, 41487, IFD_FORMAT_URATIONAL), new ExifTag(TAG_FOCAL_PLANE_RESOLUTION_UNIT, 41488, IFD_FORMAT_USHORT), new ExifTag(TAG_SUBJECT_LOCATION, 41492, IFD_FORMAT_USHORT), new ExifTag(TAG_EXPOSURE_INDEX, 41493, IFD_FORMAT_URATIONAL), new ExifTag(TAG_SENSING_METHOD, 41495, IFD_FORMAT_USHORT), new ExifTag(TAG_FILE_SOURCE, 41728, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_SCENE_TYPE, 41729, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_CFA_PATTERN, 41730, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_CUSTOM_RENDERED, 41985, IFD_FORMAT_USHORT), new ExifTag(TAG_EXPOSURE_MODE, 41986, IFD_FORMAT_USHORT), new ExifTag(TAG_WHITE_BALANCE, 41987, IFD_FORMAT_USHORT), new ExifTag(TAG_DIGITAL_ZOOM_RATIO, 41988, IFD_FORMAT_URATIONAL), new ExifTag(TAG_FOCAL_LENGTH_IN_35MM_FILM, 41989, IFD_FORMAT_USHORT), new ExifTag(TAG_SCENE_CAPTURE_TYPE, 41990, IFD_FORMAT_USHORT), new ExifTag(TAG_GAIN_CONTROL, 41991, IFD_FORMAT_USHORT), new ExifTag(TAG_CONTRAST, 41992, IFD_FORMAT_USHORT), new ExifTag(TAG_SATURATION, 41993, IFD_FORMAT_USHORT), new ExifTag(TAG_SHARPNESS, 41994, IFD_FORMAT_USHORT), new ExifTag(TAG_DEVICE_SETTING_DESCRIPTION, 41995, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_SUBJECT_DISTANCE_RANGE, 41996, IFD_FORMAT_USHORT), new ExifTag(TAG_IMAGE_UNIQUE_ID, 42016, IFD_FORMAT_STRING), new ExifTag(TAG_DNG_VERSION, 50706, IFD_FORMAT_BYTE), new ExifTag(TAG_DEFAULT_CROP_SIZE, 50720, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG) }; // Primary image IFD GPS Info tags (See JEITA CP-3451C Section 4.6.8 Tag Support Levels) private static final ExifTag[] IFD_GPS_TAGS = new ExifTag[] { new ExifTag(TAG_GPS_VERSION_ID, 0, IFD_FORMAT_BYTE), new ExifTag(TAG_GPS_LATITUDE_REF, 1, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_LATITUDE, 2, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_LONGITUDE_REF, 3, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_LONGITUDE, 4, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_ALTITUDE_REF, 5, IFD_FORMAT_BYTE), new ExifTag(TAG_GPS_ALTITUDE, 6, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_TIMESTAMP, 7, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_SATELLITES, 8, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_STATUS, 9, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_MEASURE_MODE, 10, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_DOP, 11, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_SPEED_REF, 12, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_SPEED, 13, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_TRACK_REF, 14, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_TRACK, 15, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_IMG_DIRECTION_REF, 16, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_IMG_DIRECTION, 17, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_MAP_DATUM, 18, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_DEST_LATITUDE_REF, 19, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_DEST_LATITUDE, 20, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_DEST_LONGITUDE_REF, 21, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_DEST_LONGITUDE, 22, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_DEST_BEARING_REF, 23, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_DEST_BEARING, 24, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_DEST_DISTANCE_REF, 25, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_DEST_DISTANCE, 26, IFD_FORMAT_URATIONAL), new ExifTag(TAG_GPS_PROCESSING_METHOD, 27, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_GPS_AREA_INFORMATION, 28, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_GPS_DATESTAMP, 29, IFD_FORMAT_STRING), new ExifTag(TAG_GPS_DIFFERENTIAL, 30, IFD_FORMAT_USHORT) }; // Primary image IFD Interoperability tag (See JEITA CP-3451C Section 4.6.8 Tag Support Levels) private static final ExifTag[] IFD_INTEROPERABILITY_TAGS = new ExifTag[] { new ExifTag(TAG_INTEROPERABILITY_INDEX, 1, IFD_FORMAT_STRING) }; // IFD Thumbnail tags (See JEITA CP-3451C Section 4.6.8 Tag Support Levels) private static final ExifTag[] IFD_THUMBNAIL_TAGS = new ExifTag[] { // For below two, see TIFF 6.0 Spec Section 3: Bilevel Images. new ExifTag(TAG_NEW_SUBFILE_TYPE, 254, IFD_FORMAT_ULONG), new ExifTag(TAG_SUBFILE_TYPE, 255, IFD_FORMAT_ULONG), new ExifTag(TAG_THUMBNAIL_IMAGE_WIDTH, 256, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_THUMBNAIL_IMAGE_LENGTH, 257, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_BITS_PER_SAMPLE, 258, IFD_FORMAT_USHORT), new ExifTag(TAG_COMPRESSION, 259, IFD_FORMAT_USHORT), new ExifTag(TAG_PHOTOMETRIC_INTERPRETATION, 262, IFD_FORMAT_USHORT), new ExifTag(TAG_IMAGE_DESCRIPTION, 270, IFD_FORMAT_STRING), new ExifTag(TAG_MAKE, 271, IFD_FORMAT_STRING), new ExifTag(TAG_MODEL, 272, IFD_FORMAT_STRING), new ExifTag(TAG_STRIP_OFFSETS, 273, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_ORIENTATION, 274, IFD_FORMAT_USHORT), new ExifTag(TAG_SAMPLES_PER_PIXEL, 277, IFD_FORMAT_USHORT), new ExifTag(TAG_ROWS_PER_STRIP, 278, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_STRIP_BYTE_COUNTS, 279, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG), new ExifTag(TAG_X_RESOLUTION, 282, IFD_FORMAT_URATIONAL), new ExifTag(TAG_Y_RESOLUTION, 283, IFD_FORMAT_URATIONAL), new ExifTag(TAG_PLANAR_CONFIGURATION, 284, IFD_FORMAT_USHORT), new ExifTag(TAG_RESOLUTION_UNIT, 296, IFD_FORMAT_USHORT), new ExifTag(TAG_TRANSFER_FUNCTION, 301, IFD_FORMAT_USHORT), new ExifTag(TAG_SOFTWARE, 305, IFD_FORMAT_STRING), new ExifTag(TAG_DATETIME, 306, IFD_FORMAT_STRING), new ExifTag(TAG_ARTIST, 315, IFD_FORMAT_STRING), new ExifTag(TAG_WHITE_POINT, 318, IFD_FORMAT_URATIONAL), new ExifTag(TAG_PRIMARY_CHROMATICITIES, 319, IFD_FORMAT_URATIONAL), // See Adobe PageMaker® 6.0 TIFF Technical Notes, Note 1. new ExifTag(TAG_SUB_IFD_POINTER, 330, IFD_FORMAT_ULONG), new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT, 513, IFD_FORMAT_ULONG), new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 514, IFD_FORMAT_ULONG), new ExifTag(TAG_Y_CB_CR_COEFFICIENTS, 529, IFD_FORMAT_URATIONAL), new ExifTag(TAG_Y_CB_CR_SUB_SAMPLING, 530, IFD_FORMAT_USHORT), new ExifTag(TAG_Y_CB_CR_POSITIONING, 531, IFD_FORMAT_USHORT), new ExifTag(TAG_REFERENCE_BLACK_WHITE, 532, IFD_FORMAT_URATIONAL), new ExifTag(TAG_COPYRIGHT, 33432, IFD_FORMAT_STRING), new ExifTag(TAG_EXIF_IFD_POINTER, 34665, IFD_FORMAT_ULONG), new ExifTag(TAG_GPS_INFO_IFD_POINTER, 34853, IFD_FORMAT_ULONG), new ExifTag(TAG_DNG_VERSION, 50706, IFD_FORMAT_BYTE), new ExifTag(TAG_DEFAULT_CROP_SIZE, 50720, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG) }; // RAF file tag (See piex.cc line 372) private static final ExifTag TAG_RAF_IMAGE_SIZE = new ExifTag(TAG_STRIP_OFFSETS, 273, IFD_FORMAT_USHORT); // ORF file tags (See http://www.exiv2.org/tags-olympus.html) private static final ExifTag[] ORF_MAKER_NOTE_TAGS = new ExifTag[] { new ExifTag(TAG_ORF_THUMBNAIL_IMAGE, 256, IFD_FORMAT_UNDEFINED), new ExifTag(TAG_ORF_CAMERA_SETTINGS_IFD_POINTER, 8224, IFD_FORMAT_ULONG), new ExifTag(TAG_ORF_IMAGE_PROCESSING_IFD_POINTER, 8256, IFD_FORMAT_ULONG) }; private static final ExifTag[] ORF_CAMERA_SETTINGS_TAGS = new ExifTag[] { new ExifTag(TAG_ORF_PREVIEW_IMAGE_START, 257, IFD_FORMAT_ULONG), new ExifTag(TAG_ORF_PREVIEW_IMAGE_LENGTH, 258, IFD_FORMAT_ULONG) }; private static final ExifTag[] ORF_IMAGE_PROCESSING_TAGS = new ExifTag[] { new ExifTag(TAG_ORF_ASPECT_FRAME, 4371, IFD_FORMAT_USHORT) }; // PEF file tag (See http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Pentax.html) private static final ExifTag[] PEF_TAGS = new ExifTag[] { new ExifTag(TAG_COLOR_SPACE, 55, IFD_FORMAT_USHORT) }; // See JEITA CP-3451C Section 4.6.3: Exif-specific IFD. // The following values are used for indicating pointers to the other Image File Directories. // Indices of Exif Ifd tag groups /** @hide */ @Retention(RetentionPolicy.SOURCE) @IntDef({IFD_TYPE_PRIMARY, IFD_TYPE_EXIF, IFD_TYPE_GPS, IFD_TYPE_INTEROPERABILITY, IFD_TYPE_THUMBNAIL, IFD_TYPE_PREVIEW, IFD_TYPE_ORF_MAKER_NOTE, IFD_TYPE_ORF_CAMERA_SETTINGS, IFD_TYPE_ORF_IMAGE_PROCESSING, IFD_TYPE_PEF}) public @interface IfdType {} static final int IFD_TYPE_PRIMARY = 0; private static final int IFD_TYPE_EXIF = 1; private static final int IFD_TYPE_GPS = 2; private static final int IFD_TYPE_INTEROPERABILITY = 3; static final int IFD_TYPE_THUMBNAIL = 4; static final int IFD_TYPE_PREVIEW = 5; private static final int IFD_TYPE_ORF_MAKER_NOTE = 6; private static final int IFD_TYPE_ORF_CAMERA_SETTINGS = 7; private static final int IFD_TYPE_ORF_IMAGE_PROCESSING = 8; private static final int IFD_TYPE_PEF = 9; // List of Exif tag groups static final ExifTag[][] EXIF_TAGS = new ExifTag[][] { IFD_TIFF_TAGS, IFD_EXIF_TAGS, IFD_GPS_TAGS, IFD_INTEROPERABILITY_TAGS, IFD_THUMBNAIL_TAGS, IFD_TIFF_TAGS, ORF_MAKER_NOTE_TAGS, ORF_CAMERA_SETTINGS_TAGS, ORF_IMAGE_PROCESSING_TAGS, PEF_TAGS }; // List of tags for pointing to the other image file directory offset. private static final ExifTag[] EXIF_POINTER_TAGS = new ExifTag[] { new ExifTag(TAG_SUB_IFD_POINTER, 330, IFD_FORMAT_ULONG), new ExifTag(TAG_EXIF_IFD_POINTER, 34665, IFD_FORMAT_ULONG), new ExifTag(TAG_GPS_INFO_IFD_POINTER, 34853, IFD_FORMAT_ULONG), new ExifTag(TAG_INTEROPERABILITY_IFD_POINTER, 40965, IFD_FORMAT_ULONG), new ExifTag(TAG_ORF_CAMERA_SETTINGS_IFD_POINTER, 8224, IFD_FORMAT_BYTE), new ExifTag(TAG_ORF_IMAGE_PROCESSING_IFD_POINTER, 8256, IFD_FORMAT_BYTE) }; // Tags for indicating the thumbnail offset and length private static final ExifTag JPEG_INTERCHANGE_FORMAT_TAG = new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT, 513, IFD_FORMAT_ULONG); private static final ExifTag JPEG_INTERCHANGE_FORMAT_LENGTH_TAG = new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 514, IFD_FORMAT_ULONG); // Mappings from tag number to tag name and each item represents one IFD tag group. @SuppressWarnings("unchecked") private static final HashMap<Integer, ExifTag>[] sExifTagMapsForReading = new HashMap[EXIF_TAGS.length]; // Mappings from tag name to tag number and each item represents one IFD tag group. @SuppressWarnings("unchecked") private static final HashMap<String, ExifTag>[] sExifTagMapsForWriting = new HashMap[EXIF_TAGS.length]; private static final HashSet<String> sTagSetForCompatibility = new HashSet<>(Arrays.asList( TAG_F_NUMBER, TAG_DIGITAL_ZOOM_RATIO, TAG_EXPOSURE_TIME, TAG_SUBJECT_DISTANCE, TAG_GPS_TIMESTAMP)); // Mappings from tag number to IFD type for pointer tags. @SuppressWarnings("unchecked") private static final HashMap<Integer, Integer> sExifPointerTagMap = new HashMap(); // See JPEG File Interchange Format Version 1.02. // The following values are defined for handling JPEG streams. In this implementation, we are // not only getting information from EXIF but also from some JPEG special segments such as // MARKER_COM for user comment and MARKER_SOFx for image width and height. private static final Charset ASCII = Charset.forName("US-ASCII"); // Identifier for EXIF APP1 segment in JPEG static final byte[] IDENTIFIER_EXIF_APP1 = "Exif\0\0".getBytes(ASCII); // JPEG segment markers, that each marker consumes two bytes beginning with 0xff and ending with // the indicator. There is no SOF4, SOF8, SOF16 markers in JPEG and SOFx markers indicates start // of frame(baseline DCT) and the image size info exists in its beginning part. static final byte MARKER = (byte) 0xff; private static final byte MARKER_SOI = (byte) 0xd8; private static final byte MARKER_SOF0 = (byte) 0xc0; private static final byte MARKER_SOF1 = (byte) 0xc1; private static final byte MARKER_SOF2 = (byte) 0xc2; private static final byte MARKER_SOF3 = (byte) 0xc3; private static final byte MARKER_SOF5 = (byte) 0xc5; private static final byte MARKER_SOF6 = (byte) 0xc6; private static final byte MARKER_SOF7 = (byte) 0xc7; private static final byte MARKER_SOF9 = (byte) 0xc9; private static final byte MARKER_SOF10 = (byte) 0xca; private static final byte MARKER_SOF11 = (byte) 0xcb; private static final byte MARKER_SOF13 = (byte) 0xcd; private static final byte MARKER_SOF14 = (byte) 0xce; private static final byte MARKER_SOF15 = (byte) 0xcf; private static final byte MARKER_SOS = (byte) 0xda; static final byte MARKER_APP1 = (byte) 0xe1; private static final byte MARKER_COM = (byte) 0xfe; static final byte MARKER_EOI = (byte) 0xd9; // Supported Image File Types private static final int IMAGE_TYPE_UNKNOWN = 0; private static final int IMAGE_TYPE_ARW = 1; private static final int IMAGE_TYPE_CR2 = 2; private static final int IMAGE_TYPE_DNG = 3; private static final int IMAGE_TYPE_JPEG = 4; private static final int IMAGE_TYPE_NEF = 5; private static final int IMAGE_TYPE_NRW = 6; private static final int IMAGE_TYPE_ORF = 7; private static final int IMAGE_TYPE_PEF = 8; private static final int IMAGE_TYPE_RAF = 9; private static final int IMAGE_TYPE_RW2 = 10; private static final int IMAGE_TYPE_SRW = 11; static { sFormatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss"); sFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); // Build up the hash tables to look up Exif tags for reading Exif tags. for (int ifdType = 0; ifdType < EXIF_TAGS.length; ++ifdType) { sExifTagMapsForReading[ifdType] = new HashMap<>(); sExifTagMapsForWriting[ifdType] = new HashMap<>(); for (ExifTag tag : EXIF_TAGS[ifdType]) { sExifTagMapsForReading[ifdType].put(tag.number, tag); sExifTagMapsForWriting[ifdType].put(tag.name, tag); } } // Build up the hash table to look up Exif pointer tags. sExifPointerTagMap.put(EXIF_POINTER_TAGS[0].number, IFD_TYPE_PREVIEW); // 330 sExifPointerTagMap.put(EXIF_POINTER_TAGS[1].number, IFD_TYPE_EXIF); // 34665 sExifPointerTagMap.put(EXIF_POINTER_TAGS[2].number, IFD_TYPE_GPS); // 34853 sExifPointerTagMap.put(EXIF_POINTER_TAGS[3].number, IFD_TYPE_INTEROPERABILITY); // 40965 sExifPointerTagMap.put(EXIF_POINTER_TAGS[4].number, IFD_TYPE_ORF_CAMERA_SETTINGS); // 8224 sExifPointerTagMap.put(EXIF_POINTER_TAGS[5].number, IFD_TYPE_ORF_IMAGE_PROCESSING); // 8256 } private final String mFilename; private final AssetManager.AssetInputStream mAssetInputStream; private int mMimeType; @SuppressWarnings("unchecked") private final HashMap<String, ExifAttribute>[] mAttributes = new HashMap[EXIF_TAGS.length]; private ByteOrder mExifByteOrder = ByteOrder.BIG_ENDIAN; private boolean mHasThumbnail; // The following values used for indicating a thumbnail position. private int mThumbnailOffset; private int mThumbnailLength; private byte[] mThumbnailBytes; private int mThumbnailCompression; private int mExifOffset; private int mOrfMakerNoteOffset; private int mOrfThumbnailOffset; private int mOrfThumbnailLength; private int mRw2JpgFromRawOffset; private boolean mIsSupportedFile; // Pattern to check non zero timestamp private static final Pattern sNonZeroTimePattern = Pattern.compile(".*[1-9].*"); // Pattern to check gps timestamp private static final Pattern sGpsTimestampPattern = Pattern.compile("^([0-9][0-9]):([0-9][0-9]):([0-9][0-9])$"); /** * Reads Exif tags from the specified image file. */ public ExifInterface(String filename) throws IOException { if (filename == null) { throw new IllegalArgumentException("filename cannot be null"); } FileInputStream in = null; mAssetInputStream = null; mFilename = filename; try { in = new FileInputStream(filename); loadAttributes(in); } finally { closeQuietly(in); } } /** * Reads Exif tags from the specified image input stream. Attribute mutation is not supported * for input streams. The given input stream will proceed its current position. Developers * should close the input stream after use. This constructor is not intended to be used with * an input stream that performs any networking operations. */ public ExifInterface(InputStream inputStream) throws IOException { if (inputStream == null) { throw new IllegalArgumentException("inputStream cannot be null"); } mFilename = null; if (inputStream instanceof AssetManager.AssetInputStream) { mAssetInputStream = (AssetManager.AssetInputStream) inputStream; } else { mAssetInputStream = null; } loadAttributes(inputStream); } /** * Returns the EXIF attribute of the specified tag or {@code null} if there is no such tag in * the image file. * * @param tag the name of the tag. */ private ExifAttribute getExifAttribute(String tag) { if (TAG_ISO_SPEED_RATINGS.equals(tag)) { if (DEBUG) { Log.d(TAG, "getExifAttribute: Replacing TAG_ISO_SPEED_RATINGS with " + "TAG_PHOTOGRAPHIC_SENSITIVITY."); } tag = TAG_PHOTOGRAPHIC_SENSITIVITY; } // Retrieves all tag groups. The value from primary image tag group has a higher priority // than the value from the thumbnail tag group if there are more than one candidates. for (int i = 0; i < EXIF_TAGS.length; ++i) { ExifAttribute value = mAttributes[i].get(tag); if (value != null) { return value; } } return null; } /** * Returns the value of the specified tag or {@code null} if there * is no such tag in the image file. * * @param tag the name of the tag. */ public String getAttribute(String tag) { ExifAttribute attribute = getExifAttribute(tag); if (attribute != null) { if (!sTagSetForCompatibility.contains(tag)) { return attribute.getStringValue(mExifByteOrder); } if (tag.equals(TAG_GPS_TIMESTAMP)) { // Convert the rational values to the custom formats for backwards compatibility. if (attribute.format != IFD_FORMAT_URATIONAL && attribute.format != IFD_FORMAT_SRATIONAL) { Log.w(TAG, "GPS Timestamp format is not rational. format=" + attribute.format); return null; } Rational[] array = (Rational[]) attribute.getValue(mExifByteOrder); if (array == null || array.length != 3) { Log.w(TAG, "Invalid GPS Timestamp array. array=" + Arrays.toString(array)); return null; } return String.format("%02d:%02d:%02d", (int) ((float) array[0].numerator / array[0].denominator), (int) ((float) array[1].numerator / array[1].denominator), (int) ((float) array[2].numerator / array[2].denominator)); } try { return Double.toString(attribute.getDoubleValue(mExifByteOrder)); } catch (NumberFormatException e) { return null; } } return null; } /** * Returns the integer value of the specified tag. If there is no such tag * in the image file or the value cannot be parsed as integer, return * <var>defaultValue</var>. * * @param tag the name of the tag. * @param defaultValue the value to return if the tag is not available. */ public int getAttributeInt(String tag, int defaultValue) { ExifAttribute exifAttribute = getExifAttribute(tag); if (exifAttribute == null) { return defaultValue; } try { return exifAttribute.getIntValue(mExifByteOrder); } catch (NumberFormatException e) { return defaultValue; } } /** * Returns the double value of the tag that is specified as rational or contains a * double-formatted value. If there is no such tag in the image file or the value cannot be * parsed as double, return <var>defaultValue</var>. * * @param tag the name of the tag. * @param defaultValue the value to return if the tag is not available. */ public double getAttributeDouble(String tag, double defaultValue) { ExifAttribute exifAttribute = getExifAttribute(tag); if (exifAttribute == null) { return defaultValue; } try { return exifAttribute.getDoubleValue(mExifByteOrder); } catch (NumberFormatException e) { return defaultValue; } } /** * Sets the value of the specified tag. * * @param tag the name of the tag. * @param value the value of the tag. */ public void setAttribute(String tag, String value) { if (TAG_ISO_SPEED_RATINGS.equals(tag)) { if (DEBUG) { Log.d(TAG, "setAttribute: Replacing TAG_ISO_SPEED_RATINGS with " + "TAG_PHOTOGRAPHIC_SENSITIVITY."); } tag = TAG_PHOTOGRAPHIC_SENSITIVITY; } // Convert the given value to rational values for backwards compatibility. if (value != null && sTagSetForCompatibility.contains(tag)) { if (tag.equals(TAG_GPS_TIMESTAMP)) { Matcher m = sGpsTimestampPattern.matcher(value); if (!m.find()) { Log.w(TAG, "Invalid value for " + tag + " : " + value); return; } value = Integer.parseInt(m.group(1)) + "/1," + Integer.parseInt(m.group(2)) + "/1," + Integer.parseInt(m.group(3)) + "/1"; } else { try { double doubleValue = Double.parseDouble(value); value = new Rational(doubleValue).toString(); } catch (NumberFormatException e) { Log.w(TAG, "Invalid value for " + tag + " : " + value); return; } } } for (int i = 0 ; i < EXIF_TAGS.length; ++i) { if (i == IFD_TYPE_THUMBNAIL && !mHasThumbnail) { continue; } final ExifTag exifTag = sExifTagMapsForWriting[i].get(tag); if (exifTag != null) { if (value == null) { mAttributes[i].remove(tag); continue; } Pair<Integer, Integer> guess = guessDataFormat(value); int dataFormat; if (exifTag.primaryFormat == guess.first || exifTag.primaryFormat == guess.second) { dataFormat = exifTag.primaryFormat; } else if (exifTag.secondaryFormat != -1 && (exifTag.secondaryFormat == guess.first || exifTag.secondaryFormat == guess.second)) { dataFormat = exifTag.secondaryFormat; } else if (exifTag.primaryFormat == IFD_FORMAT_BYTE || exifTag.primaryFormat == IFD_FORMAT_UNDEFINED || exifTag.primaryFormat == IFD_FORMAT_STRING) { dataFormat = exifTag.primaryFormat; } else { Log.w(TAG, "Given tag (" + tag + ") value didn't match with one of expected " + "formats: " + IFD_FORMAT_NAMES[exifTag.primaryFormat] + (exifTag.secondaryFormat == -1 ? "" : ", " + IFD_FORMAT_NAMES[exifTag.secondaryFormat]) + " (guess: " + IFD_FORMAT_NAMES[guess.first] + (guess.second == -1 ? "" : ", " + IFD_FORMAT_NAMES[guess.second]) + ")"); continue; } switch (dataFormat) { case IFD_FORMAT_BYTE: { mAttributes[i].put(tag, ExifAttribute.createByte(value)); break; } case IFD_FORMAT_UNDEFINED: case IFD_FORMAT_STRING: { mAttributes[i].put(tag, ExifAttribute.createString(value)); break; } case IFD_FORMAT_USHORT: { final String[] values = value.split(","); final int[] intArray = new int[values.length]; for (int j = 0; j < values.length; ++j) { intArray[j] = Integer.parseInt(values[j]); } mAttributes[i].put(tag, ExifAttribute.createUShort(intArray, mExifByteOrder)); break; } case IFD_FORMAT_SLONG: { final String[] values = value.split(","); final int[] intArray = new int[values.length]; for (int j = 0; j < values.length; ++j) { intArray[j] = Integer.parseInt(values[j]); } mAttributes[i].put(tag, ExifAttribute.createSLong(intArray, mExifByteOrder)); break; } case IFD_FORMAT_ULONG: { final String[] values = value.split(","); final long[] longArray = new long[values.length]; for (int j = 0; j < values.length; ++j) { longArray[j] = Long.parseLong(values[j]); } mAttributes[i].put(tag, ExifAttribute.createULong(longArray, mExifByteOrder)); break; } case IFD_FORMAT_URATIONAL: { final String[] values = value.split(","); final Rational[] rationalArray = new Rational[values.length]; for (int j = 0; j < values.length; ++j) { final String[] numbers = values[j].split("/"); rationalArray[j] = new Rational((long) Double.parseDouble(numbers[0]), (long) Double.parseDouble(numbers[1])); } mAttributes[i].put(tag, ExifAttribute.createURational(rationalArray, mExifByteOrder)); break; } case IFD_FORMAT_SRATIONAL: { final String[] values = value.split(","); final Rational[] rationalArray = new Rational[values.length]; for (int j = 0; j < values.length; ++j) { final String[] numbers = values[j].split("/"); rationalArray[j] = new Rational((long) Double.parseDouble(numbers[0]), (long) Double.parseDouble(numbers[1])); } mAttributes[i].put(tag, ExifAttribute.createSRational(rationalArray, mExifByteOrder)); break; } case IFD_FORMAT_DOUBLE: { final String[] values = value.split(","); final double[] doubleArray = new double[values.length]; for (int j = 0; j < values.length; ++j) { doubleArray[j] = Double.parseDouble(values[j]); } mAttributes[i].put(tag, ExifAttribute.createDouble(doubleArray, mExifByteOrder)); break; } default: Log.w(TAG, "Data format isn't one of expected formats: " + dataFormat); continue; } } } } /** * Resets the {@link #TAG_ORIENTATION} of the image to be {@link #ORIENTATION_NORMAL}. */ public void resetOrientation() { setAttribute(TAG_ORIENTATION, Integer.toString(ORIENTATION_NORMAL)); } /** * Rotates the image by the given degree clockwise. The degree should be a multiple of * 90 (e.g, 90, 180, -90, etc.). * * @param degree The degree of rotation. */ public void rotate(int degree) { if (degree % 90 !=0) { throw new IllegalArgumentException("degree should be a multiple of 90"); } int currentOrientation = getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL); int currentIndex, newIndex; int resultOrientation; if (ROTATION_ORDER.contains(currentOrientation)) { currentIndex = ROTATION_ORDER.indexOf(currentOrientation); newIndex = (currentIndex + degree / 90) % 4; newIndex += newIndex < 0 ? 4 : 0; resultOrientation = ROTATION_ORDER.get(newIndex); } else if (FLIPPED_ROTATION_ORDER.contains(currentOrientation)) { currentIndex = FLIPPED_ROTATION_ORDER.indexOf(currentOrientation); newIndex = (currentIndex + degree / 90) % 4; newIndex += newIndex < 0 ? 4 : 0; resultOrientation = FLIPPED_ROTATION_ORDER.get(newIndex); } else { resultOrientation = ORIENTATION_UNDEFINED; } setAttribute(TAG_ORIENTATION, Integer.toString(resultOrientation)); } /** * Flips the image vertically. */ public void flipVertically() { int currentOrientation = getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL); int resultOrientation; switch (currentOrientation) { case ORIENTATION_FLIP_HORIZONTAL: resultOrientation = ORIENTATION_ROTATE_180; break; case ORIENTATION_ROTATE_180: resultOrientation = ORIENTATION_FLIP_HORIZONTAL; break; case ORIENTATION_FLIP_VERTICAL: resultOrientation = ORIENTATION_NORMAL; break; case ORIENTATION_TRANSPOSE: resultOrientation = ORIENTATION_ROTATE_270; break; case ORIENTATION_ROTATE_90: resultOrientation = ORIENTATION_TRANSVERSE; break; case ORIENTATION_TRANSVERSE: resultOrientation = ORIENTATION_ROTATE_90; break; case ORIENTATION_ROTATE_270: resultOrientation = ORIENTATION_TRANSPOSE; break; case ORIENTATION_NORMAL: resultOrientation = ORIENTATION_FLIP_VERTICAL; break; case ORIENTATION_UNDEFINED: default: resultOrientation = ORIENTATION_UNDEFINED; break; } setAttribute(TAG_ORIENTATION, Integer.toString(resultOrientation)); } /** * Flips the image horizontally. */ public void flipHorizontally() { int currentOrientation = getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL); int resultOrientation; switch (currentOrientation) { case ORIENTATION_FLIP_HORIZONTAL: resultOrientation = ORIENTATION_NORMAL; break; case ORIENTATION_ROTATE_180: resultOrientation = ORIENTATION_FLIP_VERTICAL; break; case ORIENTATION_FLIP_VERTICAL: resultOrientation = ORIENTATION_ROTATE_180; break; case ORIENTATION_TRANSPOSE: resultOrientation = ORIENTATION_ROTATE_90; break; case ORIENTATION_ROTATE_90: resultOrientation = ORIENTATION_TRANSPOSE; break; case ORIENTATION_TRANSVERSE: resultOrientation = ORIENTATION_ROTATE_270; break; case ORIENTATION_ROTATE_270: resultOrientation = ORIENTATION_TRANSVERSE; break; case ORIENTATION_NORMAL: resultOrientation = ORIENTATION_FLIP_HORIZONTAL; break; case ORIENTATION_UNDEFINED: default: resultOrientation = ORIENTATION_UNDEFINED; break; } setAttribute(TAG_ORIENTATION, Integer.toString(resultOrientation)); } /** * Returns if the current image orientation is flipped. * * @see #getRotationDegrees() */ public boolean isFlipped() { int orientation = getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL); switch (orientation) { case ORIENTATION_FLIP_HORIZONTAL: case ORIENTATION_TRANSVERSE: case ORIENTATION_FLIP_VERTICAL: case ORIENTATION_TRANSPOSE: return true; default: return false; } } /** * Returns the rotation degrees for the current image orientation. If the image is flipped, * i.e., {@link #isFlipped()} returns {@code true}, the rotation degrees will be base on * the assumption that the image is first flipped horizontally (along Y-axis), and then do * the rotation. For example, {@link #ORIENTATION_TRANSPOSE} will be interpreted as flipped * horizontally first, and then rotate 270 degrees clockwise. * * @return The rotation degrees of the image after the horizontal flipping is applied, if any. * * @see #isFlipped() */ public int getRotationDegrees() { int orientation = getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL); switch (orientation) { case ORIENTATION_ROTATE_90: case ORIENTATION_TRANSVERSE: return 90; case ORIENTATION_ROTATE_180: case ORIENTATION_FLIP_VERTICAL: return 180; case ORIENTATION_ROTATE_270: case ORIENTATION_TRANSPOSE: return 270; case ORIENTATION_UNDEFINED: case ORIENTATION_NORMAL: case ORIENTATION_FLIP_HORIZONTAL: default: return 0; } } /** * Update the values of the tags in the tag groups if any value for the tag already was stored. * * @param tag the name of the tag. * @param value the value of the tag in a form of {@link ExifAttribute}. * @return Returns {@code true} if updating is placed. */ private boolean updateAttribute(String tag, ExifAttribute value) { boolean updated = false; for (int i = 0 ; i < EXIF_TAGS.length; ++i) { if (mAttributes[i].containsKey(tag)) { mAttributes[i].put(tag, value); updated = true; } } return updated; } /** * Remove any values of the specified tag. * * @param tag the name of the tag. */ private void removeAttribute(String tag) { for (int i = 0 ; i < EXIF_TAGS.length; ++i) { mAttributes[i].remove(tag); } } /** * This function decides which parser to read the image data according to the given input stream * type and the content of the input stream. In each case, it reads the first three bytes to * determine whether the image data format is JPEG or not. */ private void loadAttributes(@NonNull InputStream in) throws IOException { try { // Initialize mAttributes. for (int i = 0; i < EXIF_TAGS.length; ++i) { mAttributes[i] = new HashMap<>(); } // Check file type in = new BufferedInputStream(in, SIGNATURE_CHECK_SIZE); mMimeType = getMimeType((BufferedInputStream) in); // Create byte-ordered input stream ByteOrderedDataInputStream inputStream = new ByteOrderedDataInputStream(in); switch (mMimeType) { case IMAGE_TYPE_JPEG: { getJpegAttributes(inputStream, 0, IFD_TYPE_PRIMARY); // 0 is offset break; } case IMAGE_TYPE_RAF: { getRafAttributes(inputStream); break; } case IMAGE_TYPE_ORF: { getOrfAttributes(inputStream); break; } case IMAGE_TYPE_RW2: { getRw2Attributes(inputStream); break; } case IMAGE_TYPE_ARW: case IMAGE_TYPE_CR2: case IMAGE_TYPE_DNG: case IMAGE_TYPE_NEF: case IMAGE_TYPE_NRW: case IMAGE_TYPE_PEF: case IMAGE_TYPE_SRW: case IMAGE_TYPE_UNKNOWN: { getRawAttributes(inputStream); break; } default: { break; } } // Set thumbnail image offset and length setThumbnailData(inputStream); mIsSupportedFile = true; } catch (IOException e) { // Ignore exceptions in order to keep the compatibility with the old versions of // ExifInterface. mIsSupportedFile = false; if (DEBUG) { Log.w(TAG, "Invalid image: ExifInterface got an unsupported image format file" + "(ExifInterface supports JPEG and some RAW image formats only) " + "or a corrupted JPEG file to ExifInterface.", e); } } finally { addDefaultValuesForCompatibility(); if (DEBUG) { printAttributes(); } } } // Prints out attributes for debugging. private void printAttributes() { for (int i = 0; i < mAttributes.length; ++i) { Log.d(TAG, "The size of tag group[" + i + "]: " + mAttributes[i].size()); for (Map.Entry<String, ExifAttribute> entry : mAttributes[i].entrySet()) { final ExifAttribute tagValue = entry.getValue(); Log.d(TAG, "tagName: " + entry.getKey() + ", tagType: " + tagValue.toString() + ", tagValue: '" + tagValue.getStringValue(mExifByteOrder) + "'"); } } } /** * Save the tag data into the original image file. This is expensive because it involves * copying all the data from one file to another and deleting the old file and renaming the * other. It's best to use {@link #setAttribute(String,String)} to set all attributes to write * and make a single call rather than multiple calls for each attribute. * <p> * This method is only supported for JPEG files. * </p> */ public void saveAttributes() throws IOException { if (!mIsSupportedFile || mMimeType != IMAGE_TYPE_JPEG) { throw new IOException("ExifInterface only supports saving attributes on JPEG formats."); } if (mFilename == null) { throw new IOException( "ExifInterface does not support saving attributes for the current input."); } // Keep the thumbnail in memory mThumbnailBytes = getThumbnail(); File tempFile = new File(mFilename + ".tmp"); File originalFile = new File(mFilename); if (!originalFile.renameTo(tempFile)) { throw new IOException("Could not rename to " + tempFile.getAbsolutePath()); } FileInputStream in = null; FileOutputStream out = null; try { // Save the new file. in = new FileInputStream(tempFile); out = new FileOutputStream(mFilename); saveJpegAttributes(in, out); } finally { closeQuietly(in); closeQuietly(out); tempFile.delete(); } // Discard the thumbnail in memory mThumbnailBytes = null; } /** * Returns true if the image file has a thumbnail. */ public boolean hasThumbnail() { return mHasThumbnail; } /** * Returns the JPEG compressed thumbnail inside the image file, or {@code null} if there is no * JPEG compressed thumbnail. * The returned data can be decoded using * {@link android.graphics.BitmapFactory#decodeByteArray(byte[],int,int)} */ public byte[] getThumbnail() { if (mThumbnailCompression == DATA_JPEG || mThumbnailCompression == DATA_JPEG_COMPRESSED) { return getThumbnailBytes(); } return null; } /** * Returns the thumbnail bytes inside the image file, regardless of the compression type of the * thumbnail image. */ public byte[] getThumbnailBytes() { if (!mHasThumbnail) { return null; } if (mThumbnailBytes != null) { return mThumbnailBytes; } // Read the thumbnail. InputStream in = null; try { if (mAssetInputStream != null) { in = mAssetInputStream; if (in.markSupported()) { in.reset(); } else { Log.d(TAG, "Cannot read thumbnail from inputstream without mark/reset support"); return null; } } else if (mFilename != null) { in = new FileInputStream(mFilename); } if (in == null) { // Should not be reached this. throw new FileNotFoundException(); } if (in.skip(mThumbnailOffset) != mThumbnailOffset) { throw new IOException("Corrupted image"); } byte[] buffer = new byte[mThumbnailLength]; if (in.read(buffer) != mThumbnailLength) { throw new IOException("Corrupted image"); } mThumbnailBytes = buffer; return buffer; } catch (IOException e) { // Couldn't get a thumbnail image. Log.d(TAG, "Encountered exception while getting thumbnail", e); } finally { closeQuietly(in); } return null; } /** * Creates and returns a Bitmap object of the thumbnail image based on the byte array and the * thumbnail compression value, or {@code null} if the compression type is unsupported. */ public Bitmap getThumbnailBitmap() { if (!mHasThumbnail) { return null; } else if (mThumbnailBytes == null) { mThumbnailBytes = getThumbnailBytes(); } if (mThumbnailCompression == DATA_JPEG || mThumbnailCompression == DATA_JPEG_COMPRESSED) { return BitmapFactory.decodeByteArray(mThumbnailBytes, 0, mThumbnailLength); } else if (mThumbnailCompression == DATA_UNCOMPRESSED) { int[] rgbValues = new int[mThumbnailBytes.length / 3]; byte alpha = (byte) 0xff000000; for (int i = 0; i < rgbValues.length; i++) { rgbValues[i] = alpha + (mThumbnailBytes[3 * i] << 16) + (mThumbnailBytes[3 * i + 1] << 8) + mThumbnailBytes[3 * i + 2]; } ExifAttribute imageLengthAttribute = (ExifAttribute) mAttributes[IFD_TYPE_THUMBNAIL].get(TAG_IMAGE_LENGTH); ExifAttribute imageWidthAttribute = (ExifAttribute) mAttributes[IFD_TYPE_THUMBNAIL].get(TAG_IMAGE_WIDTH); if (imageLengthAttribute != null && imageWidthAttribute != null) { int imageLength = imageLengthAttribute.getIntValue(mExifByteOrder); int imageWidth = imageWidthAttribute.getIntValue(mExifByteOrder); return Bitmap.createBitmap( rgbValues, imageWidth, imageLength, Bitmap.Config.ARGB_8888); } } return null; } /** * Returns true if thumbnail image is JPEG Compressed, or false if either thumbnail image does * not exist or thumbnail image is uncompressed. */ public boolean isThumbnailCompressed() { return mThumbnailCompression == DATA_JPEG || mThumbnailCompression == DATA_JPEG_COMPRESSED; } /** * Returns the offset and length of thumbnail inside the image file, or * {@code null} if there is no thumbnail. * * @return two-element array, the offset in the first value, and length in * the second, or {@code null} if no thumbnail was found. */ public long[] getThumbnailRange() { if (!mHasThumbnail) { return null; } long[] range = new long[2]; range[0] = mThumbnailOffset; range[1] = mThumbnailLength; return range; } /** * Stores the latitude and longitude value in a float array. The first element is the latitude, * and the second element is the longitude. Returns false if the Exif tags are not available. * * @deprecated Use {@link #getLatLong()} instead. */ @Deprecated public boolean getLatLong(float output[]) { double[] latLong = getLatLong(); if (latLong == null) { return false; } output[0] = (float) latLong[0]; output[1] = (float) latLong[1]; return true; } /** * Gets the latitude and longitude values. * <p> * If there are valid latitude and longitude values in the image, this method returns a double * array where the first element is the latitude and the second element is the longitude. * Otherwise, it returns null. */ public double[] getLatLong() { String latValue = getAttribute(TAG_GPS_LATITUDE); String latRef = getAttribute(TAG_GPS_LATITUDE_REF); String lngValue = getAttribute(TAG_GPS_LONGITUDE); String lngRef = getAttribute(TAG_GPS_LONGITUDE_REF); if (latValue != null && latRef != null && lngValue != null && lngRef != null) { try { double latitude = convertRationalLatLonToDouble(latValue, latRef); double longitude = convertRationalLatLonToDouble(lngValue, lngRef); return new double[] {latitude, longitude}; } catch (IllegalArgumentException e) { Log.w(TAG, "Latitude/longitude values are not parseable. " + String.format("latValue=%s, latRef=%s, lngValue=%s, lngRef=%s", latValue, latRef, lngValue, lngRef)); } } return null; } /** * Sets the GPS-related information. It will set GPS processing method, latitude and longitude * values, GPS timestamp, and speed information at the same time. * * @param location the {@link Location} object returned by GPS service. */ public void setGpsInfo(Location location) { if (location == null) { return; } setAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD, location.getProvider()); setLatLong(location.getLatitude(), location.getLongitude()); setAltitude(location.getAltitude()); // Location objects store speeds in m/sec. Translates it to km/hr here. setAttribute(TAG_GPS_SPEED_REF, "K"); setAttribute(TAG_GPS_SPEED, new Rational(location.getSpeed() * TimeUnit.HOURS.toSeconds(1) / 1000).toString()); String[] dateTime = sFormatter.format(new Date(location.getTime())).split("\\s+"); setAttribute(ExifInterface.TAG_GPS_DATESTAMP, dateTime[0]); setAttribute(ExifInterface.TAG_GPS_TIMESTAMP, dateTime[1]); } /** * Sets the latitude and longitude values. * * @param latitude the decimal value of latitude. Must be a valid double value between -90.0 and * 90.0. * @param longitude the decimal value of longitude. Must be a valid double value between -180.0 * and 180.0. * @throws IllegalArgumentException If {@code latitude} or {@code longitude} is outside the * specified range. */ public void setLatLong(double latitude, double longitude) { if (latitude < -90.0 || latitude > 90.0 || Double.isNaN(latitude)) { throw new IllegalArgumentException("Latitude value " + latitude + " is not valid."); } if (longitude < -180.0 || longitude > 180.0 || Double.isNaN(longitude)) { throw new IllegalArgumentException("Longitude value " + longitude + " is not valid."); } setAttribute(TAG_GPS_LATITUDE_REF, latitude >= 0 ? "N" : "S"); setAttribute(TAG_GPS_LATITUDE, convertDecimalDegree(Math.abs(latitude))); setAttribute(TAG_GPS_LONGITUDE_REF, longitude >= 0 ? "E" : "W"); setAttribute(TAG_GPS_LONGITUDE, convertDecimalDegree(Math.abs(longitude))); } /** * Return the altitude in meters. If the exif tag does not exist, return * <var>defaultValue</var>. * * @param defaultValue the value to return if the tag is not available. */ public double getAltitude(double defaultValue) { double altitude = getAttributeDouble(TAG_GPS_ALTITUDE, -1); int ref = getAttributeInt(TAG_GPS_ALTITUDE_REF, -1); if (altitude >= 0 && ref >= 0) { return (altitude * ((ref == 1) ? -1 : 1)); } else { return defaultValue; } } /** * Sets the altitude in meters. */ public void setAltitude(double altitude) { String ref = altitude >= 0 ? "0" : "1"; setAttribute(TAG_GPS_ALTITUDE, new Rational(Math.abs(altitude)).toString()); setAttribute(TAG_GPS_ALTITUDE_REF, ref); } /** * Set the date time value. * * @param timeStamp number of milliseconds since Jan. 1, 1970, midnight local time. * @hide */ public void setDateTime(long timeStamp) { long sub = timeStamp % 1000; setAttribute(TAG_DATETIME, sFormatter.format(new Date(timeStamp))); setAttribute(TAG_SUBSEC_TIME, Long.toString(sub)); } /** * Returns number of milliseconds since Jan. 1, 1970, midnight local time. * Returns -1 if the date time information if not available. * @hide */ public long getDateTime() { String dateTimeString = getAttribute(TAG_DATETIME); if (dateTimeString == null || !sNonZeroTimePattern.matcher(dateTimeString).matches()) return -1; ParsePosition pos = new ParsePosition(0); try { // The exif field is in local time. Parsing it as if it is UTC will yield time // since 1/1/1970 local time Date datetime = sFormatter.parse(dateTimeString, pos); if (datetime == null) return -1; long msecs = datetime.getTime(); String subSecs = getAttribute(TAG_SUBSEC_TIME); if (subSecs != null) { try { long sub = Long.parseLong(subSecs); while (sub > 1000) { sub /= 10; } msecs += sub; } catch (NumberFormatException e) { // Ignored } } return msecs; } catch (IllegalArgumentException e) { return -1; } } /** * Returns number of milliseconds since Jan. 1, 1970, midnight UTC. * Returns -1 if the date time information if not available. * @hide */ public long getGpsDateTime() { String date = getAttribute(TAG_GPS_DATESTAMP); String time = getAttribute(TAG_GPS_TIMESTAMP); if (date == null || time == null || (!sNonZeroTimePattern.matcher(date).matches() && !sNonZeroTimePattern.matcher(time).matches())) { return -1; } String dateTimeString = date + ' ' + time; ParsePosition pos = new ParsePosition(0); try { Date datetime = sFormatter.parse(dateTimeString, pos); if (datetime == null) return -1; return datetime.getTime(); } catch (IllegalArgumentException e) { return -1; } } private static double convertRationalLatLonToDouble(String rationalString, String ref) { try { String [] parts = rationalString.split(","); String [] pair; pair = parts[0].split("/"); double degrees = Double.parseDouble(pair[0].trim()) / Double.parseDouble(pair[1].trim()); pair = parts[1].split("/"); double minutes = Double.parseDouble(pair[0].trim()) / Double.parseDouble(pair[1].trim()); pair = parts[2].split("/"); double seconds = Double.parseDouble(pair[0].trim()) / Double.parseDouble(pair[1].trim()); double result = degrees + (minutes / 60.0) + (seconds / 3600.0); if ((ref.equals("S") || ref.equals("W"))) { return -result; } else if (ref.equals("N") || ref.equals("E")) { return result; } else { // Not valid throw new IllegalArgumentException(); } } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { // Not valid throw new IllegalArgumentException(); } } private String convertDecimalDegree(double decimalDegree) { long degrees = (long) decimalDegree; long minutes = (long) ((decimalDegree - degrees) * 60.0); long seconds = Math.round((decimalDegree - degrees - minutes / 60.0) * 3600.0 * 1e7); return degrees + "/1," + minutes + "/1," + seconds + "/10000000"; } // Checks the type of image file private int getMimeType(BufferedInputStream in) throws IOException { in.mark(SIGNATURE_CHECK_SIZE); byte[] signatureCheckBytes = new byte[SIGNATURE_CHECK_SIZE]; if (in.read(signatureCheckBytes) != SIGNATURE_CHECK_SIZE) { throw new EOFException(); } in.reset(); if (isJpegFormat(signatureCheckBytes)) { return IMAGE_TYPE_JPEG; } else if (isRafFormat(signatureCheckBytes)) { return IMAGE_TYPE_RAF; } else if (isOrfFormat(signatureCheckBytes)) { return IMAGE_TYPE_ORF; } else if (isRw2Format(signatureCheckBytes)) { return IMAGE_TYPE_RW2; } // Certain file formats (PEF) are identified in readImageFileDirectory() return IMAGE_TYPE_UNKNOWN; } /** * This method looks at the first 3 bytes to determine if this file is a JPEG file. * See http://www.media.mit.edu/pia/Research/deepview/exif.html, "JPEG format and Marker" */ private static boolean isJpegFormat(byte[] signatureCheckBytes) throws IOException { for (int i = 0; i < JPEG_SIGNATURE.length; i++) { if (signatureCheckBytes[i] != JPEG_SIGNATURE[i]) { return false; } } return true; } /** * This method looks at the first 15 bytes to determine if this file is a RAF file. * There is no official specification for RAF files from Fuji, but there is an online archive of * image file specifications: * http://fileformats.archiveteam.org/wiki/Fujifilm_RAF */ private boolean isRafFormat(byte[] signatureCheckBytes) throws IOException { byte[] rafSignatureBytes = RAF_SIGNATURE.getBytes(Charset.defaultCharset()); for (int i = 0; i < rafSignatureBytes.length; i++) { if (signatureCheckBytes[i] != rafSignatureBytes[i]) { return false; } } return true; } /** * ORF has a similar structure to TIFF but it contains a different signature at the TIFF Header. * This method looks at the 2 bytes following the Byte Order bytes to determine if this file is * an ORF file. * There is no official specification for ORF files from Olympus, but there is an online archive * of image file specifications: * http://fileformats.archiveteam.org/wiki/Olympus_ORF */ private boolean isOrfFormat(byte[] signatureCheckBytes) throws IOException { ByteOrderedDataInputStream signatureInputStream = new ByteOrderedDataInputStream(signatureCheckBytes); // Read byte order mExifByteOrder = readByteOrder(signatureInputStream); // Set byte order signatureInputStream.setByteOrder(mExifByteOrder); short orfSignature = signatureInputStream.readShort(); signatureInputStream.close(); return orfSignature == ORF_SIGNATURE_1 || orfSignature == ORF_SIGNATURE_2; } /** * RW2 is TIFF-based, but stores 0x55 signature byte instead of 0x42 at the header * See http://lclevy.free.fr/raw/ */ private boolean isRw2Format(byte[] signatureCheckBytes) throws IOException { ByteOrderedDataInputStream signatureInputStream = new ByteOrderedDataInputStream(signatureCheckBytes); // Read byte order mExifByteOrder = readByteOrder(signatureInputStream); // Set byte order signatureInputStream.setByteOrder(mExifByteOrder); short signatureByte = signatureInputStream.readShort(); signatureInputStream.close(); return signatureByte == RW2_SIGNATURE; } /** * Loads EXIF attributes from a JPEG input stream. * * @param in The input stream that starts with the JPEG data. * @param jpegOffset The offset value in input stream for JPEG data. * @param imageType The image type from which to retrieve metadata. Use IFD_TYPE_PRIMARY for * primary image, IFD_TYPE_PREVIEW for preview image, and * IFD_TYPE_THUMBNAIL for thumbnail image. * @throws IOException If the data contains invalid JPEG markers, offsets, or length values. */ private void getJpegAttributes(ByteOrderedDataInputStream in, int jpegOffset, int imageType) throws IOException { // See JPEG File Interchange Format Specification, "JFIF Specification" if (DEBUG) { Log.d(TAG, "getJpegAttributes starting with: " + in); } // JPEG uses Big Endian by default. See https://people.cs.umass.edu/~verts/cs32/endian.html in.setByteOrder(ByteOrder.BIG_ENDIAN); // Skip to JPEG data in.seek(jpegOffset); int bytesRead = jpegOffset; byte marker; if ((marker = in.readByte()) != MARKER) { throw new IOException("Invalid marker: " + Integer.toHexString(marker & 0xff)); } ++bytesRead; if (in.readByte() != MARKER_SOI) { throw new IOException("Invalid marker: " + Integer.toHexString(marker & 0xff)); } ++bytesRead; while (true) { marker = in.readByte(); if (marker != MARKER) { throw new IOException("Invalid marker:" + Integer.toHexString(marker & 0xff)); } ++bytesRead; marker = in.readByte(); if (DEBUG) { Log.d(TAG, "Found JPEG segment indicator: " + Integer.toHexString(marker & 0xff)); } ++bytesRead; // EOI indicates the end of an image and in case of SOS, JPEG image stream starts and // the image data will terminate right after. if (marker == MARKER_EOI || marker == MARKER_SOS) { break; } int length = in.readUnsignedShort() - 2; bytesRead += 2; if (DEBUG) { Log.d(TAG, "JPEG segment: " + Integer.toHexString(marker & 0xff) + " (length: " + (length + 2) + ")"); } if (length < 0) { throw new IOException("Invalid length"); } switch (marker) { case MARKER_APP1: { if (DEBUG) { Log.d(TAG, "MARKER_APP1"); } if (length < 6) { // Skip if it's not an EXIF APP1 segment. break; } byte[] identifier = new byte[6]; if (in.read(identifier) != 6) { throw new IOException("Invalid exif"); } bytesRead += 6; length -= 6; if (!Arrays.equals(identifier, IDENTIFIER_EXIF_APP1)) { // Skip if it's not an EXIF APP1 segment. break; } if (length <= 0) { throw new IOException("Invalid exif"); } if (DEBUG) { Log.d(TAG, "readExifSegment with a byte array (length: " + length + ")"); } // Save offset values for createJpegThumbnailBitmap() function mExifOffset = bytesRead; byte[] bytes = new byte[length]; if (in.read(bytes) != length) { throw new IOException("Invalid exif"); } bytesRead += length; length = 0; readExifSegment(bytes, imageType); break; } case MARKER_COM: { byte[] bytes = new byte[length]; if (in.read(bytes) != length) { throw new IOException("Invalid exif"); } length = 0; if (getAttribute(TAG_USER_COMMENT) == null) { mAttributes[IFD_TYPE_EXIF].put(TAG_USER_COMMENT, ExifAttribute.createString( new String(bytes, ASCII))); } break; } case MARKER_SOF0: case MARKER_SOF1: case MARKER_SOF2: case MARKER_SOF3: case MARKER_SOF5: case MARKER_SOF6: case MARKER_SOF7: case MARKER_SOF9: case MARKER_SOF10: case MARKER_SOF11: case MARKER_SOF13: case MARKER_SOF14: case MARKER_SOF15: { if (in.skipBytes(1) != 1) { throw new IOException("Invalid SOFx"); } mAttributes[imageType].put(TAG_IMAGE_LENGTH, ExifAttribute.createULong( in.readUnsignedShort(), mExifByteOrder)); mAttributes[imageType].put(TAG_IMAGE_WIDTH, ExifAttribute.createULong( in.readUnsignedShort(), mExifByteOrder)); length -= 5; break; } default: { break; } } if (length < 0) { throw new IOException("Invalid length"); } if (in.skipBytes(length) != length) { throw new IOException("Invalid JPEG segment"); } bytesRead += length; } // Restore original byte order in.setByteOrder(mExifByteOrder); } private void getRawAttributes(ByteOrderedDataInputStream in) throws IOException { // Parse TIFF Headers. See JEITA CP-3451C Section 4.5.2. Table 1. parseTiffHeaders(in, in.available()); // Read TIFF image file directories. See JEITA CP-3451C Section 4.5.2. Figure 6. readImageFileDirectory(in, IFD_TYPE_PRIMARY); // Update ImageLength/Width tags for all image data. updateImageSizeValues(in, IFD_TYPE_PRIMARY); updateImageSizeValues(in, IFD_TYPE_PREVIEW); updateImageSizeValues(in, IFD_TYPE_THUMBNAIL); // Check if each image data is in valid position. validateImages(in); if (mMimeType == IMAGE_TYPE_PEF) { // PEF files contain a MakerNote data, which contains the data for ColorSpace tag. // See http://lclevy.free.fr/raw/ and piex.cc PefGetPreviewData() ExifAttribute makerNoteAttribute = (ExifAttribute) mAttributes[IFD_TYPE_EXIF].get(TAG_MAKER_NOTE); if (makerNoteAttribute != null) { // Create an ordered DataInputStream for MakerNote ByteOrderedDataInputStream makerNoteDataInputStream = new ByteOrderedDataInputStream(makerNoteAttribute.bytes); makerNoteDataInputStream.setByteOrder(mExifByteOrder); // Seek to MakerNote data makerNoteDataInputStream.seek(PEF_MAKER_NOTE_SKIP_SIZE); // Read IFD data from MakerNote readImageFileDirectory(makerNoteDataInputStream, IFD_TYPE_PEF); // Update ColorSpace tag ExifAttribute colorSpaceAttribute = (ExifAttribute) mAttributes[IFD_TYPE_PEF].get(TAG_COLOR_SPACE); if (colorSpaceAttribute != null) { mAttributes[IFD_TYPE_EXIF].put(TAG_COLOR_SPACE, colorSpaceAttribute); } } } } /** * RAF files contains a JPEG and a CFA data. * The JPEG contains two images, a preview and a thumbnail, while the CFA contains a RAW image. * This method looks at the first 160 bytes of a RAF file to retrieve the offset and length * values for the JPEG and CFA data. * Using that data, it parses the JPEG data to retrieve the preview and thumbnail image data, * then parses the CFA metadata to retrieve the primary image length/width values. * For data format details, see http://fileformats.archiveteam.org/wiki/Fujifilm_RAF */ private void getRafAttributes(ByteOrderedDataInputStream in) throws IOException { // Retrieve offset & length values in.skipBytes(RAF_OFFSET_TO_JPEG_IMAGE_OFFSET); byte[] jpegOffsetBytes = new byte[4]; byte[] cfaHeaderOffsetBytes = new byte[4]; in.read(jpegOffsetBytes); // Skip JPEG length value since it is not needed in.skipBytes(RAF_JPEG_LENGTH_VALUE_SIZE); in.read(cfaHeaderOffsetBytes); int rafJpegOffset = ByteBuffer.wrap(jpegOffsetBytes).getInt(); int rafCfaHeaderOffset = ByteBuffer.wrap(cfaHeaderOffsetBytes).getInt(); // Retrieve JPEG image metadata getJpegAttributes(in, rafJpegOffset, IFD_TYPE_PREVIEW); // Skip to CFA header offset. in.seek(rafCfaHeaderOffset); // Retrieve primary image length/width values, if TAG_RAF_IMAGE_SIZE exists in.setByteOrder(ByteOrder.BIG_ENDIAN); int numberOfDirectoryEntry = in.readInt(); if (DEBUG) { Log.d(TAG, "numberOfDirectoryEntry: " + numberOfDirectoryEntry); } // CFA stores some metadata about the RAW image. Since CFA uses proprietary tags, can only // find and retrieve image size information tags, while skipping others. // See piex.cc RafGetDimension() for (int i = 0; i < numberOfDirectoryEntry; ++i) { int tagNumber = in.readUnsignedShort(); int numberOfBytes = in.readUnsignedShort(); if (tagNumber == TAG_RAF_IMAGE_SIZE.number) { int imageLength = in.readShort(); int imageWidth = in.readShort(); ExifAttribute imageLengthAttribute = ExifAttribute.createUShort(imageLength, mExifByteOrder); ExifAttribute imageWidthAttribute = ExifAttribute.createUShort(imageWidth, mExifByteOrder); mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH, imageLengthAttribute); mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH, imageWidthAttribute); if (DEBUG) { Log.d(TAG, "Updated to length: " + imageLength + ", width: " + imageWidth); } return; } in.skipBytes(numberOfBytes); } } /** * ORF files contains a primary image data and a MakerNote data that contains preview/thumbnail * images. Both data takes the form of IFDs and can therefore be read with the * readImageFileDirectory() method. * This method reads all the necessary data and updates the primary/preview/thumbnail image * information according to the GetOlympusPreviewImage() method in piex.cc. * For data format details, see the following: * http://fileformats.archiveteam.org/wiki/Olympus_ORF * https://libopenraw.freedesktop.org/wiki/Olympus_ORF */ private void getOrfAttributes(ByteOrderedDataInputStream in) throws IOException { // Retrieve primary image data // Other Exif data will be located in the Makernote. getRawAttributes(in); // Additionally retrieve preview/thumbnail information from MakerNote tag, which contains // proprietary tags and therefore does not have offical documentation // See GetOlympusPreviewImage() in piex.cc & http://www.exiv2.org/tags-olympus.html ExifAttribute makerNoteAttribute = (ExifAttribute) mAttributes[IFD_TYPE_EXIF].get(TAG_MAKER_NOTE); if (makerNoteAttribute != null) { // Create an ordered DataInputStream for MakerNote ByteOrderedDataInputStream makerNoteDataInputStream = new ByteOrderedDataInputStream(makerNoteAttribute.bytes); makerNoteDataInputStream.setByteOrder(mExifByteOrder); // There are two types of headers for Olympus MakerNotes // See http://www.exiv2.org/makernote.html#R1 byte[] makerNoteHeader1Bytes = new byte[ORF_MAKER_NOTE_HEADER_1.length]; makerNoteDataInputStream.readFully(makerNoteHeader1Bytes); makerNoteDataInputStream.seek(0); byte[] makerNoteHeader2Bytes = new byte[ORF_MAKER_NOTE_HEADER_2.length]; makerNoteDataInputStream.readFully(makerNoteHeader2Bytes); // Skip the corresponding amount of bytes for each header type if (Arrays.equals(makerNoteHeader1Bytes, ORF_MAKER_NOTE_HEADER_1)) { makerNoteDataInputStream.seek(ORF_MAKER_NOTE_HEADER_1_SIZE); } else if (Arrays.equals(makerNoteHeader2Bytes, ORF_MAKER_NOTE_HEADER_2)) { makerNoteDataInputStream.seek(ORF_MAKER_NOTE_HEADER_2_SIZE); } // Read IFD data from MakerNote readImageFileDirectory(makerNoteDataInputStream, IFD_TYPE_ORF_MAKER_NOTE); // Retrieve & update preview image offset & length values ExifAttribute imageStartAttribute = (ExifAttribute) mAttributes[IFD_TYPE_ORF_CAMERA_SETTINGS].get(TAG_ORF_PREVIEW_IMAGE_START); ExifAttribute imageLengthAttribute = (ExifAttribute) mAttributes[IFD_TYPE_ORF_CAMERA_SETTINGS].get(TAG_ORF_PREVIEW_IMAGE_LENGTH); if (imageStartAttribute != null && imageLengthAttribute != null) { mAttributes[IFD_TYPE_PREVIEW].put(TAG_JPEG_INTERCHANGE_FORMAT, imageStartAttribute); mAttributes[IFD_TYPE_PREVIEW].put(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, imageLengthAttribute); } // TODO: Check this behavior in other ORF files // Retrieve primary image length & width values // See piex.cc GetOlympusPreviewImage() ExifAttribute aspectFrameAttribute = (ExifAttribute) mAttributes[IFD_TYPE_ORF_IMAGE_PROCESSING].get(TAG_ORF_ASPECT_FRAME); if (aspectFrameAttribute != null) { int[] aspectFrameValues = (int[]) aspectFrameAttribute.getValue(mExifByteOrder); if (aspectFrameValues == null || aspectFrameValues.length != 4) { Log.w(TAG, "Invalid aspect frame values. frame=" + Arrays.toString(aspectFrameValues)); return; } if (aspectFrameValues[2] > aspectFrameValues[0] && aspectFrameValues[3] > aspectFrameValues[1]) { int primaryImageWidth = aspectFrameValues[2] - aspectFrameValues[0] + 1; int primaryImageLength = aspectFrameValues[3] - aspectFrameValues[1] + 1; // Swap width & length values if (primaryImageWidth < primaryImageLength) { primaryImageWidth += primaryImageLength; primaryImageLength = primaryImageWidth - primaryImageLength; primaryImageWidth -= primaryImageLength; } ExifAttribute primaryImageWidthAttribute = ExifAttribute.createUShort(primaryImageWidth, mExifByteOrder); ExifAttribute primaryImageLengthAttribute = ExifAttribute.createUShort(primaryImageLength, mExifByteOrder); mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH, primaryImageWidthAttribute); mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH, primaryImageLengthAttribute); } } } } // RW2 contains the primary image data in IFD0 and the preview and/or thumbnail image data in // the JpgFromRaw tag // See https://libopenraw.freedesktop.org/wiki/Panasonic_RAW/ and piex.cc Rw2GetPreviewData() private void getRw2Attributes(ByteOrderedDataInputStream in) throws IOException { // Retrieve primary image data getRawAttributes(in); // Retrieve preview and/or thumbnail image data ExifAttribute jpgFromRawAttribute = (ExifAttribute) mAttributes[IFD_TYPE_PRIMARY].get(TAG_RW2_JPG_FROM_RAW); if (jpgFromRawAttribute != null) { getJpegAttributes(in, mRw2JpgFromRawOffset, IFD_TYPE_PREVIEW); } // Set ISO tag value if necessary ExifAttribute rw2IsoAttribute = (ExifAttribute) mAttributes[IFD_TYPE_PRIMARY].get(TAG_RW2_ISO); ExifAttribute exifIsoAttribute = (ExifAttribute) mAttributes[IFD_TYPE_EXIF].get(TAG_PHOTOGRAPHIC_SENSITIVITY); if (rw2IsoAttribute != null && exifIsoAttribute == null) { // Place this attribute only if it doesn't exist mAttributes[IFD_TYPE_EXIF].put(TAG_PHOTOGRAPHIC_SENSITIVITY, rw2IsoAttribute); } } // Stores a new JPEG image with EXIF attributes into a given output stream. private void saveJpegAttributes(InputStream inputStream, OutputStream outputStream) throws IOException { // See JPEG File Interchange Format Specification, "JFIF Specification" if (DEBUG) { Log.d(TAG, "saveJpegAttributes starting with (inputStream: " + inputStream + ", outputStream: " + outputStream + ")"); } DataInputStream dataInputStream = new DataInputStream(inputStream); ByteOrderedDataOutputStream dataOutputStream = new ByteOrderedDataOutputStream(outputStream, ByteOrder.BIG_ENDIAN); if (dataInputStream.readByte() != MARKER) { throw new IOException("Invalid marker"); } dataOutputStream.writeByte(MARKER); if (dataInputStream.readByte() != MARKER_SOI) { throw new IOException("Invalid marker"); } dataOutputStream.writeByte(MARKER_SOI); // Write EXIF APP1 segment dataOutputStream.writeByte(MARKER); dataOutputStream.writeByte(MARKER_APP1); writeExifSegment(dataOutputStream, 6); byte[] bytes = new byte[4096]; while (true) { byte marker = dataInputStream.readByte(); if (marker != MARKER) { throw new IOException("Invalid marker"); } marker = dataInputStream.readByte(); switch (marker) { case MARKER_APP1: { int length = dataInputStream.readUnsignedShort() - 2; if (length < 0) { throw new IOException("Invalid length"); } byte[] identifier = new byte[6]; if (length >= 6) { if (dataInputStream.read(identifier) != 6) { throw new IOException("Invalid exif"); } if (Arrays.equals(identifier, IDENTIFIER_EXIF_APP1)) { // Skip the original EXIF APP1 segment. if (dataInputStream.skipBytes(length - 6) != length - 6) { throw new IOException("Invalid length"); } break; } } // Copy non-EXIF APP1 segment. dataOutputStream.writeByte(MARKER); dataOutputStream.writeByte(marker); dataOutputStream.writeUnsignedShort(length + 2); if (length >= 6) { length -= 6; dataOutputStream.write(identifier); } int read; while (length > 0 && (read = dataInputStream.read( bytes, 0, Math.min(length, bytes.length))) >= 0) { dataOutputStream.write(bytes, 0, read); length -= read; } break; } case MARKER_EOI: case MARKER_SOS: { dataOutputStream.writeByte(MARKER); dataOutputStream.writeByte(marker); // Copy all the remaining data copy(dataInputStream, dataOutputStream); return; } default: { // Copy JPEG segment dataOutputStream.writeByte(MARKER); dataOutputStream.writeByte(marker); int length = dataInputStream.readUnsignedShort(); dataOutputStream.writeUnsignedShort(length); length -= 2; if (length < 0) { throw new IOException("Invalid length"); } int read; while (length > 0 && (read = dataInputStream.read( bytes, 0, Math.min(length, bytes.length))) >= 0) { dataOutputStream.write(bytes, 0, read); length -= read; } break; } } } } // Reads the given EXIF byte area and save its tag data into attributes. private void readExifSegment(byte[] exifBytes, int imageType) throws IOException { ByteOrderedDataInputStream dataInputStream = new ByteOrderedDataInputStream(exifBytes); // Parse TIFF Headers. See JEITA CP-3451C Section 4.5.2. Table 1. parseTiffHeaders(dataInputStream, exifBytes.length); // Read TIFF image file directories. See JEITA CP-3451C Section 4.5.2. Figure 6. readImageFileDirectory(dataInputStream, imageType); } private void addDefaultValuesForCompatibility() { // If DATETIME tag has no value, then set the value to DATETIME_ORIGINAL tag's. String valueOfDateTimeOriginal = getAttribute(TAG_DATETIME_ORIGINAL); if (valueOfDateTimeOriginal != null && getAttribute(TAG_DATETIME) == null) { mAttributes[IFD_TYPE_PRIMARY].put(TAG_DATETIME, ExifAttribute.createString(valueOfDateTimeOriginal)); } // Add the default value. if (getAttribute(TAG_IMAGE_WIDTH) == null) { mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH, ExifAttribute.createULong(0, mExifByteOrder)); } if (getAttribute(TAG_IMAGE_LENGTH) == null) { mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH, ExifAttribute.createULong(0, mExifByteOrder)); } if (getAttribute(TAG_ORIENTATION) == null) { mAttributes[IFD_TYPE_PRIMARY].put(TAG_ORIENTATION, ExifAttribute.createULong(0, mExifByteOrder)); } if (getAttribute(TAG_LIGHT_SOURCE) == null) { mAttributes[IFD_TYPE_EXIF].put(TAG_LIGHT_SOURCE, ExifAttribute.createULong(0, mExifByteOrder)); } } private ByteOrder readByteOrder(ByteOrderedDataInputStream dataInputStream) throws IOException { // Read byte order. short byteOrder = dataInputStream.readShort(); switch (byteOrder) { case BYTE_ALIGN_II: if (DEBUG) { Log.d(TAG, "readExifSegment: Byte Align II"); } return ByteOrder.LITTLE_ENDIAN; case BYTE_ALIGN_MM: if (DEBUG) { Log.d(TAG, "readExifSegment: Byte Align MM"); } return ByteOrder.BIG_ENDIAN; default: throw new IOException("Invalid byte order: " + Integer.toHexString(byteOrder)); } } private void parseTiffHeaders(ByteOrderedDataInputStream dataInputStream, int exifBytesLength) throws IOException { // Read byte order mExifByteOrder = readByteOrder(dataInputStream); // Set byte order dataInputStream.setByteOrder(mExifByteOrder); // Check start code int startCode = dataInputStream.readUnsignedShort(); if (mMimeType != IMAGE_TYPE_ORF && mMimeType != IMAGE_TYPE_RW2 && startCode != START_CODE) { throw new IOException("Invalid start code: " + Integer.toHexString(startCode)); } // Read and skip to first ifd offset int firstIfdOffset = dataInputStream.readInt(); if (firstIfdOffset < 8 || firstIfdOffset >= exifBytesLength) { throw new IOException("Invalid first Ifd offset: " + firstIfdOffset); } firstIfdOffset -= 8; if (firstIfdOffset > 0) { if (dataInputStream.skipBytes(firstIfdOffset) != firstIfdOffset) { throw new IOException("Couldn't jump to first Ifd: " + firstIfdOffset); } } } // Reads image file directory, which is a tag group in EXIF. private void readImageFileDirectory(ByteOrderedDataInputStream dataInputStream, @IfdType int ifdType) throws IOException { if (dataInputStream.mPosition + 2 > dataInputStream.mLength) { // Return if there is no data from the offset. return; } // See TIFF 6.0 Section 2: TIFF Structure, Figure 1. short numberOfDirectoryEntry = dataInputStream.readShort(); if (DEBUG) { Log.d(TAG, "numberOfDirectoryEntry: " + numberOfDirectoryEntry); } if (dataInputStream.mPosition + 12 * numberOfDirectoryEntry > dataInputStream.mLength) { // Return if the size of entries is too big. return; } // See TIFF 6.0 Section 2: TIFF Structure, "Image File Directory". for (short i = 0; i < numberOfDirectoryEntry; ++i) { int tagNumber = dataInputStream.readUnsignedShort(); int dataFormat = dataInputStream.readUnsignedShort(); int numberOfComponents = dataInputStream.readInt(); // Next four bytes is for data offset or value. long nextEntryOffset = dataInputStream.peek() + 4; // Look up a corresponding tag from tag number ExifTag tag = (ExifTag) sExifTagMapsForReading[ifdType].get(tagNumber); if (DEBUG) { Log.d(TAG, String.format("ifdType: %d, tagNumber: %d, tagName: %s, dataFormat: %d, " + "numberOfComponents: %d", ifdType, tagNumber, tag != null ? tag.name : null, dataFormat, numberOfComponents)); } long byteCount = 0; boolean valid = false; if (tag == null) { Log.w(TAG, "Skip the tag entry since tag number is not defined: " + tagNumber); } else if (dataFormat <= 0 || dataFormat >= IFD_FORMAT_BYTES_PER_FORMAT.length) { Log.w(TAG, "Skip the tag entry since data format is invalid: " + dataFormat); } else if (!tag.isFormatCompatible(dataFormat)) { Log.w(TAG, "Skip the tag entry since data format (" + IFD_FORMAT_NAMES[dataFormat] + ") is unexpected for tag: " + tag.name); } else { if (dataFormat == IFD_FORMAT_UNDEFINED) { dataFormat = tag.primaryFormat; } byteCount = (long) numberOfComponents * IFD_FORMAT_BYTES_PER_FORMAT[dataFormat]; if (byteCount < 0 || byteCount > Integer.MAX_VALUE) { Log.w(TAG, "Skip the tag entry since the number of components is invalid: " + numberOfComponents); } else { valid = true; } } if (!valid) { dataInputStream.seek(nextEntryOffset); continue; } // Read a value from data field or seek to the value offset which is stored in data // field if the size of the entry value is bigger than 4. if (byteCount > 4) { int offset = dataInputStream.readInt(); if (DEBUG) { Log.d(TAG, "seek to data offset: " + offset); } if (mMimeType == IMAGE_TYPE_ORF) { if (TAG_MAKER_NOTE.equals(tag.name)) { // Save offset value for reading thumbnail mOrfMakerNoteOffset = offset; } else if (ifdType == IFD_TYPE_ORF_MAKER_NOTE && TAG_ORF_THUMBNAIL_IMAGE.equals(tag.name)) { // Retrieve & update values for thumbnail offset and length values for ORF mOrfThumbnailOffset = offset; mOrfThumbnailLength = numberOfComponents; ExifAttribute compressionAttribute = ExifAttribute.createUShort(DATA_JPEG, mExifByteOrder); ExifAttribute jpegInterchangeFormatAttribute = ExifAttribute.createULong(mOrfThumbnailOffset, mExifByteOrder); ExifAttribute jpegInterchangeFormatLengthAttribute = ExifAttribute.createULong(mOrfThumbnailLength, mExifByteOrder); mAttributes[IFD_TYPE_THUMBNAIL].put(TAG_COMPRESSION, compressionAttribute); mAttributes[IFD_TYPE_THUMBNAIL].put(TAG_JPEG_INTERCHANGE_FORMAT, jpegInterchangeFormatAttribute); mAttributes[IFD_TYPE_THUMBNAIL].put(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, jpegInterchangeFormatLengthAttribute); } } else if (mMimeType == IMAGE_TYPE_RW2) { if (TAG_RW2_JPG_FROM_RAW.equals(tag.name)) { mRw2JpgFromRawOffset = offset; } } if (offset + byteCount <= dataInputStream.mLength) { dataInputStream.seek(offset); } else { // Skip if invalid data offset. Log.w(TAG, "Skip the tag entry since data offset is invalid: " + offset); dataInputStream.seek(nextEntryOffset); continue; } } // Recursively parse IFD when a IFD pointer tag appears. Integer nextIfdType = sExifPointerTagMap.get(tagNumber); if (DEBUG) { Log.d(TAG, "nextIfdType: " + nextIfdType + " byteCount: " + byteCount); } if (nextIfdType != null) { long offset = -1L; // Get offset from data field switch (dataFormat) { case IFD_FORMAT_USHORT: { offset = dataInputStream.readUnsignedShort(); break; } case IFD_FORMAT_SSHORT: { offset = dataInputStream.readShort(); break; } case IFD_FORMAT_ULONG: { offset = dataInputStream.readUnsignedInt(); break; } case IFD_FORMAT_SLONG: case IFD_FORMAT_IFD: { offset = dataInputStream.readInt(); break; } default: { // Nothing to do break; } } if (DEBUG) { Log.d(TAG, String.format("Offset: %d, tagName: %s", offset, tag.name)); } if (offset > 0L && offset < dataInputStream.mLength) { dataInputStream.seek(offset); readImageFileDirectory(dataInputStream, nextIfdType); } else { Log.w(TAG, "Skip jump into the IFD since its offset is invalid: " + offset); } dataInputStream.seek(nextEntryOffset); continue; } byte[] bytes = new byte[(int) byteCount]; dataInputStream.readFully(bytes); ExifAttribute attribute = new ExifAttribute(dataFormat, numberOfComponents, bytes); mAttributes[ifdType].put(tag.name, attribute); // DNG files have a DNG Version tag specifying the version of specifications that the // image file is following. // See http://fileformats.archiveteam.org/wiki/DNG if (TAG_DNG_VERSION.equals(tag.name)) { mMimeType = IMAGE_TYPE_DNG; } // PEF files have a Make or Model tag that begins with "PENTAX" or a compression tag // that is 65535. // See http://fileformats.archiveteam.org/wiki/Pentax_PEF if (((TAG_MAKE.equals(tag.name) || TAG_MODEL.equals(tag.name)) && attribute.getStringValue(mExifByteOrder).contains(PEF_SIGNATURE)) || (TAG_COMPRESSION.equals(tag.name) && attribute.getIntValue(mExifByteOrder) == 65535)) { mMimeType = IMAGE_TYPE_PEF; } // Seek to next tag offset if (dataInputStream.peek() != nextEntryOffset) { dataInputStream.seek(nextEntryOffset); } } if (dataInputStream.peek() + 4 <= dataInputStream.mLength) { int nextIfdOffset = dataInputStream.readInt(); if (DEBUG) { Log.d(TAG, String.format("nextIfdOffset: %d", nextIfdOffset)); } // The next IFD offset needs to be bigger than 8 // since the first IFD offset is at least 8. if (nextIfdOffset > 8 && nextIfdOffset < dataInputStream.mLength) { dataInputStream.seek(nextIfdOffset); if (mAttributes[IFD_TYPE_THUMBNAIL].isEmpty()) { // Do not overwrite thumbnail IFD data if it alreay exists. readImageFileDirectory(dataInputStream, IFD_TYPE_THUMBNAIL); } else if (mAttributes[IFD_TYPE_PREVIEW].isEmpty()) { readImageFileDirectory(dataInputStream, IFD_TYPE_PREVIEW); } } } } /** * JPEG compressed images do not contain IMAGE_LENGTH & IMAGE_WIDTH tags. * This value uses JpegInterchangeFormat(JPEG data offset) value, and calls getJpegAttributes() * to locate SOF(Start of Frame) marker and update the image length & width values. * See JEITA CP-3451C Table 5 and Section 4.8.1. B. */ private void retrieveJpegImageSize(ByteOrderedDataInputStream in, int imageType) throws IOException { // Check if image already has IMAGE_LENGTH & IMAGE_WIDTH values ExifAttribute imageLengthAttribute = (ExifAttribute) mAttributes[imageType].get(TAG_IMAGE_LENGTH); ExifAttribute imageWidthAttribute = (ExifAttribute) mAttributes[imageType].get(TAG_IMAGE_WIDTH); if (imageLengthAttribute == null || imageWidthAttribute == null) { // Find if offset for JPEG data exists ExifAttribute jpegInterchangeFormatAttribute = (ExifAttribute) mAttributes[imageType].get(TAG_JPEG_INTERCHANGE_FORMAT); if (jpegInterchangeFormatAttribute != null) { int jpegInterchangeFormat = jpegInterchangeFormatAttribute.getIntValue(mExifByteOrder); // Searches for SOF marker in JPEG data and updates IMAGE_LENGTH & IMAGE_WIDTH tags getJpegAttributes(in, jpegInterchangeFormat, imageType); } } } // Sets thumbnail offset & length attributes based on JpegInterchangeFormat or StripOffsets tags private void setThumbnailData(ByteOrderedDataInputStream in) throws IOException { HashMap thumbnailData = mAttributes[IFD_TYPE_THUMBNAIL]; ExifAttribute compressionAttribute = (ExifAttribute) thumbnailData.get(TAG_COMPRESSION); if (compressionAttribute != null) { mThumbnailCompression = compressionAttribute.getIntValue(mExifByteOrder); switch (mThumbnailCompression) { case DATA_JPEG: { handleThumbnailFromJfif(in, thumbnailData); break; } case DATA_UNCOMPRESSED: case DATA_JPEG_COMPRESSED: { if (isSupportedDataType(thumbnailData)) { handleThumbnailFromStrips(in, thumbnailData); } break; } } } else { // Thumbnail data may not contain Compression tag value mThumbnailCompression = DATA_JPEG; handleThumbnailFromJfif(in, thumbnailData); } } // Check JpegInterchangeFormat(JFIF) tags to retrieve thumbnail offset & length values // and reads the corresponding bytes if stream does not support seek function private void handleThumbnailFromJfif(ByteOrderedDataInputStream in, HashMap thumbnailData) throws IOException { ExifAttribute jpegInterchangeFormatAttribute = (ExifAttribute) thumbnailData.get(TAG_JPEG_INTERCHANGE_FORMAT); ExifAttribute jpegInterchangeFormatLengthAttribute = (ExifAttribute) thumbnailData.get(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH); if (jpegInterchangeFormatAttribute != null && jpegInterchangeFormatLengthAttribute != null) { int thumbnailOffset = jpegInterchangeFormatAttribute.getIntValue(mExifByteOrder); int thumbnailLength = jpegInterchangeFormatLengthAttribute.getIntValue(mExifByteOrder); // The following code limits the size of thumbnail size not to overflow EXIF data area. thumbnailLength = Math.min(thumbnailLength, in.available() - thumbnailOffset); if (mMimeType == IMAGE_TYPE_JPEG || mMimeType == IMAGE_TYPE_RAF || mMimeType == IMAGE_TYPE_RW2) { thumbnailOffset += mExifOffset; } else if (mMimeType == IMAGE_TYPE_ORF) { // Update offset value since RAF files have IFD data preceding MakerNote data. thumbnailOffset += mOrfMakerNoteOffset; } if (DEBUG) { Log.d(TAG, "Setting thumbnail attributes with offset: " + thumbnailOffset + ", length: " + thumbnailLength); } if (thumbnailOffset > 0 && thumbnailLength > 0) { mHasThumbnail = true; mThumbnailOffset = thumbnailOffset; mThumbnailLength = thumbnailLength; if (mFilename == null && mAssetInputStream == null) { // Save the thumbnail in memory if the input doesn't support reading again. byte[] thumbnailBytes = new byte[thumbnailLength]; in.seek(thumbnailOffset); in.readFully(thumbnailBytes); mThumbnailBytes = thumbnailBytes; } } } } // Check StripOffsets & StripByteCounts tags to retrieve thumbnail offset & length values private void handleThumbnailFromStrips(ByteOrderedDataInputStream in, HashMap thumbnailData) throws IOException { ExifAttribute stripOffsetsAttribute = (ExifAttribute) thumbnailData.get(TAG_STRIP_OFFSETS); ExifAttribute stripByteCountsAttribute = (ExifAttribute) thumbnailData.get(TAG_STRIP_BYTE_COUNTS); if (stripOffsetsAttribute != null && stripByteCountsAttribute != null) { long[] stripOffsets = convertToLongArray(stripOffsetsAttribute.getValue(mExifByteOrder)); long[] stripByteCounts = convertToLongArray(stripByteCountsAttribute.getValue(mExifByteOrder)); if (stripOffsets == null) { Log.w(TAG, "stripOffsets should not be null."); return; } if (stripByteCounts == null) { Log.w(TAG, "stripByteCounts should not be null."); return; } long totalStripByteCount = 0; for (long byteCount : stripByteCounts) { totalStripByteCount += byteCount; } // Set thumbnail byte array data for non-consecutive strip bytes byte[] totalStripBytes = new byte[(int) totalStripByteCount]; int bytesRead = 0; int bytesAdded = 0; for (int i = 0; i < stripOffsets.length; i++) { int stripOffset = (int) stripOffsets[i]; int stripByteCount = (int) stripByteCounts[i]; // Skip to offset int skipBytes = stripOffset - bytesRead; if (skipBytes < 0) { Log.d(TAG, "Invalid strip offset value"); } in.seek(skipBytes); bytesRead += skipBytes; // Read strip bytes byte[] stripBytes = new byte[stripByteCount]; in.read(stripBytes); bytesRead += stripByteCount; // Add bytes to array System.arraycopy(stripBytes, 0, totalStripBytes, bytesAdded, stripBytes.length); bytesAdded += stripBytes.length; } mHasThumbnail = true; mThumbnailBytes = totalStripBytes; mThumbnailLength = totalStripBytes.length; } } // Check if thumbnail data type is currently supported or not private boolean isSupportedDataType(HashMap thumbnailData) throws IOException { ExifAttribute bitsPerSampleAttribute = (ExifAttribute) thumbnailData.get(TAG_BITS_PER_SAMPLE); if (bitsPerSampleAttribute != null) { int[] bitsPerSampleValue = (int[]) bitsPerSampleAttribute.getValue(mExifByteOrder); if (Arrays.equals(BITS_PER_SAMPLE_RGB, bitsPerSampleValue)) { return true; } // See DNG Specification 1.4.0.0. Section 3, Compression. if (mMimeType == IMAGE_TYPE_DNG) { ExifAttribute photometricInterpretationAttribute = (ExifAttribute) thumbnailData.get(TAG_PHOTOMETRIC_INTERPRETATION); if (photometricInterpretationAttribute != null) { int photometricInterpretationValue = photometricInterpretationAttribute.getIntValue(mExifByteOrder); if ((photometricInterpretationValue == PHOTOMETRIC_INTERPRETATION_BLACK_IS_ZERO && Arrays.equals(bitsPerSampleValue, BITS_PER_SAMPLE_GREYSCALE_2)) || ((photometricInterpretationValue == PHOTOMETRIC_INTERPRETATION_YCBCR) && (Arrays.equals(bitsPerSampleValue, BITS_PER_SAMPLE_RGB)))) { return true; } else { // TODO: Add support for lossless Huffman JPEG data } } } } if (DEBUG) { Log.d(TAG, "Unsupported data type value"); } return false; } // Returns true if the image length and width values are <= 512. // See Section 4.8 of http://standardsproposals.bsigroup.com/Home/getPDF/567 private boolean isThumbnail(HashMap map) throws IOException { ExifAttribute imageLengthAttribute = (ExifAttribute) map.get(TAG_IMAGE_LENGTH); ExifAttribute imageWidthAttribute = (ExifAttribute) map.get(TAG_IMAGE_WIDTH); if (imageLengthAttribute != null && imageWidthAttribute != null) { int imageLengthValue = imageLengthAttribute.getIntValue(mExifByteOrder); int imageWidthValue = imageWidthAttribute.getIntValue(mExifByteOrder); if (imageLengthValue <= MAX_THUMBNAIL_SIZE && imageWidthValue <= MAX_THUMBNAIL_SIZE) { return true; } } return false; } // Validate primary, preview, thumbnail image data by comparing image size private void validateImages(InputStream in) throws IOException { // Swap images based on size (primary > preview > thumbnail) swapBasedOnImageSize(IFD_TYPE_PRIMARY, IFD_TYPE_PREVIEW); swapBasedOnImageSize(IFD_TYPE_PRIMARY, IFD_TYPE_THUMBNAIL); swapBasedOnImageSize(IFD_TYPE_PREVIEW, IFD_TYPE_THUMBNAIL); // Check if image has PixelXDimension/PixelYDimension tags, which contain valid image // sizes, excluding padding at the right end or bottom end of the image to make sure that // the values are multiples of 64. See JEITA CP-3451C Table 5 and Section 4.8.1. B. ExifAttribute pixelXDimAttribute = (ExifAttribute) mAttributes[IFD_TYPE_EXIF].get(TAG_PIXEL_X_DIMENSION); ExifAttribute pixelYDimAttribute = (ExifAttribute) mAttributes[IFD_TYPE_EXIF].get(TAG_PIXEL_Y_DIMENSION); if (pixelXDimAttribute != null && pixelYDimAttribute != null) { mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH, pixelXDimAttribute); mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH, pixelYDimAttribute); } // Check whether thumbnail image exists and whether preview image satisfies the thumbnail // image requirements if (mAttributes[IFD_TYPE_THUMBNAIL].isEmpty()) { if (isThumbnail(mAttributes[IFD_TYPE_PREVIEW])) { mAttributes[IFD_TYPE_THUMBNAIL] = mAttributes[IFD_TYPE_PREVIEW]; mAttributes[IFD_TYPE_PREVIEW] = new HashMap<>(); } } // Check if the thumbnail image satisfies the thumbnail size requirements if (!isThumbnail(mAttributes[IFD_TYPE_THUMBNAIL])) { Log.d(TAG, "No image meets the size requirements of a thumbnail image."); } } /** * If image is uncompressed, ImageWidth/Length tags are used to store size info. * However, uncompressed images often store extra pixels around the edges of the final image, * which results in larger values for TAG_IMAGE_WIDTH and TAG_IMAGE_LENGTH tags. * This method corrects those tag values by checking first the values of TAG_DEFAULT_CROP_SIZE * See DNG Specification 1.4.0.0. Section 4. (DefaultCropSize) * * If image is a RW2 file, valid image sizes are stored in SensorBorder tags. * See tiff_parser.cc GetFullDimension32() * */ private void updateImageSizeValues(ByteOrderedDataInputStream in, int imageType) throws IOException { // Uncompressed image valid image size values ExifAttribute defaultCropSizeAttribute = (ExifAttribute) mAttributes[imageType].get(TAG_DEFAULT_CROP_SIZE); // RW2 image valid image size values ExifAttribute topBorderAttribute = (ExifAttribute) mAttributes[imageType].get(TAG_RW2_SENSOR_TOP_BORDER); ExifAttribute leftBorderAttribute = (ExifAttribute) mAttributes[imageType].get(TAG_RW2_SENSOR_LEFT_BORDER); ExifAttribute bottomBorderAttribute = (ExifAttribute) mAttributes[imageType].get(TAG_RW2_SENSOR_BOTTOM_BORDER); ExifAttribute rightBorderAttribute = (ExifAttribute) mAttributes[imageType].get(TAG_RW2_SENSOR_RIGHT_BORDER); if (defaultCropSizeAttribute != null) { // Update for uncompressed image ExifAttribute defaultCropSizeXAttribute, defaultCropSizeYAttribute; if (defaultCropSizeAttribute.format == IFD_FORMAT_URATIONAL) { Rational[] defaultCropSizeValue = (Rational[]) defaultCropSizeAttribute.getValue(mExifByteOrder); if (defaultCropSizeValue == null || defaultCropSizeValue.length != 2) { Log.w(TAG, "Invalid crop size values. cropSize=" + Arrays.toString(defaultCropSizeValue)); return; } defaultCropSizeXAttribute = ExifAttribute.createURational(defaultCropSizeValue[0], mExifByteOrder); defaultCropSizeYAttribute = ExifAttribute.createURational(defaultCropSizeValue[1], mExifByteOrder); } else { int[] defaultCropSizeValue = (int[]) defaultCropSizeAttribute.getValue(mExifByteOrder); if (defaultCropSizeValue == null || defaultCropSizeValue.length != 2) { Log.w(TAG, "Invalid crop size values. cropSize=" + Arrays.toString(defaultCropSizeValue)); return; } defaultCropSizeXAttribute = ExifAttribute.createUShort(defaultCropSizeValue[0], mExifByteOrder); defaultCropSizeYAttribute = ExifAttribute.createUShort(defaultCropSizeValue[1], mExifByteOrder); } mAttributes[imageType].put(TAG_IMAGE_WIDTH, defaultCropSizeXAttribute); mAttributes[imageType].put(TAG_IMAGE_LENGTH, defaultCropSizeYAttribute); } else if (topBorderAttribute != null && leftBorderAttribute != null && bottomBorderAttribute != null && rightBorderAttribute != null) { // Update for RW2 image int topBorderValue = topBorderAttribute.getIntValue(mExifByteOrder); int bottomBorderValue = bottomBorderAttribute.getIntValue(mExifByteOrder); int rightBorderValue = rightBorderAttribute.getIntValue(mExifByteOrder); int leftBorderValue = leftBorderAttribute.getIntValue(mExifByteOrder); if (bottomBorderValue > topBorderValue && rightBorderValue > leftBorderValue) { int length = bottomBorderValue - topBorderValue; int width = rightBorderValue - leftBorderValue; ExifAttribute imageLengthAttribute = ExifAttribute.createUShort(length, mExifByteOrder); ExifAttribute imageWidthAttribute = ExifAttribute.createUShort(width, mExifByteOrder); mAttributes[imageType].put(TAG_IMAGE_LENGTH, imageLengthAttribute); mAttributes[imageType].put(TAG_IMAGE_WIDTH, imageWidthAttribute); } } else { retrieveJpegImageSize(in, imageType); } } // Writes an Exif segment into the given output stream. private int writeExifSegment(ByteOrderedDataOutputStream dataOutputStream, int exifOffsetFromBeginning) throws IOException { // The following variables are for calculating each IFD tag group size in bytes. int[] ifdOffsets = new int[EXIF_TAGS.length]; int[] ifdDataSizes = new int[EXIF_TAGS.length]; // Remove IFD pointer tags (we'll re-add it later.) for (ExifTag tag : EXIF_POINTER_TAGS) { removeAttribute(tag.name); } // Remove old thumbnail data removeAttribute(JPEG_INTERCHANGE_FORMAT_TAG.name); removeAttribute(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name); // Remove null value tags. for (int ifdType = 0; ifdType < EXIF_TAGS.length; ++ifdType) { for (Object obj : mAttributes[ifdType].entrySet().toArray()) { final Map.Entry entry = (Map.Entry) obj; if (entry.getValue() == null) { mAttributes[ifdType].remove(entry.getKey()); } } } // Add IFD pointer tags. The next offset of primary image TIFF IFD will have thumbnail IFD // offset when there is one or more tags in the thumbnail IFD. if (!mAttributes[IFD_TYPE_EXIF].isEmpty()) { mAttributes[IFD_TYPE_PRIMARY].put(EXIF_POINTER_TAGS[1].name, ExifAttribute.createULong(0, mExifByteOrder)); } if (!mAttributes[IFD_TYPE_GPS].isEmpty()) { mAttributes[IFD_TYPE_PRIMARY].put(EXIF_POINTER_TAGS[2].name, ExifAttribute.createULong(0, mExifByteOrder)); } if (!mAttributes[IFD_TYPE_INTEROPERABILITY].isEmpty()) { mAttributes[IFD_TYPE_EXIF].put(EXIF_POINTER_TAGS[3].name, ExifAttribute.createULong(0, mExifByteOrder)); } if (mHasThumbnail) { mAttributes[IFD_TYPE_THUMBNAIL].put(JPEG_INTERCHANGE_FORMAT_TAG.name, ExifAttribute.createULong(0, mExifByteOrder)); mAttributes[IFD_TYPE_THUMBNAIL].put(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name, ExifAttribute.createULong(mThumbnailLength, mExifByteOrder)); } // Calculate IFD group data area sizes. IFD group data area is assigned to save the entry // value which has a bigger size than 4 bytes. for (int i = 0; i < EXIF_TAGS.length; ++i) { int sum = 0; for (Map.Entry<String, ExifAttribute> entry : mAttributes[i].entrySet()) { final ExifAttribute exifAttribute = entry.getValue(); final int size = exifAttribute.size(); if (size > 4) { sum += size; } } ifdDataSizes[i] += sum; } // Calculate IFD offsets. int position = 8; for (int ifdType = 0; ifdType < EXIF_TAGS.length; ++ifdType) { if (!mAttributes[ifdType].isEmpty()) { ifdOffsets[ifdType] = position; position += 2 + mAttributes[ifdType].size() * 12 + 4 + ifdDataSizes[ifdType]; } } if (mHasThumbnail) { int thumbnailOffset = position; mAttributes[IFD_TYPE_THUMBNAIL].put(JPEG_INTERCHANGE_FORMAT_TAG.name, ExifAttribute.createULong(thumbnailOffset, mExifByteOrder)); mThumbnailOffset = exifOffsetFromBeginning + thumbnailOffset; position += mThumbnailLength; } // Calculate the total size int totalSize = position + 8; // eight bytes is for header part. if (DEBUG) { Log.d(TAG, "totalSize length: " + totalSize); for (int i = 0; i < EXIF_TAGS.length; ++i) { Log.d(TAG, String.format("index: %d, offsets: %d, tag count: %d, data sizes: %d", i, ifdOffsets[i], mAttributes[i].size(), ifdDataSizes[i])); } } // Update IFD pointer tags with the calculated offsets. if (!mAttributes[IFD_TYPE_EXIF].isEmpty()) { mAttributes[IFD_TYPE_PRIMARY].put(EXIF_POINTER_TAGS[1].name, ExifAttribute.createULong(ifdOffsets[IFD_TYPE_EXIF], mExifByteOrder)); } if (!mAttributes[IFD_TYPE_GPS].isEmpty()) { mAttributes[IFD_TYPE_PRIMARY].put(EXIF_POINTER_TAGS[2].name, ExifAttribute.createULong(ifdOffsets[IFD_TYPE_GPS], mExifByteOrder)); } if (!mAttributes[IFD_TYPE_INTEROPERABILITY].isEmpty()) { mAttributes[IFD_TYPE_EXIF].put(EXIF_POINTER_TAGS[3].name, ExifAttribute.createULong( ifdOffsets[IFD_TYPE_INTEROPERABILITY], mExifByteOrder)); } // Write TIFF Headers. See JEITA CP-3451C Section 4.5.2. Table 1. dataOutputStream.writeUnsignedShort(totalSize); dataOutputStream.write(IDENTIFIER_EXIF_APP1); dataOutputStream.writeShort(mExifByteOrder == ByteOrder.BIG_ENDIAN ? BYTE_ALIGN_MM : BYTE_ALIGN_II); dataOutputStream.setByteOrder(mExifByteOrder); dataOutputStream.writeUnsignedShort(START_CODE); dataOutputStream.writeUnsignedInt(IFD_OFFSET); // Write IFD groups. See JEITA CP-3451C Section 4.5.8. Figure 9. for (int ifdType = 0; ifdType < EXIF_TAGS.length; ++ifdType) { if (!mAttributes[ifdType].isEmpty()) { // See JEITA CP-3451C Section 4.6.2: IFD structure. // Write entry count dataOutputStream.writeUnsignedShort(mAttributes[ifdType].size()); // Write entry info int dataOffset = ifdOffsets[ifdType] + 2 + mAttributes[ifdType].size() * 12 + 4; for (Map.Entry<String, ExifAttribute> entry : mAttributes[ifdType].entrySet()) { // Convert tag name to tag number. final ExifTag tag = sExifTagMapsForWriting[ifdType].get(entry.getKey()); final int tagNumber = tag.number; final ExifAttribute attribute = entry.getValue(); final int size = attribute.size(); dataOutputStream.writeUnsignedShort(tagNumber); dataOutputStream.writeUnsignedShort(attribute.format); dataOutputStream.writeInt(attribute.numberOfComponents); if (size > 4) { dataOutputStream.writeUnsignedInt(dataOffset); dataOffset += size; } else { dataOutputStream.write(attribute.bytes); // Fill zero up to 4 bytes if (size < 4) { for (int i = size; i < 4; ++i) { dataOutputStream.writeByte(0); } } } } // Write the next offset. It writes the offset of thumbnail IFD if there is one or // more tags in the thumbnail IFD when the current IFD is the primary image TIFF // IFD; Otherwise 0. if (ifdType == 0 && !mAttributes[IFD_TYPE_THUMBNAIL].isEmpty()) { dataOutputStream.writeUnsignedInt(ifdOffsets[IFD_TYPE_THUMBNAIL]); } else { dataOutputStream.writeUnsignedInt(0); } // Write values of data field exceeding 4 bytes after the next offset. for (Map.Entry<String, ExifAttribute> entry : mAttributes[ifdType].entrySet()) { ExifAttribute attribute = entry.getValue(); if (attribute.bytes.length > 4) { dataOutputStream.write(attribute.bytes, 0, attribute.bytes.length); } } } } // Write thumbnail if (mHasThumbnail) { dataOutputStream.write(getThumbnailBytes()); } // Reset the byte order to big endian in order to write remaining parts of the JPEG file. dataOutputStream.setByteOrder(ByteOrder.BIG_ENDIAN); return totalSize; } /** * Determines the data format of EXIF entry value. * * @param entryValue The value to be determined. * @return Returns two data formats gussed as a pair in integer. If there is no two candidate data formats for the given entry value, returns {@code -1} in the second of the pair. */ private static Pair<Integer, Integer> guessDataFormat(String entryValue) { // See TIFF 6.0 Section 2, "Image File Directory". // Take the first component if there are more than one component. if (entryValue.contains(",")) { String[] entryValues = entryValue.split(","); Pair<Integer, Integer> dataFormat = guessDataFormat(entryValues[0]); if (dataFormat.first == IFD_FORMAT_STRING) { return dataFormat; } for (int i = 1; i < entryValues.length; ++i) { final Pair<Integer, Integer> guessDataFormat = guessDataFormat(entryValues[i]); int first = -1, second = -1; if (guessDataFormat.first.equals(dataFormat.first) || guessDataFormat.second.equals(dataFormat.first)) { first = dataFormat.first; } if (dataFormat.second != -1 && (guessDataFormat.first.equals(dataFormat.second) || guessDataFormat.second.equals(dataFormat.second))) { second = dataFormat.second; } if (first == -1 && second == -1) { return new Pair<>(IFD_FORMAT_STRING, -1); } if (first == -1) { dataFormat = new Pair<>(second, -1); continue; } if (second == -1) { dataFormat = new Pair<>(first, -1); continue; } } return dataFormat; } if (entryValue.contains("/")) { String[] rationalNumber = entryValue.split("/"); if (rationalNumber.length == 2) { try { long numerator = (long) Double.parseDouble(rationalNumber[0]); long denominator = (long) Double.parseDouble(rationalNumber[1]); if (numerator < 0L || denominator < 0L) { return new Pair<>(IFD_FORMAT_SRATIONAL, -1); } if (numerator > Integer.MAX_VALUE || denominator > Integer.MAX_VALUE) { return new Pair<>(IFD_FORMAT_URATIONAL, -1); } return new Pair<>(IFD_FORMAT_SRATIONAL, IFD_FORMAT_URATIONAL); } catch (NumberFormatException e) { // Ignored } } return new Pair<>(IFD_FORMAT_STRING, -1); } try { Long longValue = Long.parseLong(entryValue); if (longValue >= 0 && longValue <= 65535) { return new Pair<>(IFD_FORMAT_USHORT, IFD_FORMAT_ULONG); } if (longValue < 0) { return new Pair<>(IFD_FORMAT_SLONG, -1); } return new Pair<>(IFD_FORMAT_ULONG, -1); } catch (NumberFormatException e) { // Ignored } try { Double.parseDouble(entryValue); return new Pair<>(IFD_FORMAT_DOUBLE, -1); } catch (NumberFormatException e) { // Ignored } return new Pair<>(IFD_FORMAT_STRING, -1); } // An input stream to parse EXIF data area, which can be written in either little or big endian // order. private static class ByteOrderedDataInputStream extends InputStream implements DataInput { private static final ByteOrder LITTLE_ENDIAN = ByteOrder.LITTLE_ENDIAN; private static final ByteOrder BIG_ENDIAN = ByteOrder.BIG_ENDIAN; private DataInputStream mDataInputStream; private ByteOrder mByteOrder = ByteOrder.BIG_ENDIAN; private final int mLength; private int mPosition; public ByteOrderedDataInputStream(InputStream in) throws IOException { mDataInputStream = new DataInputStream(in); mLength = mDataInputStream.available(); mPosition = 0; mDataInputStream.mark(mLength); } public ByteOrderedDataInputStream(byte[] bytes) throws IOException { this(new ByteArrayInputStream(bytes)); } public void setByteOrder(ByteOrder byteOrder) { mByteOrder = byteOrder; } public void seek(long byteCount) throws IOException { if (mPosition > byteCount) { mPosition = 0; mDataInputStream.reset(); mDataInputStream.mark(mLength); } else { byteCount -= mPosition; } if (skipBytes((int) byteCount) != (int) byteCount) { throw new IOException("Couldn't seek up to the byteCount"); } } public int peek() { return mPosition; } @Override public int available() throws IOException { return mDataInputStream.available(); } @Override public int read() throws IOException { ++mPosition; return mDataInputStream.read(); } @Override public int read(byte[] b, int off, int len) throws IOException { int bytesRead = mDataInputStream.read(b, off, len); mPosition += bytesRead; return bytesRead; } @Override public int readUnsignedByte() throws IOException { ++mPosition; return mDataInputStream.readUnsignedByte(); } @Override public String readLine() throws IOException { Log.d(TAG, "Currently unsupported"); return null; } @Override public boolean readBoolean() throws IOException { ++mPosition; return mDataInputStream.readBoolean(); } @Override public char readChar() throws IOException { mPosition += 2; return mDataInputStream.readChar(); } @Override public String readUTF() throws IOException { mPosition += 2; return mDataInputStream.readUTF(); } @Override public void readFully(byte[] buffer, int offset, int length) throws IOException { mPosition += length; if (mPosition > mLength) { throw new EOFException(); } if (mDataInputStream.read(buffer, offset, length) != length) { throw new IOException("Couldn't read up to the length of buffer"); } } @Override public void readFully(byte[] buffer) throws IOException { mPosition += buffer.length; if (mPosition > mLength) { throw new EOFException(); } if (mDataInputStream.read(buffer, 0, buffer.length) != buffer.length) { throw new IOException("Couldn't read up to the length of buffer"); } } @Override public byte readByte() throws IOException { ++mPosition; if (mPosition > mLength) { throw new EOFException(); } int ch = mDataInputStream.read(); if (ch < 0) { throw new EOFException(); } return (byte) ch; } @Override public short readShort() throws IOException { mPosition += 2; if (mPosition > mLength) { throw new EOFException(); } int ch1 = mDataInputStream.read(); int ch2 = mDataInputStream.read(); if ((ch1 | ch2) < 0) { throw new EOFException(); } if (mByteOrder == LITTLE_ENDIAN) { return (short) ((ch2 << 8) + (ch1)); } else if (mByteOrder == BIG_ENDIAN) { return (short) ((ch1 << 8) + (ch2)); } throw new IOException("Invalid byte order: " + mByteOrder); } @Override public int readInt() throws IOException { mPosition += 4; if (mPosition > mLength) { throw new EOFException(); } int ch1 = mDataInputStream.read(); int ch2 = mDataInputStream.read(); int ch3 = mDataInputStream.read(); int ch4 = mDataInputStream.read(); if ((ch1 | ch2 | ch3 | ch4) < 0) { throw new EOFException(); } if (mByteOrder == LITTLE_ENDIAN) { return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + ch1); } else if (mByteOrder == BIG_ENDIAN) { return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + ch4); } throw new IOException("Invalid byte order: " + mByteOrder); } @Override public int skipBytes(int byteCount) throws IOException { int totalSkip = Math.min(byteCount, mLength - mPosition); int skipped = 0; while (skipped < totalSkip) { skipped += mDataInputStream.skipBytes(totalSkip - skipped); } mPosition += skipped; return skipped; } @Override public int readUnsignedShort() throws IOException { mPosition += 2; if (mPosition > mLength) { throw new EOFException(); } int ch1 = mDataInputStream.read(); int ch2 = mDataInputStream.read(); if ((ch1 | ch2) < 0) { throw new EOFException(); } if (mByteOrder == LITTLE_ENDIAN) { return ((ch2 << 8) + (ch1)); } else if (mByteOrder == BIG_ENDIAN) { return ((ch1 << 8) + (ch2)); } throw new IOException("Invalid byte order: " + mByteOrder); } public long readUnsignedInt() throws IOException { return readInt() & 0xffffffffL; } @Override public long readLong() throws IOException { mPosition += 8; if (mPosition > mLength) { throw new EOFException(); } int ch1 = mDataInputStream.read(); int ch2 = mDataInputStream.read(); int ch3 = mDataInputStream.read(); int ch4 = mDataInputStream.read(); int ch5 = mDataInputStream.read(); int ch6 = mDataInputStream.read(); int ch7 = mDataInputStream.read(); int ch8 = mDataInputStream.read(); if ((ch1 | ch2 | ch3 | ch4 | ch5 | ch6 | ch7 | ch8) < 0) { throw new EOFException(); } if (mByteOrder == LITTLE_ENDIAN) { return (((long) ch8 << 56) + ((long) ch7 << 48) + ((long) ch6 << 40) + ((long) ch5 << 32) + ((long) ch4 << 24) + ((long) ch3 << 16) + ((long) ch2 << 8) + (long) ch1); } else if (mByteOrder == BIG_ENDIAN) { return (((long) ch1 << 56) + ((long) ch2 << 48) + ((long) ch3 << 40) + ((long) ch4 << 32) + ((long) ch5 << 24) + ((long) ch6 << 16) + ((long) ch7 << 8) + (long) ch8); } throw new IOException("Invalid byte order: " + mByteOrder); } @Override public float readFloat() throws IOException { return Float.intBitsToFloat(readInt()); } @Override public double readDouble() throws IOException { return Double.longBitsToDouble(readLong()); } } // An output stream to write EXIF data area, which can be written in either little or big endian // order. private static class ByteOrderedDataOutputStream extends FilterOutputStream { private final OutputStream mOutputStream; private ByteOrder mByteOrder; public ByteOrderedDataOutputStream(OutputStream out, ByteOrder byteOrder) { super(out); mOutputStream = out; mByteOrder = byteOrder; } public void setByteOrder(ByteOrder byteOrder) { mByteOrder = byteOrder; } @Override public void write(byte[] bytes) throws IOException { mOutputStream.write(bytes); } @Override public void write(byte[] bytes, int offset, int length) throws IOException { mOutputStream.write(bytes, offset, length); } public void writeByte(int val) throws IOException { mOutputStream.write(val); } public void writeShort(short val) throws IOException { if (mByteOrder == ByteOrder.LITTLE_ENDIAN) { mOutputStream.write((val >>> 0) & 0xFF); mOutputStream.write((val >>> 8) & 0xFF); } else if (mByteOrder == ByteOrder.BIG_ENDIAN) { mOutputStream.write((val >>> 8) & 0xFF); mOutputStream.write((val >>> 0) & 0xFF); } } public void writeInt(int val) throws IOException { if (mByteOrder == ByteOrder.LITTLE_ENDIAN) { mOutputStream.write((val >>> 0) & 0xFF); mOutputStream.write((val >>> 8) & 0xFF); mOutputStream.write((val >>> 16) & 0xFF); mOutputStream.write((val >>> 24) & 0xFF); } else if (mByteOrder == ByteOrder.BIG_ENDIAN) { mOutputStream.write((val >>> 24) & 0xFF); mOutputStream.write((val >>> 16) & 0xFF); mOutputStream.write((val >>> 8) & 0xFF); mOutputStream.write((val >>> 0) & 0xFF); } } public void writeUnsignedShort(int val) throws IOException { writeShort((short) val); } public void writeUnsignedInt(long val) throws IOException { writeInt((int) val); } } // Swaps image data based on image size private void swapBasedOnImageSize(@IfdType int firstIfdType, @IfdType int secondIfdType) throws IOException { if (mAttributes[firstIfdType].isEmpty() || mAttributes[secondIfdType].isEmpty()) { if (DEBUG) { Log.d(TAG, "Cannot perform swap since only one image data exists"); } return; } ExifAttribute firstImageLengthAttribute = (ExifAttribute) mAttributes[firstIfdType].get(TAG_IMAGE_LENGTH); ExifAttribute firstImageWidthAttribute = (ExifAttribute) mAttributes[firstIfdType].get(TAG_IMAGE_WIDTH); ExifAttribute secondImageLengthAttribute = (ExifAttribute) mAttributes[secondIfdType].get(TAG_IMAGE_LENGTH); ExifAttribute secondImageWidthAttribute = (ExifAttribute) mAttributes[secondIfdType].get(TAG_IMAGE_WIDTH); if (firstImageLengthAttribute == null || firstImageWidthAttribute == null) { if (DEBUG) { Log.d(TAG, "First image does not contain valid size information"); } } else if (secondImageLengthAttribute == null || secondImageWidthAttribute == null) { if (DEBUG) { Log.d(TAG, "Second image does not contain valid size information"); } } else { int firstImageLengthValue = firstImageLengthAttribute.getIntValue(mExifByteOrder); int firstImageWidthValue = firstImageWidthAttribute.getIntValue(mExifByteOrder); int secondImageLengthValue = secondImageLengthAttribute.getIntValue(mExifByteOrder); int secondImageWidthValue = secondImageWidthAttribute.getIntValue(mExifByteOrder); if (firstImageLengthValue < secondImageLengthValue && firstImageWidthValue < secondImageWidthValue) { HashMap<String, ExifAttribute> tempMap = mAttributes[firstIfdType]; mAttributes[firstIfdType] = mAttributes[secondIfdType]; mAttributes[secondIfdType] = tempMap; } } } /** * Closes 'closeable', ignoring any checked exceptions. Does nothing if 'closeable' is null. */ private static void closeQuietly(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (RuntimeException rethrown) { throw rethrown; } catch (Exception ignored) { } } } /** * Copies all of the bytes from {@code in} to {@code out}. Neither stream is closed. * Returns the total number of bytes transferred. */ private static int copy(InputStream in, OutputStream out) throws IOException { int total = 0; byte[] buffer = new byte[8192]; int c; while ((c = in.read(buffer)) != -1) { total += c; out.write(buffer, 0, c); } return total; } /** * Convert given int[] to long[]. If long[] is given, just return it. * Return null for other types of input. */ private static long[] convertToLongArray(Object inputObj) { if (inputObj instanceof int[]) { int[] input = (int[]) inputObj; long[] result = new long[input.length]; for (int i = 0; i < input.length; i++) { result[i] = input[i]; } return result; } else if (inputObj instanceof long[]) { return (long[]) inputObj; } return null; } }
Add nullability annotations to ExifInterface. Test: none Change-Id: I9ec5a94519d464138a55b2329a8515f57e3c0a74
exifinterface/src/android/support/media/ExifInterface.java
Add nullability annotations to ExifInterface.
<ide><path>xifinterface/src/android/support/media/ExifInterface.java <ide> import android.location.Location; <ide> import android.support.annotation.IntDef; <ide> import android.support.annotation.NonNull; <add>import android.support.annotation.Nullable; <ide> import android.util.Log; <ide> import android.util.Pair; <ide> <ide> /** <ide> * Reads Exif tags from the specified image file. <ide> */ <del> public ExifInterface(String filename) throws IOException { <add> public ExifInterface(@NonNull String filename) throws IOException { <ide> if (filename == null) { <ide> throw new IllegalArgumentException("filename cannot be null"); <ide> } <ide> * should close the input stream after use. This constructor is not intended to be used with <ide> * an input stream that performs any networking operations. <ide> */ <del> public ExifInterface(InputStream inputStream) throws IOException { <add> public ExifInterface(@NonNull InputStream inputStream) throws IOException { <ide> if (inputStream == null) { <ide> throw new IllegalArgumentException("inputStream cannot be null"); <ide> } <ide> * <ide> * @param tag the name of the tag. <ide> */ <del> private ExifAttribute getExifAttribute(String tag) { <add> @Nullable <add> private ExifAttribute getExifAttribute(@NonNull String tag) { <ide> if (TAG_ISO_SPEED_RATINGS.equals(tag)) { <ide> if (DEBUG) { <ide> Log.d(TAG, "getExifAttribute: Replacing TAG_ISO_SPEED_RATINGS with " <ide> * <ide> * @param tag the name of the tag. <ide> */ <del> public String getAttribute(String tag) { <add> @Nullable <add> public String getAttribute(@NonNull String tag) { <ide> ExifAttribute attribute = getExifAttribute(tag); <ide> if (attribute != null) { <ide> if (!sTagSetForCompatibility.contains(tag)) { <ide> * @param tag the name of the tag. <ide> * @param defaultValue the value to return if the tag is not available. <ide> */ <del> public int getAttributeInt(String tag, int defaultValue) { <add> public int getAttributeInt(@NonNull String tag, int defaultValue) { <ide> ExifAttribute exifAttribute = getExifAttribute(tag); <ide> if (exifAttribute == null) { <ide> return defaultValue; <ide> * @param tag the name of the tag. <ide> * @param defaultValue the value to return if the tag is not available. <ide> */ <del> public double getAttributeDouble(String tag, double defaultValue) { <add> public double getAttributeDouble(@NonNull String tag, double defaultValue) { <ide> ExifAttribute exifAttribute = getExifAttribute(tag); <ide> if (exifAttribute == null) { <ide> return defaultValue; <ide> * @param tag the name of the tag. <ide> * @param value the value of the tag. <ide> */ <del> public void setAttribute(String tag, String value) { <add> public void setAttribute(@NonNull String tag, @Nullable String value) { <ide> if (TAG_ISO_SPEED_RATINGS.equals(tag)) { <ide> if (DEBUG) { <ide> Log.d(TAG, "setAttribute: Replacing TAG_ISO_SPEED_RATINGS with " <ide> * The returned data can be decoded using <ide> * {@link android.graphics.BitmapFactory#decodeByteArray(byte[],int,int)} <ide> */ <add> @Nullable <ide> public byte[] getThumbnail() { <ide> if (mThumbnailCompression == DATA_JPEG || mThumbnailCompression == DATA_JPEG_COMPRESSED) { <ide> return getThumbnailBytes(); <ide> * Returns the thumbnail bytes inside the image file, regardless of the compression type of the <ide> * thumbnail image. <ide> */ <add> @Nullable <ide> public byte[] getThumbnailBytes() { <ide> if (!mHasThumbnail) { <ide> return null; <ide> * Creates and returns a Bitmap object of the thumbnail image based on the byte array and the <ide> * thumbnail compression value, or {@code null} if the compression type is unsupported. <ide> */ <add> @Nullable <ide> public Bitmap getThumbnailBitmap() { <ide> if (!mHasThumbnail) { <ide> return null; <ide> * @return two-element array, the offset in the first value, and length in <ide> * the second, or {@code null} if no thumbnail was found. <ide> */ <add> @Nullable <ide> public long[] getThumbnailRange() { <ide> if (!mHasThumbnail) { <ide> return null; <ide> * array where the first element is the latitude and the second element is the longitude. <ide> * Otherwise, it returns null. <ide> */ <add> @Nullable <ide> public double[] getLatLong() { <ide> String latValue = getAttribute(TAG_GPS_LATITUDE); <ide> String latRef = getAttribute(TAG_GPS_LATITUDE_REF);
JavaScript
apache-2.0
acee4c54ba0993bb2ca6b831b41bc0ee2c5cb354
0
xdegenne/alien4cloud,san-tak/alien4cloud,broly-git/alien4cloud,PierreLemordant/alien4cloud,ngouagna/alien4cloud,OresteVisari/alien4cloud,PierreLemordant/alien4cloud,broly-git/alien4cloud,broly-git/alien4cloud,PierreLemordant/alien4cloud,OresteVisari/alien4cloud,alien4cloud/alien4cloud,ngouagna/alien4cloud,ngouagna/alien4cloud,broly-git/alien4cloud,loicalbertin/alien4cloud,ngouagna/alien4cloud,xdegenne/alien4cloud,san-tak/alien4cloud,loicalbertin/alien4cloud,loicalbertin/alien4cloud,san-tak/alien4cloud,alien4cloud/alien4cloud,igorng/alien4cloud,alien4cloud/alien4cloud,ahgittin/alien4cloud,ahgittin/alien4cloud,igorng/alien4cloud,xdegenne/alien4cloud,OresteVisari/alien4cloud,xdegenne/alien4cloud,OresteVisari/alien4cloud,igorng/alien4cloud,alien4cloud/alien4cloud,san-tak/alien4cloud,ahgittin/alien4cloud,igorng/alien4cloud,loicalbertin/alien4cloud,ahgittin/alien4cloud,PierreLemordant/alien4cloud
// Generated on 2014-01-13 using generator-angular 0.7.1 'use strict'; // # Globbing // for performance reasons we're only matching one level down: // 'test/spec/{,*/}*.js' // use this if you want to recursively match all subfolders: // 'test/spec/**/*.js' module.exports = function(grunt) { // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // Load grunt-connect-proxy module grunt.loadNpmTasks('grunt-connect-proxy'); // Load grunt-protractor module grunt.loadNpmTasks('grunt-protractor-runner'); // Load protractor packaged selenium server grunt.loadNpmTasks('grunt-protractor_webdriver'); // load grunt-ng-annotate module grunt.loadNpmTasks('grunt-ng-annotate'); // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); // Define the configuration for all the tasks grunt.initConfig({ // Project settings yeoman: { // configurable paths app: require('./bower.json').appPath || 'app', dist: 'dist' }, // Watches files for changes and runs tasks based on the changed files watch: { js: { files: ['<%= yeoman.app %>/scripts/**/*.js'], tasks: ['newer:jshint:all'], options: { livereload: true } }, jsTest: { files: ['test/spec/{,*/}*.js'], tasks: ['newer:jshint:test', 'karma'] }, compass: { files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'], tasks: ['compass:server', 'autoprefixer'] }, gruntfile: { files: ['Gruntfile.js'] }, livereload: { options: { livereload: '<%= connect.options.livereload %>' }, files: ['<%= yeoman.app %>/bower_components/**/*.js', '<%= yeoman.app %>/views/**/*.html', '.tmp/styles/{,*/}*.css', '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'] } }, // The actual grunt server settings connect: { options: { port: 9999, // Change this to'0.0.0.0' to access the server from outside. hostname: 'localhost', livereload: 35729 }, proxies: [ /* * proxy all /rest* request to tomcat domain with specific spring security * requests */ { context: ['/rest', '/api-docs', '/login', '/logout', '/img', '/csarrepository', '/version.json'], host: 'localhost', port: 8088 } ], livereload: { options: { open: true, base: ['.tmp', '<%= yeoman.app %>'], middleware: function(connect, options) { if (!Array.isArray(options.base)) { options.base = [options.base]; } // Setup the proxy var middlewares = [require('grunt-connect-proxy/lib/utils').proxyRequest]; // Serve static files. options.base.forEach(function(base) { middlewares.push(connect.static(base)); }); // Make directory browse-able. var directory = options.directory || options.base[options.base.length - 1]; middlewares.push(connect.directory(directory)); return middlewares; } } }, test: { options: { port: 9998, base: ['.tmp', 'test', '<%= yeoman.app %>'] } }, dist: { options: { base: '<%= yeoman.dist %>' } } }, // Make sure code styles are up to par and there are no obvious mistakes jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish'), force: true }, all: ['Gruntfile.js', '<%= yeoman.app %>/scripts/{,*/}*.js'], test: { options: { jshintrc: 'test/.jshintrc' }, src: ['test/spec/{,*/}*.js'] } }, // Empties folders to start fresh clean: { dist: { files: [{ dot: true, src: ['.tmp', '<%= yeoman.dist %>/*', '!<%= yeoman.dist %>/.git*'] }] }, server: '.tmp' }, // Add vendor prefixed styles autoprefixer: { options: { browsers: ['last 1 version'] }, dist: { files: [{ expand: true, cwd: '.tmp/styles/', src: '{,*/}*.css', dest: '.tmp/styles/' }] } }, // Automatically inject Bower components into the app 'bower-install': { app: { html: '<%= yeoman.app %>/index.html', ignorePath: '<%= yeoman.app %>/' } }, // Compiles Sass to CSS and generates necessary files if requested compass: { options: { sassDir: '<%= yeoman.app %>/styles', cssDir: '.tmp/styles', generatedImagesDir: '.tmp/images/generated', imagesDir: '<%= yeoman.app %>/images', javascriptsDir: '<%= yeoman.app %>/scripts', fontsDir: '<%= yeoman.app %>/styles/fonts', importPath: '<%= yeoman.app %>/bower_components', httpImagesPath: '/images', httpGeneratedImagesPath: '/images/generated', httpFontsPath: '/styles/fonts', relativeAssets: false, assetCacheBuster: false, raw: 'Sass::Script::Number.precision = 10\n' }, dist: { options: { generatedImagesDir: '<%= yeoman.dist %>/images/generated' } }, server: { options: { debugInfo: true } } }, // Renames files for browser caching purposes rev: { dist: { files: { src: ['<%= yeoman.dist %>/scripts/{,*/}*.js', '<%= yeoman.dist %>/styles/{,*/}*.css', // '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}', '<%= yeoman.dist %>/styles/fonts/*' ] } } }, // Reads HTML for usemin blocks to enable smart builds that automatically // concat, minify and revision files. Creates configurations in memory so // additional tasks can operate on them useminPrepare: { html: '<%= yeoman.app %>/index.html', options: { dest: '<%= yeoman.dist %>' } }, // Performs rewrites based on rev and the useminPrepare configuration usemin: { html: ['<%= yeoman.dist %>/{,*/}*.html'], css: ['<%= yeoman.dist %>/styles/{,*/}*.css'], options: { assetsDirs: ['<%= yeoman.dist %>'] } }, // The following *-min tasks produce minified files in the dist folder imagemin: { dist: { files: [{ expand: true, cwd: '<%= yeoman.app %>/images', src: '{,*/}*.{png,jpg,jpeg,gif}', dest: '<%= yeoman.dist %>/images' }] } }, svgmin: { dist: { files: [{ expand: true, cwd: '<%= yeoman.app %>/images', src: '{,*/}*.svg', dest: '<%= yeoman.dist %>/images' }] } }, htmlmin: { dist: { options: { collapseWhitespace: true, collapseBooleanAttributes: false, removeCommentsFromCDATA: true, removeOptionalTags: false }, files: [{ expand: true, cwd: '<%= yeoman.dist %>', // src: ['*.html', 'views/{,*/}*.html'], src: ['*.html', 'views/**/*.html'], dest: '<%= yeoman.dist %>' }] } }, // Allow the use of non-minsafe AngularJS files. Automatically makes it // minsafe compatible so Uglify does not destroy the ng references ngAnnotate: { dist: { files: [{ expand: true, cwd: '.tmp/concat/scripts', src: '*.js', dest: '.tmp/concat/scripts' }] } }, // Replace Google CDN references cdnify: { dist: { html: ['<%= yeoman.dist %>/*.html'] } }, // Copies remaining files to places other tasks can use copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%= yeoman.app %>', dest: '<%= yeoman.dist %>', src: ['*.{ico,png,txt}', '.htaccess', '*.html', // 'views/{,*/}*.html', 'views/**/*.html', 'bower_components/**/*', 'js-lib/**/*', 'images/**/*', 'data/**/*', 'api-doc/**/*', 'version.json', // 'images/{,*/}*.{webp}', // 'images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}', 'fonts/*' ] }, { expand: true, cwd: '.tmp/images', dest: '<%= yeoman.dist %>/images', src: ['generated/*'] }, { expand: true, flatten: true, cwd: '<%= yeoman.app %>', dest: '<%= yeoman.dist %>/images', src: ['bower_components/angular-tree-control/images/*'] }] }, styles: { expand: true, cwd: '<%= yeoman.app %>/styles', dest: '.tmp/styles/', src: '{,*/}*.css' } }, // Run some tasks in parallel to speed up the build process concurrent: { server: ['compass:server'], test: ['compass'], dist: ['compass:dist', // 'imagemin', 'svgmin' ] }, // By default, your `index.html`'s <!-- Usemin block --> will take care of // minification. These next options are pre-configured if you do not wish // to use the Usemin blocks. // cssmin:{ // dist:{ // files:{ // '<%= yeoman.dist %>/styles/main.css':[ // '.tmp/styles/{,*/}*.css', // '<%= yeoman.app %>/styles/{,*/}*.css' // ] // } // } // }, // uglify:{ // dist:{ // files:{ // '<%= yeoman.dist %>/scripts/scripts.js':[ // '<%= yeoman.dist %>/scripts/scripts.js' // ] // } // } // }, // concat:{ // dist:{} // }, // Test settings karma: { unit: { configFile: 'karma.conf.js', singleRun: true }, e2e: { configFile: 'karma-e2e.conf.js', singleRun: true }, jenkins: { configFile: 'karma.conf.js', singleRun: true, runnerPort: 9999, browsers: ['PhantomJS'] } }, protractor: { // Options :shared configuration with other target options: { configFile: 'protractor.conf.js', // Default config file keepAlive: false, // If false, the grunt process stops when the test // fails. noColor: false, // If true, protractor will not use colors in its // output. singleRun: false, args: { // Arguments passed to the command } }, runAdmin: { options: { args: { browser: grunt.option('browser'), baseUrl: 'http://localhost:8088', specs: [ 'test/e2e/setup-scenario/before-all.js', 'test/e2e/scenarios/admin/**/*.js' ] } } }, runApplication: { options: { args: { browser: grunt.option('browser'), baseUrl: 'http://localhost:8088', specs: [ 'test/e2e/setup-scenario/before-all.js', 'test/e2e/scenarios/application/**/*.js' ] } } }, runApplicationTopology: { options: { args: { browser: grunt.option('browser'), baseUrl: 'http://localhost:8088', specs: [ 'test/e2e/setup-scenario/before-all.js', 'test/e2e/scenarios/application_topology/**/*.js' ] } } }, runDeploymentAndSecurity: { options: { args: { browser: grunt.option('browser'), baseUrl: 'http://localhost:8088', specs: [ 'test/e2e/setup-scenario/before-all.js', 'test/e2e/scenarios/deployment/**/*.js', 'test/e2e/scenarios/security/**/*.js' ] } } }, runOtherTests: { options: { args: { browser: grunt.option('browser'), baseUrl: 'http://localhost:8088', specs: [ 'test/e2e/setup-scenario/before-all.js', 'test/e2e/scenarios/*.js' ] } } }, runFirefox: { options: { args: { browser: 'firefox' } } }, runIexplore: { options: { args: { browser: 'iexplore' } } }, runLocalserver: { options: { args: { capabilities: { 'browserName': 'firefox' }, // baseUrl: 'http://localhost:9999', baseUrl: 'http://localhost:8088', specs: [ // 'test/e2e/setup-scenario/before-all.js', // 'test/e2e/scenarios/admin/admin_cloud.js', 'test/e2e/scenarios/admin/admin_cloud_image.js', // 'test/e2e/scenarios/admin/admin_groups_management.js', // 'test/e2e/scenarios/admin/admin_metaprops_configuration.js', // 'test/e2e/scenarios/admin/admin_users_management.js', // 'test/e2e/scenarios/application/application.js', // 'test/e2e/scenarios/application/application_metaprops.js', // 'test/e2e/scenarios/application/application_environments.js', // 'test/e2e/scenarios/application/application_versions.js', // 'test/e2e/scenarios/application/application_security.js', // 'test/e2e/scenarios/application/application_security_role_check.js', // 'test/e2e/scenarios/application/application_tags.js', // 'test/e2e/scenarios/application_topology/application_topology_editor_editrelationshipname.js', // 'test/e2e/scenarios/application_topology/application_topology_editor_editrequiredprops.js', // 'test/e2e/scenarios/application_topology/application_topology_editor_input_output.js', // 'test/e2e/scenarios/application_topology/application_topology_editor_multiplenodeversions.js', // 'test/e2e/scenarios/application_topology/application_topology_editor_nodetemplate.js', // 'test/e2e/scenarios/application_topology/application_topology_editor_plan.js', // 'test/e2e/scenarios/application_topology/application_topology_editor_relationships.js', // 'test/e2e/scenarios/application_topology/application_topology_editor_replacenode.js', // 'test/e2e/scenarios/application_topology/application_topology_runtime.js', // 'test/e2e/scenarios/deployment/deployment.js', // 'test/e2e/scenarios/deployment/deployment_matcher.js', // 'test/e2e/scenarios/deployment/deployment_manual_match_resources.js', // 'test/e2e/scenarios/security/security_cloud.js', // 'test/e2e/scenarios/security/security_groups.js', // 'test/e2e/scenarios/security/security_users.js', // 'test/e2e/scenarios/authentication.js', // 'test/e2e/scenarios/component_details.js', // 'test/e2e/scenarios/component_details_tags.js', // 'test/e2e/scenarios/csar.js', // 'test/e2e/scenarios/homepage.js', // 'test/e2e/scenarios/language_test.js', // 'test/e2e/scenarios/plugins.js', // 'test/e2e/scenarios/quick_search.js', // 'test/e2e/scenarios/topology_template.js', // 'test/e2e/scenarios/*' ] } } } }, protractor_webdriver: { start: { options: { // default webdriver packaged with protractor // `webdriver-manager update` done by the calm-yeoman-maven-plugin path: 'node_modules/.bin/', command: 'webdriver-manager start' } } } }); grunt.registerTask('serve', function(target) { if (target === 'dist') { return grunt.task.run(['build', 'connect:dist:keepalive']); } grunt.task.run(['clean:server', 'bower-install', 'concurrent:server', 'autoprefixer', 'configureProxies:server', 'connect:livereload', 'watch']); }); grunt.registerTask('server', function() { grunt.log.warn('The` server` task has been deprecated.Use` grunt serve` to start a server.'); grunt.task.run(['serve']); }); grunt.registerTask('test', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'karma:unit']); grunt.registerTask('chrome-ittest', '', function() { var tasks = ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', 'protractor:runChrome' ]; grunt.option('force', true); grunt.task.run(tasks); }); // grunt.registerTask('chrome-ittest', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', // 'protractor:runChrome' // ]); grunt.registerTask('firefox-ittest', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', 'protractor:runFirefox' ]); grunt.registerTask('iexplore-ittest', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', 'protractor:runIexplore' ]); grunt.registerTask('local-ittest', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', 'protractor:runLocalserver' ]); grunt.registerTask('ittest-admin', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', 'protractor:runAdmin' ]); grunt.registerTask('ittest-application', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', 'protractor:runApplication' ]); grunt.registerTask('ittest-applicationTopology', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', 'protractor:runApplicationTopology' ]); grunt.registerTask('ittest-deploymentAndSecurity', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', 'protractor:runDeploymentAndSecurity' ]); grunt.registerTask('ittest-otherTests', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', 'protractor:runOtherTests' ]); grunt.registerTask('continuoustest', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'karma:jenkins']); grunt.registerTask('build', ['clean:dist', 'bower-install', 'useminPrepare', 'concurrent:dist', 'autoprefixer', 'concat', 'ngAnnotate', 'copy:dist', 'cdnify', 'cssmin', 'uglify', 'rev', 'usemin', 'htmlmin' ]); grunt.registerTask('default', ['newer:jshint', 'test', 'build']); };
alien4cloud-ui/yo/Gruntfile.js
// Generated on 2014-01-13 using generator-angular 0.7.1 'use strict'; // # Globbing // for performance reasons we're only matching one level down: // 'test/spec/{,*/}*.js' // use this if you want to recursively match all subfolders: // 'test/spec/**/*.js' module.exports = function(grunt) { // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // Load grunt-connect-proxy module grunt.loadNpmTasks('grunt-connect-proxy'); // Load grunt-protractor module grunt.loadNpmTasks('grunt-protractor-runner'); // Load protractor packaged selenium server grunt.loadNpmTasks('grunt-protractor_webdriver'); // load grunt-ng-annotate module grunt.loadNpmTasks('grunt-ng-annotate'); // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); // Define the configuration for all the tasks grunt.initConfig({ // Project settings yeoman: { // configurable paths app: require('./bower.json').appPath || 'app', dist: 'dist' }, // Watches files for changes and runs tasks based on the changed files watch: { js: { files: ['<%= yeoman.app %>/scripts/**/*.js'], tasks: ['newer:jshint:all'], options: { livereload: true } }, jsTest: { files: ['test/spec/{,*/}*.js'], tasks: ['newer:jshint:test', 'karma'] }, compass: { files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'], tasks: ['compass:server', 'autoprefixer'] }, gruntfile: { files: ['Gruntfile.js'] }, livereload: { options: { livereload: '<%= connect.options.livereload %>' }, files: ['<%= yeoman.app %>/bower_components/**/*.js', '<%= yeoman.app %>/views/**/*.html', '.tmp/styles/{,*/}*.css', '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'] } }, // The actual grunt server settings connect: { options: { port: 9999, // Change this to'0.0.0.0' to access the server from outside. hostname: 'localhost', livereload: 35729 }, proxies: [ /* * proxy all /rest* request to tomcat domain with specific spring security * requests */ { context: ['/rest', '/api-docs', '/login', '/logout', '/img', '/csarrepository', '/version.json'], host: 'localhost', port: 8088 } ], livereload: { options: { open: true, base: ['.tmp', '<%= yeoman.app %>'], middleware: function(connect, options) { if (!Array.isArray(options.base)) { options.base = [options.base]; } // Setup the proxy var middlewares = [require('grunt-connect-proxy/lib/utils').proxyRequest]; // Serve static files. options.base.forEach(function(base) { middlewares.push(connect.static(base)); }); // Make directory browse-able. var directory = options.directory || options.base[options.base.length - 1]; middlewares.push(connect.directory(directory)); return middlewares; } } }, test: { options: { port: 9998, base: ['.tmp', 'test', '<%= yeoman.app %>'] } }, dist: { options: { base: '<%= yeoman.dist %>' } } }, // Make sure code styles are up to par and there are no obvious mistakes jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish'), force: true }, all: ['Gruntfile.js', '<%= yeoman.app %>/scripts/{,*/}*.js'], test: { options: { jshintrc: 'test/.jshintrc' }, src: ['test/spec/{,*/}*.js'] } }, // Empties folders to start fresh clean: { dist: { files: [{ dot: true, src: ['.tmp', '<%= yeoman.dist %>/*', '!<%= yeoman.dist %>/.git*'] }] }, server: '.tmp' }, // Add vendor prefixed styles autoprefixer: { options: { browsers: ['last 1 version'] }, dist: { files: [{ expand: true, cwd: '.tmp/styles/', src: '{,*/}*.css', dest: '.tmp/styles/' }] } }, // Automatically inject Bower components into the app 'bower-install': { app: { html: '<%= yeoman.app %>/index.html', ignorePath: '<%= yeoman.app %>/' } }, // Compiles Sass to CSS and generates necessary files if requested compass: { options: { sassDir: '<%= yeoman.app %>/styles', cssDir: '.tmp/styles', generatedImagesDir: '.tmp/images/generated', imagesDir: '<%= yeoman.app %>/images', javascriptsDir: '<%= yeoman.app %>/scripts', fontsDir: '<%= yeoman.app %>/styles/fonts', importPath: '<%= yeoman.app %>/bower_components', httpImagesPath: '/images', httpGeneratedImagesPath: '/images/generated', httpFontsPath: '/styles/fonts', relativeAssets: false, assetCacheBuster: false, raw: 'Sass::Script::Number.precision = 10\n' }, dist: { options: { generatedImagesDir: '<%= yeoman.dist %>/images/generated' } }, server: { options: { debugInfo: true } } }, // Renames files for browser caching purposes rev: { dist: { files: { src: ['<%= yeoman.dist %>/scripts/{,*/}*.js', '<%= yeoman.dist %>/styles/{,*/}*.css', // '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}', '<%= yeoman.dist %>/styles/fonts/*' ] } } }, // Reads HTML for usemin blocks to enable smart builds that automatically // concat, minify and revision files. Creates configurations in memory so // additional tasks can operate on them useminPrepare: { html: '<%= yeoman.app %>/index.html', options: { dest: '<%= yeoman.dist %>' } }, // Performs rewrites based on rev and the useminPrepare configuration usemin: { html: ['<%= yeoman.dist %>/{,*/}*.html'], css: ['<%= yeoman.dist %>/styles/{,*/}*.css'], options: { assetsDirs: ['<%= yeoman.dist %>'] } }, // The following *-min tasks produce minified files in the dist folder imagemin: { dist: { files: [{ expand: true, cwd: '<%= yeoman.app %>/images', src: '{,*/}*.{png,jpg,jpeg,gif}', dest: '<%= yeoman.dist %>/images' }] } }, svgmin: { dist: { files: [{ expand: true, cwd: '<%= yeoman.app %>/images', src: '{,*/}*.svg', dest: '<%= yeoman.dist %>/images' }] } }, htmlmin: { dist: { options: { collapseWhitespace: true, collapseBooleanAttributes: false, removeCommentsFromCDATA: true, removeOptionalTags: false }, files: [{ expand: true, cwd: '<%= yeoman.dist %>', // src: ['*.html', 'views/{,*/}*.html'], src: ['*.html', 'views/**/*.html'], dest: '<%= yeoman.dist %>' }] } }, // Allow the use of non-minsafe AngularJS files. Automatically makes it // minsafe compatible so Uglify does not destroy the ng references ngAnnotate: { dist: { files: [{ expand: true, cwd: '.tmp/concat/scripts', src: '*.js', dest: '.tmp/concat/scripts' }] } }, // Replace Google CDN references cdnify: { dist: { html: ['<%= yeoman.dist %>/*.html'] } }, // Copies remaining files to places other tasks can use copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%= yeoman.app %>', dest: '<%= yeoman.dist %>', src: ['*.{ico,png,txt}', '.htaccess', '*.html', // 'views/{,*/}*.html', 'views/**/*.html', 'bower_components/**/*', 'js-lib/**/*', 'images/**/*', 'data/**/*', 'api-doc/**/*', 'version.json', // 'images/{,*/}*.{webp}', // 'images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}', 'fonts/*' ] }, { expand: true, cwd: '.tmp/images', dest: '<%= yeoman.dist %>/images', src: ['generated/*'] }, { expand: true, flatten: true, cwd: '<%= yeoman.app %>', dest: '<%= yeoman.dist %>/images', src: ['bower_components/angular-tree-control/images/*'] }] }, styles: { expand: true, cwd: '<%= yeoman.app %>/styles', dest: '.tmp/styles/', src: '{,*/}*.css' } }, // Run some tasks in parallel to speed up the build process concurrent: { server: ['compass:server'], test: ['compass'], dist: ['compass:dist', // 'imagemin', 'svgmin' ] }, // By default, your `index.html`'s <!-- Usemin block --> will take care of // minification. These next options are pre-configured if you do not wish // to use the Usemin blocks. // cssmin:{ // dist:{ // files:{ // '<%= yeoman.dist %>/styles/main.css':[ // '.tmp/styles/{,*/}*.css', // '<%= yeoman.app %>/styles/{,*/}*.css' // ] // } // } // }, // uglify:{ // dist:{ // files:{ // '<%= yeoman.dist %>/scripts/scripts.js':[ // '<%= yeoman.dist %>/scripts/scripts.js' // ] // } // } // }, // concat:{ // dist:{} // }, // Test settings karma: { unit: { configFile: 'karma.conf.js', singleRun: true }, e2e: { configFile: 'karma-e2e.conf.js', singleRun: true }, jenkins: { configFile: 'karma.conf.js', singleRun: true, runnerPort: 9999, browsers: ['PhantomJS'] } }, protractor: { // Options :shared configuration with other target options: { configFile: 'protractor.conf.js', // Default config file keepAlive: false, // If false, the grunt process stops when the test // fails. noColor: false, // If true, protractor will not use colors in its // output. singleRun: false, args: { // Arguments passed to the command } }, runChromeAdmin: { options: { args: { browser: 'chrome', baseUrl: 'http://localhost:8088', specs: [ 'test/e2e/setup-scenario/before-all.js', 'test/e2e/scenarios/admin/**/*.js' ] } } }, runChromeApplication: { options: { args: { browser: 'chrome', baseUrl: 'http://localhost:8088', specs: [ 'test/e2e/setup-scenario/before-all.js', 'test/e2e/scenarios/application/**/*.js' ] } } }, runChromeApplicationTopology: { options: { args: { browser: 'chrome', baseUrl: 'http://localhost:8088', specs: [ 'test/e2e/setup-scenario/before-all.js', 'test/e2e/scenarios/application_topology/**/*.js' ] } } }, runChromeDeploymentAndSecurity: { options: { args: { browser: 'chrome', baseUrl: 'http://localhost:8088', specs: [ 'test/e2e/setup-scenario/before-all.js', 'test/e2e/scenarios/deployment/**/*.js', 'test/e2e/scenarios/security/**/*.js' ] } } }, runChromeOtherTests: { options: { args: { browser: 'chrome', baseUrl: 'http://localhost:8088', specs: [ 'test/e2e/setup-scenario/before-all.js', 'test/e2e/scenarios/*.js' ] } } }, runFirefox: { options: { args: { browser: 'firefox' } } }, runIexplore: { options: { args: { browser: 'iexplore' } } }, runLocalserver: { options: { args: { capabilities: { 'browserName': 'firefox' }, // baseUrl: 'http://localhost:9999', baseUrl: 'http://localhost:8088', specs: [ // 'test/e2e/setup-scenario/before-all.js', // 'test/e2e/scenarios/admin_cloud.js', 'test/e2e/scenarios/admin_cloud_image.js', // 'test/e2e/scenarios/admin_groups_management.js', // 'test/e2e/scenarios/admin_metaprops_configuration.js', // 'test/e2e/scenarios/admin_users_management.js', // 'test/e2e/scenarios/application.js', // 'test/e2e/scenarios/application_metaprops.js', // 'test/e2e/scenarios/application_environments.js', // 'test/e2e/scenarios/application_versions.js', // 'test/e2e/scenarios/application_security.js', // 'test/e2e/scenarios/application_security_role_check.js', // 'test/e2e/scenarios/application_tags.js', // 'test/e2e/scenarios/application_topology_editor_editrelationshipname.js', // 'test/e2e/scenarios/application_topology_editor_editrequiredprops.js', // 'test/e2e/scenarios/application_topology_editor_input_output.js', // 'test/e2e/scenarios/application_topology_editor_multiplenodeversions.js', // 'test/e2e/scenarios/application_topology_editor_nodetemplate.js', // 'test/e2e/scenarios/application_topology_editor_plan.js', // 'test/e2e/scenarios/application_topology_editor_relationships.js', // 'test/e2e/scenarios/application_topology_editor_replacenode.js', // 'test/e2e/scenarios/application_topology_runtime.js', // 'test/e2e/scenarios/authentication.js', // 'test/e2e/scenarios/component_details.js', // 'test/e2e/scenarios/component_details_tags.js', // 'test/e2e/scenarios/csar.js', // 'test/e2e/scenarios/deployment.js', // 'test/e2e/scenarios/deployment_matcher.js', // 'test/e2e/scenarios/deployment_manual_match_resources.js', // 'test/e2e/scenarios/homepage.js', // 'test/e2e/scenarios/language_test.js', // 'test/e2e/scenarios/plugins.js', // 'test/e2e/scenarios/quick_search.js', // 'test/e2e/scenarios/security_cloud.js', // 'test/e2e/scenarios/security_groups.js', // 'test/e2e/scenarios/security_users.js', // 'test/e2e/scenarios/topology_template.js', // 'test/e2e/scenarios/*' ] } } } }, protractor_webdriver: { start: { options: { // default webdriver packaged with protractor // `webdriver-manager update` done by the calm-yeoman-maven-plugin path: 'node_modules/.bin/', command: 'webdriver-manager start' } } } }); grunt.registerTask('serve', function(target) { if (target === 'dist') { return grunt.task.run(['build', 'connect:dist:keepalive']); } grunt.task.run(['clean:server', 'bower-install', 'concurrent:server', 'autoprefixer', 'configureProxies:server', 'connect:livereload', 'watch']); }); grunt.registerTask('server', function() { grunt.log.warn('The` server` task has been deprecated.Use` grunt serve` to start a server.'); grunt.task.run(['serve']); }); grunt.registerTask('test', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'karma:unit']); grunt.registerTask('chrome-ittest', '', function() { var tasks = ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', 'protractor:runChrome' ]; grunt.option('force', true); grunt.task.run(tasks); }); // grunt.registerTask('chrome-ittest', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', // 'protractor:runChrome' // ]); grunt.registerTask('firefox-ittest', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', 'protractor:runFirefox' ]); grunt.registerTask('iexplore-ittest', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', 'protractor:runIexplore' ]); grunt.registerTask('local-ittest', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', 'protractor:runLocalserver' ]); grunt.registerTask('chrome-admin', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', 'protractor:runChromeAdmin' ]); grunt.registerTask('chrome-application', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', 'protractor:runChromeApplication' ]); grunt.registerTask('chrome-applicationTopology', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', 'protractor:runChromeApplicationTopology' ]); grunt.registerTask('chrome-deploymentAndSecurity', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', 'protractor:runChromeDeploymentAndSecurity' ]); grunt.registerTask('chrome-otherTests', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', 'protractor:runChromeOtherTests' ]); grunt.registerTask('continuoustest', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'karma:jenkins']); grunt.registerTask('build', ['clean:dist', 'bower-install', 'useminPrepare', 'concurrent:dist', 'autoprefixer', 'concat', 'ngAnnotate', 'copy:dist', 'cdnify', 'cssmin', 'uglify', 'rev', 'usemin', 'htmlmin' ]); grunt.registerTask('default', ['newer:jshint', 'test', 'build']); };
ALIEN-618: Use parameter into Gruntfile
alien4cloud-ui/yo/Gruntfile.js
ALIEN-618: Use parameter into Gruntfile
<ide><path>lien4cloud-ui/yo/Gruntfile.js <ide> // Arguments passed to the command <ide> } <ide> }, <del> runChromeAdmin: { <del> options: { <del> args: { <del> browser: 'chrome', <add> runAdmin: { <add> options: { <add> args: { <add> browser: grunt.option('browser'), <ide> baseUrl: 'http://localhost:8088', <ide> specs: [ <ide> 'test/e2e/setup-scenario/before-all.js', <ide> } <ide> } <ide> }, <del> runChromeApplication: { <del> options: { <del> args: { <del> browser: 'chrome', <add> runApplication: { <add> options: { <add> args: { <add> browser: grunt.option('browser'), <ide> baseUrl: 'http://localhost:8088', <ide> specs: [ <ide> 'test/e2e/setup-scenario/before-all.js', <ide> } <ide> } <ide> }, <del> runChromeApplicationTopology: { <del> options: { <del> args: { <del> browser: 'chrome', <add> runApplicationTopology: { <add> options: { <add> args: { <add> browser: grunt.option('browser'), <ide> baseUrl: 'http://localhost:8088', <ide> specs: [ <ide> 'test/e2e/setup-scenario/before-all.js', <ide> } <ide> } <ide> }, <del> runChromeDeploymentAndSecurity: { <del> options: { <del> args: { <del> browser: 'chrome', <add> runDeploymentAndSecurity: { <add> options: { <add> args: { <add> browser: grunt.option('browser'), <ide> baseUrl: 'http://localhost:8088', <ide> specs: [ <ide> 'test/e2e/setup-scenario/before-all.js', <ide> } <ide> } <ide> }, <del> runChromeOtherTests: { <del> options: { <del> args: { <del> browser: 'chrome', <add> runOtherTests: { <add> options: { <add> args: { <add> browser: grunt.option('browser'), <ide> baseUrl: 'http://localhost:8088', <ide> specs: [ <ide> 'test/e2e/setup-scenario/before-all.js', <ide> baseUrl: 'http://localhost:8088', <ide> specs: [ <ide> // 'test/e2e/setup-scenario/before-all.js', <del> // 'test/e2e/scenarios/admin_cloud.js', <del> 'test/e2e/scenarios/admin_cloud_image.js', <del> // 'test/e2e/scenarios/admin_groups_management.js', <del> // 'test/e2e/scenarios/admin_metaprops_configuration.js', <del> // 'test/e2e/scenarios/admin_users_management.js', <del> // 'test/e2e/scenarios/application.js', <del> // 'test/e2e/scenarios/application_metaprops.js', <del> // 'test/e2e/scenarios/application_environments.js', <del> // 'test/e2e/scenarios/application_versions.js', <del> // 'test/e2e/scenarios/application_security.js', <del> // 'test/e2e/scenarios/application_security_role_check.js', <del> // 'test/e2e/scenarios/application_tags.js', <del> // 'test/e2e/scenarios/application_topology_editor_editrelationshipname.js', <del> // 'test/e2e/scenarios/application_topology_editor_editrequiredprops.js', <del> // 'test/e2e/scenarios/application_topology_editor_input_output.js', <del> // 'test/e2e/scenarios/application_topology_editor_multiplenodeversions.js', <del> // 'test/e2e/scenarios/application_topology_editor_nodetemplate.js', <del> // 'test/e2e/scenarios/application_topology_editor_plan.js', <del> // 'test/e2e/scenarios/application_topology_editor_relationships.js', <del> // 'test/e2e/scenarios/application_topology_editor_replacenode.js', <del> // 'test/e2e/scenarios/application_topology_runtime.js', <add> // 'test/e2e/scenarios/admin/admin_cloud.js', <add> 'test/e2e/scenarios/admin/admin_cloud_image.js', <add> // 'test/e2e/scenarios/admin/admin_groups_management.js', <add> // 'test/e2e/scenarios/admin/admin_metaprops_configuration.js', <add> // 'test/e2e/scenarios/admin/admin_users_management.js', <add> // 'test/e2e/scenarios/application/application.js', <add> // 'test/e2e/scenarios/application/application_metaprops.js', <add> // 'test/e2e/scenarios/application/application_environments.js', <add> // 'test/e2e/scenarios/application/application_versions.js', <add> // 'test/e2e/scenarios/application/application_security.js', <add> // 'test/e2e/scenarios/application/application_security_role_check.js', <add> // 'test/e2e/scenarios/application/application_tags.js', <add> // 'test/e2e/scenarios/application_topology/application_topology_editor_editrelationshipname.js', <add> // 'test/e2e/scenarios/application_topology/application_topology_editor_editrequiredprops.js', <add> // 'test/e2e/scenarios/application_topology/application_topology_editor_input_output.js', <add> // 'test/e2e/scenarios/application_topology/application_topology_editor_multiplenodeversions.js', <add> // 'test/e2e/scenarios/application_topology/application_topology_editor_nodetemplate.js', <add> // 'test/e2e/scenarios/application_topology/application_topology_editor_plan.js', <add> // 'test/e2e/scenarios/application_topology/application_topology_editor_relationships.js', <add> // 'test/e2e/scenarios/application_topology/application_topology_editor_replacenode.js', <add> // 'test/e2e/scenarios/application_topology/application_topology_runtime.js', <add> // 'test/e2e/scenarios/deployment/deployment.js', <add> // 'test/e2e/scenarios/deployment/deployment_matcher.js', <add> // 'test/e2e/scenarios/deployment/deployment_manual_match_resources.js', <add> // 'test/e2e/scenarios/security/security_cloud.js', <add> // 'test/e2e/scenarios/security/security_groups.js', <add> // 'test/e2e/scenarios/security/security_users.js', <ide> // 'test/e2e/scenarios/authentication.js', <ide> // 'test/e2e/scenarios/component_details.js', <ide> // 'test/e2e/scenarios/component_details_tags.js', <ide> // 'test/e2e/scenarios/csar.js', <del> // 'test/e2e/scenarios/deployment.js', <del> // 'test/e2e/scenarios/deployment_matcher.js', <del> // 'test/e2e/scenarios/deployment_manual_match_resources.js', <ide> // 'test/e2e/scenarios/homepage.js', <ide> // 'test/e2e/scenarios/language_test.js', <ide> // 'test/e2e/scenarios/plugins.js', <ide> // 'test/e2e/scenarios/quick_search.js', <del> // 'test/e2e/scenarios/security_cloud.js', <del> // 'test/e2e/scenarios/security_groups.js', <del> // 'test/e2e/scenarios/security_users.js', <ide> // 'test/e2e/scenarios/topology_template.js', <ide> // 'test/e2e/scenarios/*' <ide> ] <ide> 'protractor:runLocalserver' <ide> ]); <ide> <del> grunt.registerTask('chrome-admin', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', <del> 'protractor:runChromeAdmin' <del> ]); <del> <del> grunt.registerTask('chrome-application', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', <del> 'protractor:runChromeApplication' <del> ]); <del> <del> grunt.registerTask('chrome-applicationTopology', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', <del> 'protractor:runChromeApplicationTopology' <del> ]); <del> <del> grunt.registerTask('chrome-deploymentAndSecurity', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', <del> 'protractor:runChromeDeploymentAndSecurity' <del> ]); <del> <del> grunt.registerTask('chrome-otherTests', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', <del> 'protractor:runChromeOtherTests' <add> grunt.registerTask('ittest-admin', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', <add> 'protractor:runAdmin' <add> ]); <add> <add> grunt.registerTask('ittest-application', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', <add> 'protractor:runApplication' <add> ]); <add> <add> grunt.registerTask('ittest-applicationTopology', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', <add> 'protractor:runApplicationTopology' <add> ]); <add> <add> grunt.registerTask('ittest-deploymentAndSecurity', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', <add> 'protractor:runDeploymentAndSecurity' <add> ]); <add> <add> grunt.registerTask('ittest-otherTests', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'protractor_webdriver:start', <add> 'protractor:runOtherTests' <ide> ]); <ide> <ide> grunt.registerTask('continuoustest', ['clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'karma:jenkins']);
Java
lgpl-2.1
c5e7e889e992d66039a361186a9b9066428b8e58
0
viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.ine.telluride.jaer.cuda; import ch.unizh.ini.jaer.chip.retina.DVS128; import ch.unizh.ini.jaer.chip.retina.Tmpdiff128; import java.awt.HeadlessException; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.net.UnknownHostException; import javax.swing.JOptionPane; import net.sf.jaer.aemonitor.AEPacketRaw; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.EventPacket; import net.sf.jaer.event.PolarityEvent; import net.sf.jaer.eventio.AEUnicastInput; import net.sf.jaer.eventprocessing.EventFilter2D; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; import net.sf.jaer.chip.EventExtractor2D; import net.sf.jaer.event.TypedEvent; import net.sf.jaer.eventio.AEUnicastOutput; import net.sf.jaer.eventprocessing.FilterChain; import net.sf.jaer.eventprocessing.filter.RefractoryFilter; import net.sf.jaer.graphics.AEViewer; /** * Allows control of remote CUDA process for filtering jAER data. *<p> * This filter does not process events at all. Rather it opens a TCP stream socket connection to a remote (maybe on the same machine) * process which is a CUDA GPGPU program which accepts AEs from jAER and which sends its output back to jAER for visualization. * <p> * The stream socket works with text command lines as though it were a terminal. * * * @author tobi/yingxue/jay */ public class CUDAObjectTrackerControl extends EventFilter2D { AEViewer outputViewer = null; private int controlPort = getPrefs().getInt("CUDAObjectTrackerControl.controlPort", 9998); private int recvOnPort = getPrefs().getInt("CUDAObjectTrackerControl.inputPort", 9999); private int sendToPort = getPrefs().getInt("CUDAObjectTrackerControl.outputPort", 10000); private String hostname = getPrefs().get("CUDAObjectTrackerControl.hostname", "localhost"); private String cudaExecutablePath = getPrefs().get("CUDAObjectTrackerControl.cudaExecutablePath", null); private String cudaEnvironmentPath = getPrefs().get("CUDAObjectTrackerControl.cudaEnvironmentPath", null); private DatagramSocket controlSocket = null; InetAddress cudaInetAddress = null; private boolean cudaEnabled = getPrefs().getBoolean("CUDAObjectTrackerControl.cudaEnabled", true); Process cudaProcess = null; ProcessBuilder cudaProcessBuilder = null; AEUnicastOutput unicastOutput; AEUnicastInput unicastInput; /* * // from config.h in CUDA code #define MEMBRANE_TAU 10000.0F // membrane time constant #define MEMBRANE_THRESHOLD 100.0F // membrane threshold #define MEMBRANE_POTENTIAL_MIN -50.0F // membrane equilibrium potential #define MIN_FIRING_TIME_DIFF 15000 // low pass filter the events from retina #define E_I_NEURON_POTENTIAL 10.0 // excitatory to inhibitory synaptic weight #define I_E_NEURON_POTENTIAL 10.0 // inhibitory to excitatory synaptic weight */ // TODO these cuda parameters better handled by indexed properties, but indexed properties not handled in FilterPanel yet static final String CMD_THRESHOLD = "threshold"; private float threshold = getPrefs().getFloat("CUDAObjectTrackerControl.threshold", 100); static final String CMD_MEMBRANE_TAU = "membraneTau"; private float membraneTauUs = getPrefs().getFloat("CUDAObjectTrackerControl.membraneTauUs", 10000); static final String CMD_MEMBRANE_POTENTIAL_MIN = "membranePotentialMin"; private float membranePotentialMin = getPrefs().getFloat("CUDAObjectTrackerControl.membranePotentialMin", -50); static final String CMD_MIN_FIRING_TIME_DIFF = "minFiringTimeDiff"; private float minFiringTimeDiff = getPrefs().getFloat("CUDAObjectTrackerControl.minFiringTimeDiff", 15000); static final String CMD_E_I_NEURON_POTENTIAL = "eISynWeight"; private float eISynWeight = getPrefs().getFloat("CUDAObjectTrackerControl.eISynWeight", 10); static final String CMD_I_E_NEURON_POTENTIAL = "iESynWeight"; private float iESynWeight = getPrefs().getFloat("CUDAObjectTrackerControl.iESynWeight", 10); static final String CMD_EXIT = "exit"; private final String CMD_DEBUG_LEVEL = "debugLevel"; private int debugLevel = getPrefs().getInt("CUDAObjectTrackerControl.debugLevel", 1); private final String CMD_MAX_XMIT_INTERVAL_MS = "maxXmitIntervalMs"; private int maxXmitIntervalMs = getPrefs().getInt("CUDAObjectTrackerControl.maxXmitIntervalMs", 20); static final String CMD_CUDA_ENABLED = "cudaEnabled"; // static final String CMD_TERMINATE_IMMEDIATELY="terminate"; static final String CMD_KERNEL_SHAPE = "kernelShape"; static final String CMD_SPIKE_PARTITIONING_METHOD = "spikePartitioningMethod"; private String CMD_CUDAS_RECVON_PORT = "inputPort"; // swapped here because these are CUDAs private String CMD_CUDAS_SENDTO_PORT = "outputPort"; public enum KernelShape { DoG, Circle }; public enum SpikePartitioningMethod { SingleSpike, MultipleSpike }; private KernelShape kernelShape = KernelShape.valueOf(getPrefs().get("CUDAObjectTrackerControl.kernelShape", KernelShape.DoG.toString())); private SpikePartitioningMethod spikePartitioningMethod = SpikePartitioningMethod.valueOf(getPrefs().get("CUDAObjectTrackerControl.spikePartitioningMethod", SpikePartitioningMethod.MultipleSpike.toString())); public CUDAObjectTrackerControl(AEChip chip) { super(chip); setPropertyTooltip("hostname", "hostname or IP address of CUDA process"); setPropertyTooltip("controlPort", "port number of CUDA process UDP control port (we control CUDA over this)"); setPropertyTooltip("inputPort", "UDP port number we receive events on from CUDA (CUDA's outputPort)"); setPropertyTooltip("outputPort", "UDP port number we send events to (CUDA's inputPort)"); setPropertyTooltip("cudaEnvironmentPath", "Windows PATH to include CUDA stuff (cutil32.dll), e.g. c:\\cuda\\bin;c:\\Program Files\\NVIDIA Corporation\\NVIDIA CUDA SDK\\bin\\win32\\Debug"); setPropertyTooltip("cudaExecutablePath", "Full path to CUDA process executable"); setPropertyTooltip("threshold", "neuron spike thresholds"); setPropertyTooltip("membraneTauUs", "neuron membrane decay time constant in us"); setPropertyTooltip("membranePotentialMin", "neuron reset potential"); setPropertyTooltip("minFiringTimeDiff", "refractory period in us for spikes from jear to cuda - spike intervals shorter to this from a cell are not processed"); setPropertyTooltip("eISynWeight", "excitatory to inhibitory weights"); setPropertyTooltip("iESynWeight", "inhibitory to excitatory weights"); setPropertyTooltip("cudaEnabled", "true to enable use of CUDA hardware - false to run on host"); setPropertyTooltip("KillCUDA", "kills CUDA process, iff started from jaer"); setPropertyTooltip("SelectCUDAExecutable", "select the CUDA executable (.exe) file"); setPropertyTooltip("LaunchCUDA", "Launches the selected CUDA executable"); setPropertyTooltip("debugLevel", "0=minimal debug, 1=debug"); setPropertyTooltip("maxXmitIntervalMs", "maximum interval in ms between sending packets from CUDA (if there are spikes to send)"); setPropertyTooltip("SendParameters", "Send all the parameters to a CUDA process we have not started from here"); if (cudaEnvironmentPath == null || cudaEnvironmentPath.isEmpty()) { // String cudaBinPath=System.getenv("CUDA_BIN_PATH"); // String cudaLibPath=System.getenv("CUDA_LIB_PATH"); // cudaEnvironmentPath = cudaBinPath+File.pathSeparator+cudaLibPath; // "c:\\cuda\\bin;c:\\Program Files\\NVIDIA Corporation\\NVIDIA CUDA SDK\\bin\\win32\\Debug"; cudaEnvironmentPath = "c:\\cuda\\bin;c:\\Program Files\\NVIDIA Corporation\\NVIDIA CUDA SDK\\bin\\win32\\Debug"; } try { cudaInetAddress = InetAddress.getByName(hostname); } catch (UnknownHostException ex) { log.warning("CUDA hostname " + hostname + " unknown? " + ex.toString()); } setEnclosedFilterChain(new FilterChain(chip)); RefractoryFilter rf = new RefractoryFilter(chip); rf.setEnclosed(true, this); getEnclosedFilterChain().add(rf); // to filter out redundant events - multiple spikes from same cell with short ISI. } public void doKillCUDA() { writeCommandToCuda(CMD_EXIT); try { Thread.sleep(200); } catch (InterruptedException e) { } ; // let cuda print results if (cudaProcess != null) { cudaProcess.destroy(); // kill it anyhow if we started it } } /** Launches the CUDA process, then sends parameters to it. When the CUDA process is * launched externally, we don't know if it's running and it will not have commands from us initially. */ public void doLaunchCUDA() { if (isCudaRunning()) { int ret = JOptionPane.showConfirmDialog(chip.getAeViewer(), "Kill existing CUDA process and start a new one?"); if (ret != JOptionPane.OK_OPTION) { return; } cudaProcess.destroy(); } cudaProcessBuilder = new ProcessBuilder(); cudaProcessBuilder.command(cudaExecutablePath); cudaProcessBuilder.environment().put("Path", cudaEnvironmentPath); cudaProcessBuilder.directory(new File(System.getProperty("user.dir"))); cudaProcessBuilder.redirectErrorStream(true); try { log.info("launching CUDA executable \"" + cudaProcessBuilder.command() + "\" with environment=\"" + cudaProcessBuilder.environment() + "\"+ in directory=" + cudaProcessBuilder.directory()); cudaProcess = cudaProcessBuilder.start(); Runtime.getRuntime().addShutdownHook(new Thread("CUDA detroyer") { @Override public void run() { log.info("destroying CUDA process"); cudaProcess.destroy(); } }); final BufferedReader outReader = new BufferedReader(new InputStreamReader(cudaProcess.getInputStream())); Thread outThread = new Thread("CUDA output") { public void run() { try { Thread.sleep(100); try { String line; do { line = outReader.readLine(); log.info("CUDA: " + line); } while (line != null); } catch (IOException ex) { log.warning(ex.toString()); } } catch (InterruptedException ex) { log.warning(ex.toString()); } } }; outThread.start(); Thread.sleep(300); sendParameters(); // set defaults to override #defines in CUDA code } catch (Exception ex) { log.warning(ex.toString()); } } private boolean checkControlSocket() { if (controlSocket == null) { try { controlSocket = new DatagramSocket(); // bind to any available port because we will send to CUDA on its port // writer = new OutputStreamWriter(controlSocket.getOutputStream()); log.info("bound to local port " + controlSocket.getLocalPort() + " for controlling CUDA"); sendParameters(); // send on construction in case CUDA is running } catch (Exception ex) { log.warning(ex.toString() + " to " + hostname + ":" + controlPort); return false; // return launchCuda(); } } return true; } synchronized private void checkIOPorts() throws IOException { checkControlSocket(); if (unicastInput == null) { unicastInput = new AEUnicastInput(); unicastInput.setPort(recvOnPort); unicastInput.set4ByteAddrTimestampEnabled(true); unicastInput.setAddressFirstEnabled(true); unicastInput.setSequenceNumberEnabled(false); // TODO, should use seq numbers on both sides unicastInput.setSwapBytesEnabled(false); unicastInput.setTimestampMultiplier(1); unicastInput.start(); } if (unicastOutput == null) { unicastOutput = new AEUnicastOutput(); unicastOutput.setHost(getHostname()); unicastOutput.setPort(sendToPort); unicastOutput.set4ByteAddrTimestampEnabled(true); unicastOutput.setAddressFirstEnabled(true); unicastOutput.setSequenceNumberEnabled(true); // TODO sequence numbers unicastOutput.setSwapBytesEnabled(false); unicastOutput.setTimestampMultiplier(1); } } // private void checkOutputViewer() throws HeadlessException { // if (outputViewer == null) { // outputViewer = new AEViewer(chip.getAeViewer().getJaerViewer()); // Class originalChipClass = outputViewer.getAeChipClass(); // outputViewer.setAeChipClass(CUDAOutputAEChip.class); // outputViewer.setVisible(true); // outputViewer.setPreferredAEChipClass(originalChipClass); // outputViewer.reopenSocketInputStream(); // } // } // thread safe for renewing sockets synchronized private void sendParameters() { log.info("sending parameters to CUDA"); sendParameter(CMD_THRESHOLD, threshold); sendParameter(CMD_I_E_NEURON_POTENTIAL, iESynWeight); sendParameter(CMD_E_I_NEURON_POTENTIAL, eISynWeight); sendParameter(CMD_MEMBRANE_POTENTIAL_MIN, membranePotentialMin); sendParameter(CMD_MEMBRANE_TAU, membraneTauUs); sendParameter(CMD_MIN_FIRING_TIME_DIFF, minFiringTimeDiff); writeCommandToCuda(CMD_DEBUG_LEVEL + " " + debugLevel); writeCommandToCuda(CMD_CUDA_ENABLED + " " + cudaEnabled); writeCommandToCuda(CMD_KERNEL_SHAPE + " " + kernelShape.toString()); writeCommandToCuda(CMD_SPIKE_PARTITIONING_METHOD + " " + spikePartitioningMethod.toString()); writeCommandToCuda(CMD_MAX_XMIT_INTERVAL_MS + " " + maxXmitIntervalMs); writeCommandToCuda(CMD_CUDAS_RECVON_PORT + " " + sendToPort); // tells CUDA "inputPort XXX" which it uses to set which port it sends to writeCommandToCuda(CMD_CUDAS_SENDTO_PORT + " " + recvOnPort); } private void sendParameter(String name, float value) { String s = String.format(name + " " + value); writeCommandToCuda(s); } private boolean isCudaRunning() { if (cudaProcess == null) { return false; } try { int exitValue = 0; if ((exitValue = cudaProcess.exitValue()) != 0) { log.warning("CUDA exit process was " + exitValue); cudaProcess = null; } return false; } catch (IllegalThreadStateException e) { return true; } } // /** does reconnect to CUDA server */ // public void doReconnect() { // if (controlSocket != null) { // controlSocket.close(); // controlSocket = null; // } // checkControlSocket(); // } public void doSelectCUDAExecutable() { if (cudaExecutablePath == null || cudaExecutablePath.isEmpty()) { cudaExecutablePath = System.getProperty("user.dir"); } JFileChooser chooser = new JFileChooser(cudaExecutablePath); chooser.setDialogTitle("Choose CUDA executable .exe file (from CUDA project win32 subfolder)"); chooser.setFileFilter(new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".exe"); } @Override public String getDescription() { return "Executables"; } }); chooser.setMultiSelectionEnabled(false); int retval = chooser.showOpenDialog(getChip().getAeViewer().getFilterFrame()); if (retval == JFileChooser.APPROVE_OPTION) { File f = chooser.getSelectedFile(); if (f != null && f.isFile()) { setCudaExecutablePath(f.toString()); log.info("selected CUDA executable " + cudaExecutablePath); } } } private void writeCommandToCuda(String s) { if (!checkControlSocket()) { return; } byte[] b = s.getBytes(); DatagramPacket packet = new DatagramPacket(b, b.length, cudaInetAddress, controlPort); try { controlSocket.send(packet); } catch (IOException ex) { log.warning(ex.toString()); } // try { // writer.write(s); // } catch (IOException ex) { // log.warning("writing string " + s + " got " + ex); // } } public void doSendParameters() { sendParameters(); } private int warningCount = 0; /** Reconstructs a raw event packet, sends it to jaercuda, reads the output from jaercuda, extracts this raw packet, and then returns the events. @param in the input packets. @return the output packet. */ @Override public EventPacket<?> filterPacket(EventPacket<?> in) { if (!isFilterEnabled()) { return in; } if (!isCudaRunning()) { if (warningCount++ % 300 == 0) { log.warning("cuda has not been started from jaer or has terminated"); } // return in; } try { checkIOPorts(); AEPacketRaw rawOutputPacket = chip.getEventExtractor().reconstructRawPacket(in); unicastOutput.writePacket(rawOutputPacket); AEPacketRaw rawInputPacket = unicastInput.readPacket(); // right here is where we can use a custom extractor to output any kind of events we like from the MSB bits of the returned addresses out = cudaExtractor.extractPacket(rawInputPacket); return out; } catch (IOException e) { log.warning(e.toString()); } return in; } /** This AEChip has an EventExtractor2D that understands the CUDA event output. * */ public class CUDAChip extends DVS128 { public CUDAChip() { setEventClass(PolarityEvent.class); // modify to elaborated event type, e.g. TypedEvent, and write extractPacket to understand it } public class CUDAExtractor extends CUDAChip.Extractor { public CUDAExtractor(DVS128 chip) { super(chip); } @Override public synchronized EventPacket extractPacket(AEPacketRaw in) { return super.extractPacket(in); } } } EventExtractor2D cudaExtractor = new CUDAChip().getEventExtractor(); @Override public synchronized void setFilterEnabled(boolean yes) { super.setFilterEnabled(yes); if (yes) { // checkOutputViewer(); } } @Override public Object getFilterState() { return null; } @Override public void resetFilter() { } @Override public void initFilter() { } public int getControlPort() { return controlPort; } public void setControlPort(int port) { support.firePropertyChange("controlPort", controlPort, port); this.controlPort = port; getPrefs().putInt("CUDAObjectTrackerControl.controlPort", controlPort); } /** * @return the inputPort */ public int getInputPort() { return recvOnPort; } /** * @param inputPort the inputPort to set */ public void setInputPort(int inputPort) { support.firePropertyChange("inputPort", this.recvOnPort, inputPort); this.recvOnPort = inputPort; getPrefs().putInt("CUDAObjectTrackerControl.inputPort", inputPort); if (unicastInput != null) { unicastInput.setPort(inputPort); } writeCommandToCuda(CMD_CUDAS_SENDTO_PORT + " " + inputPort); } /** * @return the outputPort */ public int getOutputPort() { return sendToPort; } /** * @param outputPort the outputPort to set */ public void setOutputPort(int outputPort) { support.firePropertyChange("outputPort", this.sendToPort, outputPort); this.sendToPort = outputPort; getPrefs().putInt("CUDAObjectTrackerControl.outputPort", outputPort); if (unicastOutput != null) { unicastOutput.setPort(outputPort); } writeCommandToCuda(CMD_CUDAS_RECVON_PORT + " " + outputPort); } public String getHostname() { return hostname; } public void setHostname(String hostname) { try { cudaInetAddress = InetAddress.getByName(hostname); } catch (UnknownHostException ex) { log.warning("CUDA hostname " + hostname + " unknown? " + ex.toString()); support.firePropertyChange("hostname", null, this.hostname); return; } support.firePropertyChange("hostname", this.hostname, hostname); this.hostname = hostname; getPrefs().put("CUDAObjectTrackerControl.hostname", hostname); } public float getThreshold() { return threshold; } public void setThreshold(float threshold) { support.firePropertyChange("threshold", this.threshold, threshold); this.threshold = threshold; getPrefs().putFloat("CUDAObjectTrackerControl.threshold", threshold); sendParameter(CMD_THRESHOLD, threshold); } /** * @return the cudaExecutablePath */ public String getCudaExecutablePath() { return cudaExecutablePath; } /** * @param cudaExecutablePath the cudaExecutablePath to set */ public void setCudaExecutablePath(String cudaExecutablePath) { support.firePropertyChange("cudaExecutablePath", this.cudaExecutablePath, cudaExecutablePath); this.cudaExecutablePath = cudaExecutablePath; getPrefs().put("CUDAObjectTrackerControl.cudaExecutablePath", cudaExecutablePath); } /** * @return the cudaEnvironmentPath */ public String getCudaEnvironmentPath() { return cudaEnvironmentPath; } /** * @param cudaEnvironmentPath the cudaEnvironmentPath to set */ public void setCudaEnvironmentPath(String cudaEnvironmentPath) { support.firePropertyChange("cudaEnvironmentPath", this.cudaEnvironmentPath, cudaEnvironmentPath); this.cudaEnvironmentPath = cudaEnvironmentPath; getPrefs().put("CUDAObjectTrackerControl.cudaEnvironmentPath", cudaEnvironmentPath); } /** * @return the membraneTauUs */ public float getMembraneTauUs() { return membraneTauUs; } /** * @param membraneTauUs the membraneTauUs to set */ public void setMembraneTauUs(float membraneTauUs) { support.firePropertyChange("membraneTauUs", this.membraneTauUs, membraneTauUs); this.membraneTauUs = membraneTauUs; getPrefs().putFloat("CUDAObjectTrackerControl.membraneTauUs", membraneTauUs); sendParameter(CMD_MEMBRANE_TAU, membraneTauUs); } /** * @return the membranePotentialMin */ public float getMembranePotentialMin() { return membranePotentialMin; } /** * @param membranePotentialMin the membranePotentialMin to set */ public void setMembranePotentialMin(float membranePotentialMin) { support.firePropertyChange("membranePotentialMin", this.membranePotentialMin, membranePotentialMin); this.membranePotentialMin = membranePotentialMin; getPrefs().putFloat("CUDAObjectTrackerControl.membranePotentialMin", membranePotentialMin); sendParameter(CMD_MEMBRANE_POTENTIAL_MIN, membranePotentialMin); } /** * @return the minFiringTimeDiff */ public float getMinFiringTimeDiff() { return minFiringTimeDiff; } /** * @param minFiringTimeDiff the minFiringTimeDiff to set */ public void setMinFiringTimeDiff(float minFiringTimeDiff) { support.firePropertyChange("minFiringTimeDiff", this.minFiringTimeDiff, minFiringTimeDiff); this.minFiringTimeDiff = minFiringTimeDiff; getPrefs().putFloat("CUDAObjectTrackerControl.minFiringTimeDiff", minFiringTimeDiff); sendParameter(CMD_MIN_FIRING_TIME_DIFF, minFiringTimeDiff); } /** * @return the eISynWeight */ public float geteISynWeight() { return eISynWeight; } /** * @param eISynWeight the eISynWeight to set */ public void seteISynWeight(float eISynWeight) { support.firePropertyChange("eISynWeight", this.eISynWeight, eISynWeight); this.eISynWeight = eISynWeight; getPrefs().putFloat("CUDAObjectTrackerControl.eISynWeight", eISynWeight); sendParameter(CMD_E_I_NEURON_POTENTIAL, eISynWeight); } /** * @return the iESynWeight */ public float getiESynWeight() { return iESynWeight; } /** * @param iESynWeight the iESynWeight to set */ public void setiESynWeight(float iESynWeight) { support.firePropertyChange("iESynWeight", this.iESynWeight, iESynWeight); this.iESynWeight = iESynWeight; getPrefs().putFloat("CUDAObjectTrackerControl.iESynWeight", iESynWeight); sendParameter(CMD_I_E_NEURON_POTENTIAL, iESynWeight); } /** * @return the kernelShape */ public KernelShape getKernelShape() { return kernelShape; } /** * @param kernelShape the kernelShape to set */ public void setKernelShape(KernelShape kernelShape) { support.firePropertyChange("kernelShape", this.kernelShape, kernelShape); this.kernelShape = kernelShape; getPrefs().put("CUDAObjectTrackerControl.kernelShape", kernelShape.toString()); writeCommandToCuda(CMD_KERNEL_SHAPE + " " + kernelShape.toString()); } /** * @return the spikePartitioningMethod */ public SpikePartitioningMethod getSpikePartitioningMethod() { return spikePartitioningMethod; } /** * @param spikePartitioningMethod the spikePartitioningMethod to set */ public void setSpikePartitioningMethod(SpikePartitioningMethod spikePartitioningMethod) { support.firePropertyChange("kernelShape", this.spikePartitioningMethod, spikePartitioningMethod); this.spikePartitioningMethod = spikePartitioningMethod; getPrefs().put("CUDAObjectTrackerControl.spikePartitioningMethod", spikePartitioningMethod.toString()); writeCommandToCuda(CMD_SPIKE_PARTITIONING_METHOD + " " + spikePartitioningMethod.toString()); } /** * @return the cudaEnabled */ public boolean isCudaEnabled() { return cudaEnabled; } /** * @param cudaEnabled the cudaEnabled to set */ public void setCudaEnabled(boolean cudaEnabled) { support.firePropertyChange("cudaEnabled", this.cudaEnabled, cudaEnabled); this.cudaEnabled = cudaEnabled; getPrefs().putBoolean("CUDAObjectTrackerControl.cudaEnabled", cudaEnabled); writeCommandToCuda(CMD_CUDA_ENABLED + " " + cudaEnabled); } /** * @return the debugLevel */ public int getDebugLevel() { return debugLevel; } /** * @param debugLevel the debugLevel to set */ public void setDebugLevel(int debugLevel) { support.firePropertyChange("debugLevel", this.debugLevel, debugLevel); this.debugLevel = debugLevel; getPrefs().putInt("CUDAObjectTrackerControl.debugLevel", debugLevel); writeCommandToCuda(CMD_DEBUG_LEVEL + " " + debugLevel); } /** * @return the maxXmitIntervalMs */ public int getMaxXmitIntervalMs() { return maxXmitIntervalMs; } /** * @param maxXmitIntervalMs the maxXmitIntervalMs to set */ public void setMaxXmitIntervalMs(int maxXmitIntervalMs) { support.firePropertyChange("maxXmitIntervalMs", this.maxXmitIntervalMs, maxXmitIntervalMs); this.maxXmitIntervalMs = maxXmitIntervalMs; getPrefs().putInt("CUDAObjectTrackerControl.maxXmitIntervalMs", maxXmitIntervalMs); writeCommandToCuda(CMD_MAX_XMIT_INTERVAL_MS + " " + maxXmitIntervalMs); } // TODO these classes define properties for communicating with CUDA, but i cannot see how to statically compile in the get/set // to go with them to allow introspection to find them public class CUDACommand { String cmd = null; String tooltip = null; String name; public void writeCommand() { writeCommandToCuda(cmd); } public CUDACommand(String name, String cmd, String tooltip) { this.cmd = cmd; this.tooltip = tooltip; this.name = name; setPropertyTooltip(cmd, tooltip); } } public class CUDAParameter extends CUDACommand { Object obj; public CUDAParameter(String name, String cmd, Object obj, String tooltip) { super(name, cmd, tooltip); this.obj = obj; } @Override public void writeCommand() { writeCommandToCuda(cmd + " " + obj.toString()); } public Object get() { return obj; } public void set(Object obj) { support.firePropertyChange(name, get(), obj); this.obj = obj; getPrefs().put("CUDAObjectTrackerControl." + name, obj.toString()); } } }
src/org/ine/telluride/jaer/cuda/CUDAObjectTrackerControl.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.ine.telluride.jaer.cuda; import ch.unizh.ini.jaer.chip.retina.DVS128; import ch.unizh.ini.jaer.chip.retina.Tmpdiff128; import java.awt.HeadlessException; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.net.UnknownHostException; import javax.swing.JOptionPane; import net.sf.jaer.aemonitor.AEPacketRaw; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.EventPacket; import net.sf.jaer.event.PolarityEvent; import net.sf.jaer.eventio.AEUnicastInput; import net.sf.jaer.eventprocessing.EventFilter2D; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; import net.sf.jaer.chip.EventExtractor2D; import net.sf.jaer.event.TypedEvent; import net.sf.jaer.eventio.AEUnicastOutput; import net.sf.jaer.eventprocessing.FilterChain; import net.sf.jaer.eventprocessing.filter.RefractoryFilter; import net.sf.jaer.graphics.AEViewer; /** * Allows control of remote CUDA process for filtering jAER data. *<p> * This filter does not process events at all. Rather it opens a TCP stream socket connection to a remote (maybe on the same machine) * process which is a CUDA GPGPU program which accepts AEs from jAER and which sends its output back to jAER for visualization. * <p> * The stream socket works with text command lines as though it were a terminal. * * * @author tobi/yingxue/jay */ public class CUDAObjectTrackerControl extends EventFilter2D { AEViewer outputViewer = null; private int controlPort = getPrefs().getInt("CUDAObjectTrackerControl.controlPort", 9998); private int recvOnPort = getPrefs().getInt("CUDAObjectTrackerControl.inputPort", 9999); private int sendToPort = getPrefs().getInt("CUDAObjectTrackerControl.outputPort", 10000); private String hostname = getPrefs().get("CUDAObjectTrackerControl.hostname", "localhost"); private String cudaExecutablePath = getPrefs().get("CUDAObjectTrackerControl.cudaExecutablePath", null); private String cudaEnvironmentPath = getPrefs().get("CUDAObjectTrackerControl.cudaEnvironmentPath", null); private DatagramSocket controlSocket = null; InetAddress cudaInetAddress = null; private boolean cudaEnabled = getPrefs().getBoolean("CUDAObjectTrackerControl.cudaEnabled", true); Process cudaProcess = null; ProcessBuilder cudaProcessBuilder = null; AEUnicastOutput unicastOutput; AEUnicastInput unicastInput; /* * // from config.h in CUDA code #define MEMBRANE_TAU 10000.0F // membrane time constant #define MEMBRANE_THRESHOLD 100.0F // membrane threshold #define MEMBRANE_POTENTIAL_MIN -50.0F // membrane equilibrium potential #define MIN_FIRING_TIME_DIFF 15000 // low pass filter the events from retina #define E_I_NEURON_POTENTIAL 10.0 // excitatory to inhibitory synaptic weight #define I_E_NEURON_POTENTIAL 10.0 // inhibitory to excitatory synaptic weight */ // TODO these cuda parameters better handled by indexed properties, but indexed properties not handled in FilterPanel yet static final String CMD_THRESHOLD = "threshold"; private float threshold = getPrefs().getFloat("CUDAObjectTrackerControl.threshold", 100); static final String CMD_MEMBRANE_TAU = "membraneTau"; private float membraneTauUs = getPrefs().getFloat("CUDAObjectTrackerControl.membraneTauUs", 10000); static final String CMD_MEMBRANE_POTENTIAL_MIN = "membranePotentialMin"; private float membranePotentialMin = getPrefs().getFloat("CUDAObjectTrackerControl.membranePotentialMin", -50); static final String CMD_MIN_FIRING_TIME_DIFF = "minFiringTimeDiff"; private float minFiringTimeDiff = getPrefs().getFloat("CUDAObjectTrackerControl.minFiringTimeDiff", 15000); static final String CMD_E_I_NEURON_POTENTIAL = "eISynWeight"; private float eISynWeight = getPrefs().getFloat("CUDAObjectTrackerControl.eISynWeight", 10); static final String CMD_I_E_NEURON_POTENTIAL = "iESynWeight"; private float iESynWeight = getPrefs().getFloat("CUDAObjectTrackerControl.iESynWeight", 10); static final String CMD_EXIT = "exit"; private final String CMD_DEBUG_LEVEL = "debugLevel"; private int debugLevel = getPrefs().getInt("CUDAObjectTrackerControl.debugLevel", 1); private final String CMD_MAX_XMIT_INTERVAL_MS = "maxXmitIntervalMs"; private int maxXmitIntervalMs = getPrefs().getInt("CUDAObjectTrackerControl.maxXmitIntervalMs", 20); static final String CMD_CUDA_ENABLED = "cudaEnabled"; // static final String CMD_TERMINATE_IMMEDIATELY="terminate"; static final String CMD_KERNEL_SHAPE = "kernelShape"; static final String CMD_SPIKE_PARTITIONING_METHOD = "spikePartitioningMethod"; private String CMD_CUDAS_RECVON_PORT = "inputPort"; // swapped here because these are CUDAs private String CMD_CUDAS_SENDTO_PORT = "outputPort"; public enum KernelShape { DoG, Circle }; public enum SpikePartitioningMethod { SingleSpike, MultipleSpike }; private KernelShape kernelShape = KernelShape.valueOf(getPrefs().get("CUDAObjectTrackerControl.kernelShape", KernelShape.DoG.toString())); private SpikePartitioningMethod spikePartitioningMethod = SpikePartitioningMethod.valueOf(getPrefs().get("CUDAObjectTrackerControl.spikePartitioningMethod", SpikePartitioningMethod.MultipleSpike.toString())); public CUDAObjectTrackerControl(AEChip chip) { super(chip); setPropertyTooltip("hostname", "hostname or IP address of CUDA process"); setPropertyTooltip("controlPort", "port number of CUDA process UDP control port (we control CUDA over this)"); setPropertyTooltip("inputPort", "UDP port number we receive events on from CUDA (CUDA's outputPort)"); setPropertyTooltip("outputPort", "UDP port number we send events to (CUDA's inputPort)"); setPropertyTooltip("cudaEnvironmentPath", "Windows PATH to include CUDA stuff (cutil32.dll), e.g. c:\\cuda\\bin;c:\\Program Files\\NVIDIA Corporation\\NVIDIA CUDA SDK\\bin\\win32\\Debug"); setPropertyTooltip("cudaExecutablePath", "Full path to CUDA process executable"); setPropertyTooltip("threshold", "neuron spike thresholds"); setPropertyTooltip("membraneTauUs", "neuron membrane decay time constant in us"); setPropertyTooltip("membranePotentialMin", "neuron reset potential"); setPropertyTooltip("minFiringTimeDiff", "refractory period in us for spikes from jear to cuda - spike intervals shorter to this from a cell are not processed"); setPropertyTooltip("eISynWeight", "excitatory to inhibitory weights"); setPropertyTooltip("iESynWeight", "inhibitory to excitatory weights"); setPropertyTooltip("cudaEnabled", "true to enable use of CUDA hardware - false to run on host"); setPropertyTooltip("KillCUDA", "kills CUDA process, iff started from jaer"); setPropertyTooltip("SelectCUDAExecutable", "select the CUDA executable (.exe) file"); setPropertyTooltip("LaunchCUDA", "Launches the selected CUDA executable"); setPropertyTooltip("debugLevel", "0=minimal debug, 1=debug"); setPropertyTooltip("maxXmitIntervalMs", "maximum interval in ms between sending packets from CUDA (if there are spikes to send)"); setPropertyTooltip("SendParameters", "Send all the parameters to a CUDA process we have not started from here"); if (cudaEnvironmentPath == null || cudaEnvironmentPath.isEmpty()) { // String cudaBinPath=System.getenv("CUDA_BIN_PATH"); // String cudaLibPath=System.getenv("CUDA_LIB_PATH"); // cudaEnvironmentPath = cudaBinPath+File.pathSeparator+cudaLibPath; // "c:\\cuda\\bin;c:\\Program Files\\NVIDIA Corporation\\NVIDIA CUDA SDK\\bin\\win32\\Debug"; cudaEnvironmentPath = "c:\\cuda\\bin;c:\\Program Files\\NVIDIA Corporation\\NVIDIA CUDA SDK\\bin\\win32\\Debug"; } try { cudaInetAddress = InetAddress.getByName(hostname); } catch (UnknownHostException ex) { log.warning("CUDA hostname " + hostname + " unknown? " + ex.toString()); } setEnclosedFilterChain(new FilterChain(chip)); RefractoryFilter rf = new RefractoryFilter(chip); rf.setEnclosed(true, this); getEnclosedFilterChain().add(rf); // to filter out redundant events - multiple spikes from same cell with short ISI. } public void doKillCUDA() { writeCommandToCuda(CMD_EXIT); try { Thread.sleep(200); } catch (InterruptedException e) { } ; // let cuda print results if (cudaProcess != null) { cudaProcess.destroy(); // kill it anyhow if we started it } } /** Launches the CUDA process, then sends parameters to it. When the CUDA process is * launched externally, we don't know if it's running and it will not have commands from us initially. */ public void doLaunchCUDA() { if (isCudaRunning()) { int ret = JOptionPane.showConfirmDialog(chip.getAeViewer(), "Kill existing CUDA process and start a new one?"); if (ret != JOptionPane.OK_OPTION) { return; } cudaProcess.destroy(); } cudaProcessBuilder = new ProcessBuilder(); cudaProcessBuilder.command(cudaExecutablePath); cudaProcessBuilder.environment().put("Path", cudaEnvironmentPath); cudaProcessBuilder.directory(new File(System.getProperty("user.dir"))); cudaProcessBuilder.redirectErrorStream(true); try { log.info("launching CUDA executable \"" + cudaProcessBuilder.command() + "\" with environment=\"" + cudaProcessBuilder.environment() + "\"+ in directory=" + cudaProcessBuilder.directory()); cudaProcess = cudaProcessBuilder.start(); Runtime.getRuntime().addShutdownHook(new Thread("CUDA detroyer") { @Override public void run() { log.info("destroying CUDA process"); cudaProcess.destroy(); } }); final BufferedReader outReader = new BufferedReader(new InputStreamReader(cudaProcess.getInputStream())); Thread outThread = new Thread("CUDA output") { public void run() { try { Thread.sleep(100); try { String line; do { line = outReader.readLine(); log.info("CUDA: " + line); } while (line != null); } catch (IOException ex) { log.warning(ex.toString()); } } catch (InterruptedException ex) { log.warning(ex.toString()); } } }; outThread.start(); Thread.sleep(300); sendParameters(); // set defaults to override #defines in CUDA code } catch (Exception ex) { log.warning(ex.toString()); } } private boolean checkControlSocket() { if (controlSocket == null) { try { controlSocket = new DatagramSocket(); // bind to any available port because we will send to CUDA on its port // writer = new OutputStreamWriter(controlSocket.getOutputStream()); log.info("bound to local port " + controlSocket.getLocalPort() + " for controlling CUDA"); sendParameters(); // send on construction in case CUDA is running } catch (Exception ex) { log.warning(ex.toString() + " to " + hostname + ":" + controlPort); return false; // return launchCuda(); } } return true; } private void checkIOPorts() throws IOException { if (unicastInput == null) { unicastInput = new AEUnicastInput(); unicastInput.setPort(recvOnPort); unicastInput.set4ByteAddrTimestampEnabled(true); unicastInput.setAddressFirstEnabled(true); unicastInput.setSequenceNumberEnabled(false); // TODO, should use seq numbers on both sides unicastInput.setSwapBytesEnabled(false); unicastInput.setTimestampMultiplier(1); unicastInput.start(); } if (unicastOutput == null) { unicastOutput = new AEUnicastOutput(); unicastOutput.setHost(getHostname()); unicastOutput.setPort(sendToPort); unicastOutput.set4ByteAddrTimestampEnabled(true); unicastOutput.setAddressFirstEnabled(true); unicastOutput.setSequenceNumberEnabled(true); // TODO sequence numbers unicastOutput.setSwapBytesEnabled(false); unicastOutput.setTimestampMultiplier(1); } } // private void checkOutputViewer() throws HeadlessException { // if (outputViewer == null) { // outputViewer = new AEViewer(chip.getAeViewer().getJaerViewer()); // Class originalChipClass = outputViewer.getAeChipClass(); // outputViewer.setAeChipClass(CUDAOutputAEChip.class); // outputViewer.setVisible(true); // outputViewer.setPreferredAEChipClass(originalChipClass); // outputViewer.reopenSocketInputStream(); // } // } private void sendParameters() { log.info("sending parameters to CUDA"); sendParameter(CMD_THRESHOLD, threshold); sendParameter(CMD_I_E_NEURON_POTENTIAL, iESynWeight); sendParameter(CMD_E_I_NEURON_POTENTIAL, eISynWeight); sendParameter(CMD_MEMBRANE_POTENTIAL_MIN, membranePotentialMin); sendParameter(CMD_MEMBRANE_TAU, membraneTauUs); sendParameter(CMD_MIN_FIRING_TIME_DIFF, minFiringTimeDiff); writeCommandToCuda(CMD_DEBUG_LEVEL + " " + debugLevel); writeCommandToCuda(CMD_CUDA_ENABLED + " " + cudaEnabled); writeCommandToCuda(CMD_KERNEL_SHAPE + " " + kernelShape.toString()); writeCommandToCuda(CMD_SPIKE_PARTITIONING_METHOD + " " + spikePartitioningMethod.toString()); writeCommandToCuda(CMD_MAX_XMIT_INTERVAL_MS + " " + maxXmitIntervalMs); writeCommandToCuda(CMD_CUDAS_RECVON_PORT + " " + sendToPort); // tells CUDA "inputPort XXX" which it uses to set which port it sends to writeCommandToCuda(CMD_CUDAS_SENDTO_PORT + " " + recvOnPort); } private void sendParameter(String name, float value) { String s = String.format(name + " " + value); writeCommandToCuda(s); } private boolean isCudaRunning() { if (cudaProcess == null) { return false; } try { int exitValue = 0; if ((exitValue = cudaProcess.exitValue()) != 0) { log.warning("CUDA exit process was " + exitValue); cudaProcess = null; } return false; } catch (IllegalThreadStateException e) { return true; } } // /** does reconnect to CUDA server */ // public void doReconnect() { // if (controlSocket != null) { // controlSocket.close(); // controlSocket = null; // } // checkControlSocket(); // } public void doSelectCUDAExecutable() { if (cudaExecutablePath == null || cudaExecutablePath.isEmpty()) { cudaExecutablePath = System.getProperty("user.dir"); } JFileChooser chooser = new JFileChooser(cudaExecutablePath); chooser.setDialogTitle("Choose CUDA executable .exe file (from CUDA project win32 subfolder)"); chooser.setFileFilter(new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".exe"); } @Override public String getDescription() { return "Executables"; } }); chooser.setMultiSelectionEnabled(false); int retval = chooser.showOpenDialog(getChip().getAeViewer().getFilterFrame()); if (retval == JFileChooser.APPROVE_OPTION) { File f = chooser.getSelectedFile(); if (f != null && f.isFile()) { setCudaExecutablePath(f.toString()); log.info("selected CUDA executable " + cudaExecutablePath); } } } private void writeCommandToCuda(String s) { if (!checkControlSocket()) { return; } byte[] b = s.getBytes(); DatagramPacket packet = new DatagramPacket(b, b.length, cudaInetAddress, controlPort); try { controlSocket.send(packet); } catch (IOException ex) { log.warning(ex.toString()); } // try { // writer.write(s); // } catch (IOException ex) { // log.warning("writing string " + s + " got " + ex); // } } public void doSendParameters() { sendParameters(); } private int warningCount = 0; /** Reconstructs a raw event packet, sends it to jaercuda, reads the output from jaercuda, extracts this raw packet, and then returns the events. @param in the input packets. @return the output packet. */ @Override public EventPacket<?> filterPacket(EventPacket<?> in) { if (!isFilterEnabled()) { return in; } if (!isCudaRunning()) { if (warningCount++ % 100 == 0) { log.warning("cuda has not been started from jaer or has terminated"); } // return in; } checkControlSocket(); try { checkIOPorts(); AEPacketRaw rawOutputPacket = chip.getEventExtractor().reconstructRawPacket(in); unicastOutput.writePacket(rawOutputPacket); AEPacketRaw rawInputPacket = unicastInput.readPacket(); // right here is where we can use a custom extractor to output any kind of events we like from the MSB bits of the returned addresses out = cudaExtractor.extractPacket(rawInputPacket); return out; } catch (IOException e) { log.warning(e.toString()); } return in; } /** This AEChip has an EventExtractor2D that understands the CUDA event output. * */ public class CUDAChip extends DVS128 { public CUDAChip() { setEventClass(PolarityEvent.class); // modify to elaborated event type, e.g. TypedEvent, and write extractPacket to understand it } public class CUDAExtractor extends CUDAChip.Extractor { public CUDAExtractor(DVS128 chip) { super(chip); } @Override public synchronized EventPacket extractPacket(AEPacketRaw in) { return super.extractPacket(in); } } } EventExtractor2D cudaExtractor = new CUDAChip().getEventExtractor(); @Override public synchronized void setFilterEnabled(boolean yes) { super.setFilterEnabled(yes); if (yes) { // checkOutputViewer(); } } @Override public Object getFilterState() { return null; } @Override public void resetFilter() { } @Override public void initFilter() { } public int getControlPort() { return controlPort; } public void setControlPort(int port) { support.firePropertyChange("controlPort", controlPort, port); this.controlPort = port; getPrefs().putInt("CUDAObjectTrackerControl.controlPort", controlPort); } /** * @return the inputPort */ public int getInputPort() { return recvOnPort; } /** * @param inputPort the inputPort to set */ public void setInputPort(int inputPort) { support.firePropertyChange("inputPort", this.recvOnPort, inputPort); this.recvOnPort = inputPort; getPrefs().putInt("CUDAObjectTrackerControl.inputPort", inputPort); if (unicastInput != null) { unicastInput.setPort(inputPort); } writeCommandToCuda(CMD_CUDAS_SENDTO_PORT + " " + inputPort); } /** * @return the outputPort */ public int getOutputPort() { return sendToPort; } /** * @param outputPort the outputPort to set */ public void setOutputPort(int outputPort) { support.firePropertyChange("outputPort", this.sendToPort, outputPort); this.sendToPort = outputPort; getPrefs().putInt("CUDAObjectTrackerControl.outputPort", outputPort); if (unicastOutput != null) { unicastOutput.setPort(outputPort); } writeCommandToCuda(CMD_CUDAS_RECVON_PORT + " " + outputPort); } public String getHostname() { return hostname; } public void setHostname(String hostname) { try { cudaInetAddress = InetAddress.getByName(hostname); } catch (UnknownHostException ex) { log.warning("CUDA hostname " + hostname + " unknown? " + ex.toString()); support.firePropertyChange("hostname", null, this.hostname); return; } support.firePropertyChange("hostname", this.hostname, hostname); this.hostname = hostname; getPrefs().put("CUDAObjectTrackerControl.hostname", hostname); } public float getThreshold() { return threshold; } public void setThreshold(float threshold) { support.firePropertyChange("threshold", this.threshold, threshold); this.threshold = threshold; getPrefs().putFloat("CUDAObjectTrackerControl.threshold", threshold); sendParameter(CMD_THRESHOLD, threshold); } /** * @return the cudaExecutablePath */ public String getCudaExecutablePath() { return cudaExecutablePath; } /** * @param cudaExecutablePath the cudaExecutablePath to set */ public void setCudaExecutablePath(String cudaExecutablePath) { support.firePropertyChange("cudaExecutablePath", this.cudaExecutablePath, cudaExecutablePath); this.cudaExecutablePath = cudaExecutablePath; getPrefs().put("CUDAObjectTrackerControl.cudaExecutablePath", cudaExecutablePath); } /** * @return the cudaEnvironmentPath */ public String getCudaEnvironmentPath() { return cudaEnvironmentPath; } /** * @param cudaEnvironmentPath the cudaEnvironmentPath to set */ public void setCudaEnvironmentPath(String cudaEnvironmentPath) { support.firePropertyChange("cudaEnvironmentPath", this.cudaEnvironmentPath, cudaEnvironmentPath); this.cudaEnvironmentPath = cudaEnvironmentPath; getPrefs().put("CUDAObjectTrackerControl.cudaEnvironmentPath", cudaEnvironmentPath); } /** * @return the membraneTauUs */ public float getMembraneTauUs() { return membraneTauUs; } /** * @param membraneTauUs the membraneTauUs to set */ public void setMembraneTauUs(float membraneTauUs) { support.firePropertyChange("membraneTauUs", this.membraneTauUs, membraneTauUs); this.membraneTauUs = membraneTauUs; getPrefs().putFloat("CUDAObjectTrackerControl.membraneTauUs", membraneTauUs); sendParameter(CMD_MEMBRANE_TAU, membraneTauUs); } /** * @return the membranePotentialMin */ public float getMembranePotentialMin() { return membranePotentialMin; } /** * @param membranePotentialMin the membranePotentialMin to set */ public void setMembranePotentialMin(float membranePotentialMin) { support.firePropertyChange("membranePotentialMin", this.membranePotentialMin, membranePotentialMin); this.membranePotentialMin = membranePotentialMin; getPrefs().putFloat("CUDAObjectTrackerControl.membranePotentialMin", membranePotentialMin); sendParameter(CMD_MEMBRANE_POTENTIAL_MIN, membranePotentialMin); } /** * @return the minFiringTimeDiff */ public float getMinFiringTimeDiff() { return minFiringTimeDiff; } /** * @param minFiringTimeDiff the minFiringTimeDiff to set */ public void setMinFiringTimeDiff(float minFiringTimeDiff) { support.firePropertyChange("minFiringTimeDiff", this.minFiringTimeDiff, minFiringTimeDiff); this.minFiringTimeDiff = minFiringTimeDiff; getPrefs().putFloat("CUDAObjectTrackerControl.minFiringTimeDiff", minFiringTimeDiff); sendParameter(CMD_MIN_FIRING_TIME_DIFF, minFiringTimeDiff); } /** * @return the eISynWeight */ public float geteISynWeight() { return eISynWeight; } /** * @param eISynWeight the eISynWeight to set */ public void seteISynWeight(float eISynWeight) { support.firePropertyChange("eISynWeight", this.eISynWeight, eISynWeight); this.eISynWeight = eISynWeight; getPrefs().putFloat("CUDAObjectTrackerControl.eISynWeight", eISynWeight); sendParameter(CMD_E_I_NEURON_POTENTIAL, eISynWeight); } /** * @return the iESynWeight */ public float getiESynWeight() { return iESynWeight; } /** * @param iESynWeight the iESynWeight to set */ public void setiESynWeight(float iESynWeight) { support.firePropertyChange("iESynWeight", this.iESynWeight, iESynWeight); this.iESynWeight = iESynWeight; getPrefs().putFloat("CUDAObjectTrackerControl.iESynWeight", iESynWeight); sendParameter(CMD_I_E_NEURON_POTENTIAL, iESynWeight); } /** * @return the kernelShape */ public KernelShape getKernelShape() { return kernelShape; } /** * @param kernelShape the kernelShape to set */ public void setKernelShape(KernelShape kernelShape) { support.firePropertyChange("kernelShape", this.kernelShape, kernelShape); this.kernelShape = kernelShape; getPrefs().put("CUDAObjectTrackerControl.kernelShape", kernelShape.toString()); writeCommandToCuda(CMD_KERNEL_SHAPE + " " + kernelShape.toString()); } /** * @return the spikePartitioningMethod */ public SpikePartitioningMethod getSpikePartitioningMethod() { return spikePartitioningMethod; } /** * @param spikePartitioningMethod the spikePartitioningMethod to set */ public void setSpikePartitioningMethod(SpikePartitioningMethod spikePartitioningMethod) { support.firePropertyChange("kernelShape", this.spikePartitioningMethod, spikePartitioningMethod); this.spikePartitioningMethod = spikePartitioningMethod; getPrefs().put("CUDAObjectTrackerControl.spikePartitioningMethod", spikePartitioningMethod.toString()); writeCommandToCuda(CMD_SPIKE_PARTITIONING_METHOD + " " + spikePartitioningMethod.toString()); } /** * @return the cudaEnabled */ public boolean isCudaEnabled() { return cudaEnabled; } /** * @param cudaEnabled the cudaEnabled to set */ public void setCudaEnabled(boolean cudaEnabled) { support.firePropertyChange("cudaEnabled", this.cudaEnabled, cudaEnabled); this.cudaEnabled = cudaEnabled; getPrefs().putBoolean("CUDAObjectTrackerControl.cudaEnabled", cudaEnabled); writeCommandToCuda(CMD_CUDA_ENABLED + " " + cudaEnabled); } /** * @return the debugLevel */ public int getDebugLevel() { return debugLevel; } /** * @param debugLevel the debugLevel to set */ public void setDebugLevel(int debugLevel) { support.firePropertyChange("debugLevel", this.debugLevel, debugLevel); this.debugLevel = debugLevel; getPrefs().putInt("CUDAObjectTrackerControl.debugLevel", debugLevel); writeCommandToCuda(CMD_DEBUG_LEVEL + " " + debugLevel); } /** * @return the maxXmitIntervalMs */ public int getMaxXmitIntervalMs() { return maxXmitIntervalMs; } /** * @param maxXmitIntervalMs the maxXmitIntervalMs to set */ public void setMaxXmitIntervalMs(int maxXmitIntervalMs) { support.firePropertyChange("maxXmitIntervalMs", this.maxXmitIntervalMs, maxXmitIntervalMs); this.maxXmitIntervalMs = maxXmitIntervalMs; getPrefs().putInt("CUDAObjectTrackerControl.maxXmitIntervalMs", maxXmitIntervalMs); writeCommandToCuda(CMD_MAX_XMIT_INTERVAL_MS + " " + maxXmitIntervalMs); } // TODO these classes define properties for communicating with CUDA, but i cannot see how to statically compile in the get/set // to go with them to allow introspection to find them public class CUDACommand { String cmd = null; String tooltip = null; String name; public void writeCommand() { writeCommandToCuda(cmd); } public CUDACommand(String name, String cmd, String tooltip) { this.cmd = cmd; this.tooltip = tooltip; this.name = name; setPropertyTooltip(cmd, tooltip); } } public class CUDAParameter extends CUDACommand { Object obj; public CUDAParameter(String name, String cmd, Object obj, String tooltip) { super(name, cmd, tooltip); this.obj = obj; } @Override public void writeCommand() { writeCommandToCuda(cmd + " " + obj.toString()); } public Object get() { return obj; } public void set(Object obj) { support.firePropertyChange(name, get(), obj); this.obj = obj; getPrefs().put("CUDAObjectTrackerControl." + name, obj.toString()); } } }
check for control port moved inside checkIOPorts in filterPacket method git-svn-id: e3d3b427d532171a6bd7557d8a4952a393b554a2@1164 b7f4320f-462c-0410-a916-d9f35bb82d52
src/org/ine/telluride/jaer/cuda/CUDAObjectTrackerControl.java
check for control port moved inside checkIOPorts in filterPacket method
<ide><path>rc/org/ine/telluride/jaer/cuda/CUDAObjectTrackerControl.java <ide> return true; <ide> } <ide> <del> private void checkIOPorts() throws IOException { <add> synchronized private void checkIOPorts() throws IOException { <add> checkControlSocket(); <ide> if (unicastInput == null) { <ide> unicastInput = new AEUnicastInput(); <ide> unicastInput.setPort(recvOnPort); <ide> // outputViewer.reopenSocketInputStream(); <ide> // } <ide> // } <del> private void sendParameters() { <add> <add> // thread safe for renewing sockets <add> synchronized private void sendParameters() { <ide> log.info("sending parameters to CUDA"); <ide> sendParameter(CMD_THRESHOLD, threshold); <ide> sendParameter(CMD_I_E_NEURON_POTENTIAL, iESynWeight); <ide> return in; <ide> } <ide> if (!isCudaRunning()) { <del> if (warningCount++ % 100 == 0) { <add> if (warningCount++ % 300 == 0) { <ide> log.warning("cuda has not been started from jaer or has terminated"); <ide> } <ide> // return in; <ide> } <del> checkControlSocket(); <ide> try { <ide> checkIOPorts(); <ide> AEPacketRaw rawOutputPacket = chip.getEventExtractor().reconstructRawPacket(in);
Java
apache-2.0
af1961c56a9dde6aedfa81b1a7f04b744c4a9638
0
apereo/cas,rkorn86/cas,Jasig/cas,fogbeam/cas_mirror,rkorn86/cas,Jasig/cas,apereo/cas,fogbeam/cas_mirror,fogbeam/cas_mirror,rkorn86/cas,rkorn86/cas,fogbeam/cas_mirror,apereo/cas,apereo/cas,fogbeam/cas_mirror,fogbeam/cas_mirror,apereo/cas,apereo/cas,apereo/cas,Jasig/cas,Jasig/cas
package org.apereo.cas.monitor; import org.apereo.cas.config.CasCoreUtilSerializationConfiguration; import org.apereo.cas.monitor.config.MemcachedMonitorConfiguration; import org.apereo.cas.util.junit.EnabledIfPortOpen; import lombok.val; import net.spy.memcached.MemcachedClientIF; import org.apache.commons.pool2.ObjectPool; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.boot.actuate.health.Status; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration; import org.springframework.test.annotation.DirtiesContext; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; /** * This is {@link MemcachedHealthIndicatorTests}. * * @author Misagh Moayyed * @since 4.2.0 */ @SpringBootTest(classes = { RefreshAutoConfiguration.class, MemcachedMonitorConfiguration.class, CasCoreUtilSerializationConfiguration.class }, properties = { "cas.monitor.memcached.servers=localhost:11212", "cas.monitor.memcached.failure-mode=Redistribute", "cas.monitor.memcached.locator-type=ARRAY_MOD", "cas.monitor.memcached.hash-algorithm=FNV1A_64_HASH" }) @DirtiesContext @Tag("Memcached") @EnabledIfPortOpen(port = 11211) public class MemcachedHealthIndicatorTests { @Autowired @Qualifier("memcachedHealthIndicator") private HealthIndicator monitor; @Test public void verifyMonitorNotRunning() { val health = monitor.health(); assertEquals(Status.OUT_OF_SERVICE, health.getStatus()); } @Test public void verifyUnavailableServers() throws Exception { val memcached = mock(MemcachedClientIF.class); when(memcached.getUnavailableServers()).thenReturn(List.of(new InetSocketAddress(1234))); when(memcached.getAvailableServers()).thenReturn(List.of(new InetSocketAddress(11212))); val client = mock(ObjectPool.class); when(client.borrowObject()).thenReturn(memcached); val indicator = new MemcachedHealthIndicator(client, 1, 1); val health = indicator.health(); assertEquals(Status.DOWN, health.getStatus()); } @Test public void verifyMonitorError() throws Exception { val memcached = mock(MemcachedClientIF.class); when(memcached.getUnavailableServers()).thenThrow(new RuntimeException("error")); when(memcached.getAvailableServers()).thenThrow(new RuntimeException("error")); val client = mock(ObjectPool.class); when(client.borrowObject()).thenReturn(memcached); val indicator = new MemcachedHealthIndicator(client, 1, 1); val health = indicator.health(); assertEquals(Status.DOWN, health.getStatus()); } @Test public void verifyMonitorSuccess() throws Exception { val memcached = mock(MemcachedClientIF.class); when(memcached.getUnavailableServers()).thenReturn(List.of()); val socket = new InetSocketAddress("localhost", 11212); when(memcached.getAvailableServers()).thenReturn(List.of(socket)); val details = new HashMap<String, String>(); details.put("bytes", "1000"); details.put("limit_maxbytes", "500"); details.put("evictions", "10"); when(memcached.getStats()).thenReturn(Map.of(socket, details)); val client = mock(ObjectPool.class); when(client.borrowObject()).thenReturn(memcached); val indicator = new MemcachedHealthIndicator(client, 1, 1); val health = indicator.health(); assertEquals(new Status("WARN"), health.getStatus()); } }
support/cas-server-support-memcached-monitor/src/test/java/org/apereo/cas/monitor/MemcachedHealthIndicatorTests.java
package org.apereo.cas.monitor; import org.apereo.cas.config.CasCoreUtilSerializationConfiguration; import org.apereo.cas.monitor.config.MemcachedMonitorConfiguration; import org.apereo.cas.util.junit.EnabledIfPortOpen; import lombok.val; import net.spy.memcached.MemcachedClientIF; import org.apache.commons.pool2.ObjectPool; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.boot.actuate.health.Status; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration; import org.springframework.test.annotation.DirtiesContext; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; /** * This is {@link MemcachedHealthIndicatorTests}. * * @author Misagh Moayyed * @since 4.2.0 */ @SpringBootTest(classes = { RefreshAutoConfiguration.class, MemcachedMonitorConfiguration.class, CasCoreUtilSerializationConfiguration.class }, properties = { "cas.monitor.memcached.servers=localhost:11212", "cas.monitor.memcached.failureMode=Redistribute", "cas.monitor.memcached.locatorType=ARRAY_MOD", "cas.monitor.memcached.hashAlgorithm=FNV1A_64_HASH" }) @DirtiesContext @Tag("Memcached") @EnabledIfPortOpen(port = 11211) public class MemcachedHealthIndicatorTests { @Autowired @Qualifier("memcachedHealthIndicator") private HealthIndicator monitor; @Test public void verifyMonitorNotRunning() { val health = monitor.health(); assertEquals(Status.OUT_OF_SERVICE, health.getStatus()); } @Test public void verifyUnavailableServers() throws Exception { val memcached = mock(MemcachedClientIF.class); when(memcached.getUnavailableServers()).thenReturn(List.of(new InetSocketAddress(1234))); when(memcached.getAvailableServers()).thenReturn(List.of(new InetSocketAddress(11212))); val client = mock(ObjectPool.class); when(client.borrowObject()).thenReturn(memcached); val indicator = new MemcachedHealthIndicator(client, 1, 1); val health = indicator.health(); assertEquals(Status.DOWN, health.getStatus()); } @Test public void verifyMonitorError() throws Exception { val memcached = mock(MemcachedClientIF.class); when(memcached.getUnavailableServers()).thenThrow(new RuntimeException("error")); when(memcached.getAvailableServers()).thenThrow(new RuntimeException("error")); val client = mock(ObjectPool.class); when(client.borrowObject()).thenReturn(memcached); val indicator = new MemcachedHealthIndicator(client, 1, 1); val health = indicator.health(); assertEquals(Status.DOWN, health.getStatus()); } @Test public void verifyMonitorSuccess() throws Exception { val memcached = mock(MemcachedClientIF.class); when(memcached.getUnavailableServers()).thenReturn(List.of()); val socket = new InetSocketAddress("localhost", 11212); when(memcached.getAvailableServers()).thenReturn(List.of(socket)); val details = new HashMap<String, String>(); details.put("bytes", "1000"); details.put("limit_maxbytes", "500"); details.put("evictions", "10"); when(memcached.getStats()).thenReturn(Map.of(socket, details)); val client = mock(ObjectPool.class); when(client.borrowObject()).thenReturn(memcached); val indicator = new MemcachedHealthIndicator(client, 1, 1); val health = indicator.health(); assertEquals(new Status("WARN"), health.getStatus()); } }
trigger dependency update
support/cas-server-support-memcached-monitor/src/test/java/org/apereo/cas/monitor/MemcachedHealthIndicatorTests.java
trigger dependency update
<ide><path>upport/cas-server-support-memcached-monitor/src/test/java/org/apereo/cas/monitor/MemcachedHealthIndicatorTests.java <ide> CasCoreUtilSerializationConfiguration.class <ide> }, properties = { <ide> "cas.monitor.memcached.servers=localhost:11212", <del> "cas.monitor.memcached.failureMode=Redistribute", <del> "cas.monitor.memcached.locatorType=ARRAY_MOD", <del> "cas.monitor.memcached.hashAlgorithm=FNV1A_64_HASH" <add> "cas.monitor.memcached.failure-mode=Redistribute", <add> "cas.monitor.memcached.locator-type=ARRAY_MOD", <add> "cas.monitor.memcached.hash-algorithm=FNV1A_64_HASH" <ide> }) <ide> @DirtiesContext <ide> @Tag("Memcached")
Java
apache-2.0
e73c42dfe7ff36701352fb63996431da2ecc5d07
0
ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf
/* * $Log: SpringJmsConnector.java,v $ * Revision 1.17 2008-08-27 16:23:02 europe\L190409 * improved logging * * Revision 1.16 2008/08/21 17:56:20 Gerrit van Brakel <[email protected]> * removed ifsa specific timing evaluation, that was not working * * Revision 1.15 2008/06/30 14:18:27 Gerrit van Brakel <[email protected]> * use more robust detection transaction and setting of rollbackonly * * Revision 1.14 2008/06/24 15:13:08 Gerrit van Brakel <[email protected]> * improved logging of exceptions * * Revision 1.13 2008/06/18 12:39:24 Gerrit van Brakel <[email protected]> * set default cache mode CACHE_NONE, for both transacted and non transacted * * Revision 1.12 2008/05/14 11:51:45 Gerrit van Brakel <[email protected]> * improved handling when not completly configured * * Revision 1.11 2008/02/19 13:58:35 Gerrit van Brakel <[email protected]> * tiny little bug, pushed into 4.8.0 * * Revision 1.10 2008/02/15 14:11:16 Gerrit van Brakel <[email protected]> * avoid NPE when not configured * * Revision 1.9 2008/02/13 13:32:49 Gerrit van Brakel <[email protected]> * show detailed processing times * * Revision 1.8 2008/02/06 16:38:51 Gerrit van Brakel <[email protected]> * added support for setting of transaction timeout * removed global transaction inserted for jmsTransacted handling * * Revision 1.7 2008/01/29 12:17:26 Gerrit van Brakel <[email protected]> * added support for thread number control * * Revision 1.6 2008/01/17 16:24:47 Gerrit van Brakel <[email protected]> * txManager in onMessage only for only local transacted sessions * * Revision 1.5 2008/01/11 10:23:59 Gerrit van Brakel <[email protected]> * fixed a lot of things * * Revision 1.4 2008/01/03 15:57:58 Gerrit van Brakel <[email protected]> * rework port connected listener interfaces * * Revision 1.3 2007/11/22 09:12:03 Gerrit van Brakel <[email protected]> * added message as parameter of populateThreadContext * * Revision 1.2 2007/11/05 13:06:55 Tim van der Leeuw <[email protected]> * Rename and redefine methods in interface IListenerConnector to remove 'jms' from names * * Revision 1.1 2007/11/05 12:24:01 Tim van der Leeuw <[email protected]> * Rename 'SpringJmsConfigurator' to 'SpringJmsConnector' * * Revision 1.5 2007/11/05 10:33:15 Tim van der Leeuw <[email protected]> * Move interface 'IListenerConnector' from package 'configuration' to package 'core' in preparation of renaming it * * Revision 1.4 2007/10/17 11:33:40 Gerrit van Brakel <[email protected]> * add at least one consumer * * Revision 1.3 2007/10/16 09:52:35 Tim van der Leeuw <[email protected]> * Change over JmsListener to a 'switch-class' to facilitate smoother switchover from older version to spring version * * Revision 1.2 2007/10/15 13:11:04 Gerrit van Brakel <[email protected]> * copy from EJB branch * */ package nl.nn.adapterframework.unmanaged; import java.util.HashMap; import java.util.Map; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.ExceptionListener; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.IListenerConnector; import nl.nn.adapterframework.core.IPortConnectedListener; import nl.nn.adapterframework.core.IThreadCountControllable; import nl.nn.adapterframework.core.IbisExceptionListener; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.util.Counter; import nl.nn.adapterframework.util.DateUtils; import org.apache.commons.lang.StringUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.jms.listener.DefaultMessageListenerContainer; import org.springframework.jms.listener.SessionAwareMessageListener; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import com.ing.ifsa.IFSAMessage; /** * Configure a Spring JMS Container from a {@link nl.nn.adapterframework.jms.PushingJmsListener}. * * <p> * This implementation expects to receive an instance of * org.springframework.jms.listener.DefaultMessageListenerContainer * from the Spring BeanFactory. If another type of MessageListenerContainer * is created by the BeanFactory, then another implementation of IListenerConnector * should be provided as well. * </p> * <p> * This implementation works only with a PushingJmsListener, and not with other types PortConnectedListeners. * </p> * @author Tim van der Leeuw * @since 4.8 * @version Id */ public class SpringJmsConnector extends AbstractJmsConfigurator implements IListenerConnector, IThreadCountControllable, BeanFactoryAware, ExceptionListener, SessionAwareMessageListener { private PlatformTransactionManager txManager; private BeanFactory beanFactory; private DefaultMessageListenerContainer jmsContainer; private String messageListenerClassName; public static final int DEFAULT_CACHE_LEVEL_TRANSACTED=DefaultMessageListenerContainer.CACHE_NONE; public static final int DEFAULT_CACHE_LEVEL_NON_TRANSACTED=DefaultMessageListenerContainer.CACHE_NONE; // public static final int MAX_MESSAGES_PER_TASK=100; public static final int IDLE_TASK_EXECUTION_LIMIT=1000; private TransactionDefinition TX = null; int retryInterval=5; final Counter threadsProcessing = new Counter(0); protected DefaultMessageListenerContainer createMessageListenerContainer() throws ConfigurationException { try { Class klass = Class.forName(messageListenerClassName); return (DefaultMessageListenerContainer) klass.newInstance(); } catch (Exception e) { throw new ConfigurationException(getLogPrefix()+"error creating instance of MessageListenerContainer ["+messageListenerClassName+"]", e); } } /* (non-Javadoc) * @see nl.nn.adapterframework.configuration.IListenerConnector#configureReceiver(nl.nn.adapterframework.jms.PushingJmsListener) */ public void configureEndpointConnection(final IPortConnectedListener jmsListener, ConnectionFactory connectionFactory, Destination destination, IbisExceptionListener exceptionListener, String cacheMode, boolean sessionTransacted, String messageSelector) throws ConfigurationException { super.configureEndpointConnection(jmsListener, connectionFactory, destination, exceptionListener); // Create the Message Listener Container manually. // This is needed, because otherwise the Spring Factory will // call afterPropertiesSet() on the object which will validate // that all required properties are set before we get a chance // to insert our dynamic values from the config. file. this.jmsContainer = createMessageListenerContainer(); if (getReceiver().isTransacted()) { log.debug(getLogPrefix()+"setting transction manager to ["+txManager+"]"); jmsContainer.setTransactionManager(txManager); if (getReceiver().getTransactionTimeout()>0) { jmsContainer.setTransactionTimeout(getReceiver().getTransactionTimeout()); } TX = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED); } else { log.debug(getLogPrefix()+"setting no transction manager"); } if (sessionTransacted) { jmsContainer.setSessionTransacted(sessionTransacted); } if (StringUtils.isNotEmpty(messageSelector)) { jmsContainer.setMessageSelector(messageSelector); } // Initialize with a number of dynamic properties which come from the configuration file jmsContainer.setConnectionFactory(getConnectionFactory()); jmsContainer.setDestination(getDestination()); jmsContainer.setExceptionListener(this); // the following is not required, the timeout set is the time waited to start a new poll attempt. //this.jmsContainer.setReceiveTimeout(getJmsListener().getTimeOut()); if (getReceiver().getNumThreads() > 0) { jmsContainer.setMaxConcurrentConsumers(getReceiver().getNumThreads()); } else { jmsContainer.setMaxConcurrentConsumers(1); } jmsContainer.setIdleTaskExecutionLimit(IDLE_TASK_EXECUTION_LIMIT); if (StringUtils.isNotEmpty(cacheMode)) { jmsContainer.setCacheLevelName(cacheMode); } else { if (getReceiver().isTransacted()) { jmsContainer.setCacheLevel(DEFAULT_CACHE_LEVEL_TRANSACTED); } else { jmsContainer.setCacheLevel(DEFAULT_CACHE_LEVEL_NON_TRANSACTED); } } jmsContainer.setMessageListener(this); // Use Spring BeanFactory to complete the auto-wiring of the JMS Listener Container, // and run the bean lifecycle methods. try { ((AutowireCapableBeanFactory) this.beanFactory).configureBean(this.jmsContainer, "proto-jmsContainer"); } catch (BeansException e) { throw new ConfigurationException(getLogPrefix()+"Out of luck wiring up and configuring Default JMS Message Listener Container for JMS Listener ["+ (getListener().getName()+"]"), e); } // Finally, set bean name to something we can make sense of if (getListener().getName() != null) { jmsContainer.setBeanName(getListener().getName()); } else { jmsContainer.setBeanName(getReceiver().getName()); } } public void start() throws ListenerException { log.debug(getLogPrefix()+"starting"); if (jmsContainer!=null) { try { jmsContainer.start(); } catch (Exception e) { throw new ListenerException(getLogPrefix()+"cannot start", e); } } else { throw new ListenerException(getLogPrefix()+"no jmsContainer defined"); } } public void stop() throws ListenerException { log.debug(getLogPrefix()+"stopping"); if (jmsContainer!=null) { try { jmsContainer.stop(); } catch (Exception e) { throw new ListenerException(getLogPrefix()+"Exception while trying to stop", e); } } else { throw new ListenerException(getLogPrefix()+"no jmsContainer defined"); } } public void onMessage(Message message, Session session) throws JMSException { TransactionStatus txStatus=null; long onMessageStart= System.currentTimeMillis(); long jmsTimestamp= message.getJMSTimestamp(); threadsProcessing.increase(); Thread.currentThread().setName(getReceiver().getName()+"["+threadsProcessing.getValue()+"]"); try { if (TX!=null) { txStatus = txManager.getTransaction(TX); } Map threadContext = new HashMap(); try { IPortConnectedListener listener = getListener(); threadContext.put("session",session); // if (log.isDebugEnabled()) log.debug("transaction status before: "+JtaUtil.displayTransactionStatus()); getReceiver().processRawMessage(listener, message, threadContext); // if (log.isDebugEnabled()) log.debug("transaction status after: "+JtaUtil.displayTransactionStatus()); getReceiver().resetRetryInterval(); } catch (ListenerException e) { getReceiver().increaseRetryIntervalAndWait(e,getLogPrefix()); if (txStatus!=null) { txStatus.setRollbackOnly(); } else { JMSException jmse = new JMSException(getLogPrefix()+"caught exception: "+e.getMessage()); jmse.setLinkedException(e); throw jmse; } // if (JtaUtil.inTransaction()) { // log.warn(getLogPrefix()+"caught exception processing message, setting rollbackonly", e); // JtaUtil.setRollbackOnly(); // } else { // if (jmsContainer.isSessionTransacted()) { // log.warn(getLogPrefix()+"caught exception processing message, rolling back JMS session", e); // session.rollback(); // } else { // JMSException jmse = new JMSException(getLogPrefix()+"caught exception, no transactional stuff to rollback"); // jmse.initCause(e); // throw jmse; // } // } } finally { if (jmsContainer.isSessionTransacted()) { log.debug(getLogPrefix()+"committing JMS session"); session.commit(); } } } finally { if (txStatus!=null) { txManager.commit(txStatus); } threadsProcessing.decrease(); if (log.isInfoEnabled()) { long onMessageEnd= System.currentTimeMillis(); log.info(getLogPrefix()+"A) JMSMessageTime ["+DateUtils.format(jmsTimestamp)+"]"); log.info(getLogPrefix()+"B) onMessageStart ["+DateUtils.format(onMessageStart)+"] diff (~'queing' time) ["+(onMessageStart-jmsTimestamp)+"]"); log.info(getLogPrefix()+"C) onMessageEnd ["+DateUtils.format(onMessageEnd)+"] diff (process time) ["+(onMessageEnd-onMessageStart)+"]"); } // boolean simulateCrashAfterCommit=true; // if (simulateCrashAfterCommit) { // toggle=!toggle; // if (toggle) { // JtaUtil.setRollbackOnly(); // throw new JMSException("simulate crash just before final commit"); // } // } } } // private boolean toggle=true; public void onException(JMSException e) { IbisExceptionListener ibisExceptionListener = getExceptionListener(); if (ibisExceptionListener!= null) { ibisExceptionListener.exceptionThrown(getListener(), e); } else { log.error(getLogPrefix()+"Cannot report the error to an IBIS Exception Listener", e); } } public boolean isThreadCountReadable() { return jmsContainer!=null; } public boolean isThreadCountControllable() { return jmsContainer!=null; } public int getCurrentThreadCount() { if (jmsContainer!=null) { return jmsContainer.getActiveConsumerCount(); } return 0; } public int getMaxThreadCount() { if (jmsContainer!=null) { return jmsContainer.getMaxConcurrentConsumers(); } return 0; } public void increaseThreadCount() { if (jmsContainer!=null) { jmsContainer.setMaxConcurrentConsumers(jmsContainer.getMaxConcurrentConsumers()+1); } } public void decreaseThreadCount() { if (jmsContainer!=null) { int current=getMaxThreadCount(); if (current>1) { jmsContainer.setMaxConcurrentConsumers(current-1); } } } public String getLogPrefix() { String result="SpringJmsContainer "; if (getListener()!=null && getListener().getReceiver()!=null) { result += "of Receiver ["+getListener().getReceiver().getName()+"] "; } return result; } /* (non-Javadoc) * @see org.springframework.beans.factory.BeanFactoryAware#setBeanFactory(org.springframework.beans.factory.BeanFactory) */ public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } public void setTxManager(PlatformTransactionManager txManager) { this.txManager = txManager; } public PlatformTransactionManager getTxManager() { return txManager; } public void setMessageListenerClassName(String messageListenerClassName) { this.messageListenerClassName = messageListenerClassName; } public String getMessageListenerClassName() { return messageListenerClassName; } }
JavaSource/nl/nn/adapterframework/unmanaged/SpringJmsConnector.java
/* * $Log: SpringJmsConnector.java,v $ * Revision 1.16 2008-08-21 17:56:20 europe\L190409 * removed ifsa specific timing evaluation, that was not working * * Revision 1.15 2008/06/30 14:18:27 Gerrit van Brakel <[email protected]> * use more robust detection transaction and setting of rollbackonly * * Revision 1.14 2008/06/24 15:13:08 Gerrit van Brakel <[email protected]> * improved logging of exceptions * * Revision 1.13 2008/06/18 12:39:24 Gerrit van Brakel <[email protected]> * set default cache mode CACHE_NONE, for both transacted and non transacted * * Revision 1.12 2008/05/14 11:51:45 Gerrit van Brakel <[email protected]> * improved handling when not completly configured * * Revision 1.11 2008/02/19 13:58:35 Gerrit van Brakel <[email protected]> * tiny little bug, pushed into 4.8.0 * * Revision 1.10 2008/02/15 14:11:16 Gerrit van Brakel <[email protected]> * avoid NPE when not configured * * Revision 1.9 2008/02/13 13:32:49 Gerrit van Brakel <[email protected]> * show detailed processing times * * Revision 1.8 2008/02/06 16:38:51 Gerrit van Brakel <[email protected]> * added support for setting of transaction timeout * removed global transaction inserted for jmsTransacted handling * * Revision 1.7 2008/01/29 12:17:26 Gerrit van Brakel <[email protected]> * added support for thread number control * * Revision 1.6 2008/01/17 16:24:47 Gerrit van Brakel <[email protected]> * txManager in onMessage only for only local transacted sessions * * Revision 1.5 2008/01/11 10:23:59 Gerrit van Brakel <[email protected]> * fixed a lot of things * * Revision 1.4 2008/01/03 15:57:58 Gerrit van Brakel <[email protected]> * rework port connected listener interfaces * * Revision 1.3 2007/11/22 09:12:03 Gerrit van Brakel <[email protected]> * added message as parameter of populateThreadContext * * Revision 1.2 2007/11/05 13:06:55 Tim van der Leeuw <[email protected]> * Rename and redefine methods in interface IListenerConnector to remove 'jms' from names * * Revision 1.1 2007/11/05 12:24:01 Tim van der Leeuw <[email protected]> * Rename 'SpringJmsConfigurator' to 'SpringJmsConnector' * * Revision 1.5 2007/11/05 10:33:15 Tim van der Leeuw <[email protected]> * Move interface 'IListenerConnector' from package 'configuration' to package 'core' in preparation of renaming it * * Revision 1.4 2007/10/17 11:33:40 Gerrit van Brakel <[email protected]> * add at least one consumer * * Revision 1.3 2007/10/16 09:52:35 Tim van der Leeuw <[email protected]> * Change over JmsListener to a 'switch-class' to facilitate smoother switchover from older version to spring version * * Revision 1.2 2007/10/15 13:11:04 Gerrit van Brakel <[email protected]> * copy from EJB branch * */ package nl.nn.adapterframework.unmanaged; import java.util.HashMap; import java.util.Map; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.ExceptionListener; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.IListenerConnector; import nl.nn.adapterframework.core.IPortConnectedListener; import nl.nn.adapterframework.core.IThreadCountControllable; import nl.nn.adapterframework.core.IbisExceptionListener; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.util.Counter; import nl.nn.adapterframework.util.DateUtils; import org.apache.commons.lang.StringUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.jms.listener.DefaultMessageListenerContainer; import org.springframework.jms.listener.SessionAwareMessageListener; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import com.ing.ifsa.IFSAMessage; /** * Configure a Spring JMS Container from a {@link nl.nn.adapterframework.jms.PushingJmsListener}. * * <p> * This implementation expects to receive an instance of * org.springframework.jms.listener.DefaultMessageListenerContainer * from the Spring BeanFactory. If another type of MessageListenerContainer * is created by the BeanFactory, then another implementation of IListenerConnector * should be provided as well. * </p> * <p> * This implementation works only with a PushingJmsListener, and not with other types PortConnectedListeners. * </p> * @author Tim van der Leeuw * @since 4.8 * @version Id */ public class SpringJmsConnector extends AbstractJmsConfigurator implements IListenerConnector, IThreadCountControllable, BeanFactoryAware, ExceptionListener, SessionAwareMessageListener { private PlatformTransactionManager txManager; private BeanFactory beanFactory; private DefaultMessageListenerContainer jmsContainer; private String messageListenerClassName; public static final int DEFAULT_CACHE_LEVEL_TRANSACTED=DefaultMessageListenerContainer.CACHE_NONE; public static final int DEFAULT_CACHE_LEVEL_NON_TRANSACTED=DefaultMessageListenerContainer.CACHE_NONE; // public static final int MAX_MESSAGES_PER_TASK=100; public static final int IDLE_TASK_EXECUTION_LIMIT=1000; private TransactionDefinition TX = null; int retryInterval=5; final Counter threadsProcessing = new Counter(0); protected DefaultMessageListenerContainer createMessageListenerContainer() throws ConfigurationException { try { Class klass = Class.forName(messageListenerClassName); return (DefaultMessageListenerContainer) klass.newInstance(); } catch (Exception e) { throw new ConfigurationException(getLogPrefix()+"error creating instance of MessageListenerContainer ["+messageListenerClassName+"]", e); } } /* (non-Javadoc) * @see nl.nn.adapterframework.configuration.IListenerConnector#configureReceiver(nl.nn.adapterframework.jms.PushingJmsListener) */ public void configureEndpointConnection(final IPortConnectedListener jmsListener, ConnectionFactory connectionFactory, Destination destination, IbisExceptionListener exceptionListener, String cacheMode, boolean sessionTransacted, String messageSelector) throws ConfigurationException { super.configureEndpointConnection(jmsListener, connectionFactory, destination, exceptionListener); // Create the Message Listener Container manually. // This is needed, because otherwise the Spring Factory will // call afterPropertiesSet() on the object which will validate // that all required properties are set before we get a chance // to insert our dynamic values from the config. file. this.jmsContainer = createMessageListenerContainer(); if (getReceiver().isTransacted()) { log.debug(getLogPrefix()+"setting transction manager to ["+txManager+"]"); jmsContainer.setTransactionManager(txManager); if (getReceiver().getTransactionTimeout()>0) { jmsContainer.setTransactionTimeout(getReceiver().getTransactionTimeout()); } TX = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED); } else { log.debug(getLogPrefix()+"setting no transction manager"); } if (sessionTransacted) { jmsContainer.setSessionTransacted(sessionTransacted); } if (StringUtils.isNotEmpty(messageSelector)) { jmsContainer.setMessageSelector(messageSelector); } // Initialize with a number of dynamic properties which come from the configuration file jmsContainer.setConnectionFactory(getConnectionFactory()); jmsContainer.setDestination(getDestination()); jmsContainer.setExceptionListener(this); // the following is not required, the timeout set is the time waited to start a new poll attempt. //this.jmsContainer.setReceiveTimeout(getJmsListener().getTimeOut()); if (getReceiver().getNumThreads() > 0) { jmsContainer.setMaxConcurrentConsumers(getReceiver().getNumThreads()); } else { jmsContainer.setMaxConcurrentConsumers(1); } jmsContainer.setIdleTaskExecutionLimit(IDLE_TASK_EXECUTION_LIMIT); if (StringUtils.isNotEmpty(cacheMode)) { jmsContainer.setCacheLevelName(cacheMode); } else { if (getReceiver().isTransacted()) { jmsContainer.setCacheLevel(DEFAULT_CACHE_LEVEL_TRANSACTED); } else { jmsContainer.setCacheLevel(DEFAULT_CACHE_LEVEL_NON_TRANSACTED); } } jmsContainer.setMessageListener(this); // Use Spring BeanFactory to complete the auto-wiring of the JMS Listener Container, // and run the bean lifecycle methods. try { ((AutowireCapableBeanFactory) this.beanFactory).configureBean(this.jmsContainer, "proto-jmsContainer"); } catch (BeansException e) { throw new ConfigurationException(getLogPrefix()+"Out of luck wiring up and configuring Default JMS Message Listener Container for JMS Listener ["+ (getListener().getName()+"]"), e); } // Finally, set bean name to something we can make sense of if (getListener().getName() != null) { jmsContainer.setBeanName(getListener().getName()); } else { jmsContainer.setBeanName(getReceiver().getName()); } } public void start() throws ListenerException { log.debug(getLogPrefix()+"starting"); if (jmsContainer!=null) { try { jmsContainer.start(); } catch (Exception e) { throw new ListenerException(getLogPrefix()+"cannot start", e); } } else { throw new ListenerException(getLogPrefix()+"no jmsContainer defined"); } } public void stop() throws ListenerException { log.debug(getLogPrefix()+"stopping"); if (jmsContainer!=null) { try { jmsContainer.stop(); } catch (Exception e) { throw new ListenerException(getLogPrefix()+"Exception while trying to stop", e); } } else { throw new ListenerException(getLogPrefix()+"no jmsContainer defined"); } } public void onMessage(Message message, Session session) throws JMSException { TransactionStatus txStatus=null; long onMessageStart= System.currentTimeMillis(); long jmsTimestamp= message.getJMSTimestamp(); threadsProcessing.increase(); Thread.currentThread().setName(getReceiver().getName()+"["+threadsProcessing.getValue()+"]"); try { if (TX!=null) { txStatus = txManager.getTransaction(TX); } Map threadContext = new HashMap(); try { IPortConnectedListener listener = getListener(); threadContext.put("session",session); // if (log.isDebugEnabled()) log.debug("transaction status before: "+JtaUtil.displayTransactionStatus()); getReceiver().processRawMessage(listener, message, threadContext); // if (log.isDebugEnabled()) log.debug("transaction status after: "+JtaUtil.displayTransactionStatus()); getReceiver().resetRetryInterval(); } catch (ListenerException e) { getReceiver().increaseRetryIntervalAndWait(e,getLogPrefix()); if (txStatus!=null) { txStatus.setRollbackOnly(); } else { JMSException jmse = new JMSException(getLogPrefix()+"caught exception: "+e.getMessage()); jmse.setLinkedException(e); throw jmse; } // if (JtaUtil.inTransaction()) { // log.warn(getLogPrefix()+"caught exception processing message, setting rollbackonly", e); // JtaUtil.setRollbackOnly(); // } else { // if (jmsContainer.isSessionTransacted()) { // log.warn(getLogPrefix()+"caught exception processing message, rolling back JMS session", e); // session.rollback(); // } else { // JMSException jmse = new JMSException(getLogPrefix()+"caught exception, no transactional stuff to rollback"); // jmse.initCause(e); // throw jmse; // } // } } finally { if (jmsContainer.isSessionTransacted()) { log.debug(getLogPrefix()+"committing JMS session"); session.commit(); } } } finally { if (txStatus!=null) { txManager.commit(txStatus); } threadsProcessing.decrease(); if (log.isInfoEnabled()) { long onMessageEnd= System.currentTimeMillis(); log.info(getLogPrefix()+"A) JMSMessageTime ["+DateUtils.format(jmsTimestamp)+"]"); log.info(getLogPrefix()+"B) onMessageStart ["+DateUtils.format(onMessageStart)+"] diff ["+(onMessageStart-jmsTimestamp)+"]"); log.info(getLogPrefix()+"C) onMessageEnd ["+DateUtils.format(onMessageEnd)+"] diff ["+(onMessageEnd-onMessageStart)+"]"); } // boolean simulateCrashAfterCommit=true; // if (simulateCrashAfterCommit) { // toggle=!toggle; // if (toggle) { // JtaUtil.setRollbackOnly(); // throw new JMSException("simulate crash just before final commit"); // } // } } } // private boolean toggle=true; public void onException(JMSException e) { IbisExceptionListener ibisExceptionListener = getExceptionListener(); if (ibisExceptionListener!= null) { ibisExceptionListener.exceptionThrown(getListener(), e); } else { log.error(getLogPrefix()+"Cannot report the error to an IBIS Exception Listener", e); } } public boolean isThreadCountReadable() { return jmsContainer!=null; } public boolean isThreadCountControllable() { return jmsContainer!=null; } public int getCurrentThreadCount() { if (jmsContainer!=null) { return jmsContainer.getActiveConsumerCount(); } return 0; } public int getMaxThreadCount() { if (jmsContainer!=null) { return jmsContainer.getMaxConcurrentConsumers(); } return 0; } public void increaseThreadCount() { if (jmsContainer!=null) { jmsContainer.setMaxConcurrentConsumers(jmsContainer.getMaxConcurrentConsumers()+1); } } public void decreaseThreadCount() { if (jmsContainer!=null) { int current=getMaxThreadCount(); if (current>1) { jmsContainer.setMaxConcurrentConsumers(current-1); } } } public String getLogPrefix() { String result="SpringJmsContainer "; if (getListener()!=null && getListener().getReceiver()!=null) { result += "of Receiver ["+getListener().getReceiver().getName()+"] "; } return result; } /* (non-Javadoc) * @see org.springframework.beans.factory.BeanFactoryAware#setBeanFactory(org.springframework.beans.factory.BeanFactory) */ public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } public void setTxManager(PlatformTransactionManager txManager) { this.txManager = txManager; } public PlatformTransactionManager getTxManager() { return txManager; } public void setMessageListenerClassName(String messageListenerClassName) { this.messageListenerClassName = messageListenerClassName; } public String getMessageListenerClassName() { return messageListenerClassName; } }
improved logging
JavaSource/nl/nn/adapterframework/unmanaged/SpringJmsConnector.java
improved logging
<ide><path>avaSource/nl/nn/adapterframework/unmanaged/SpringJmsConnector.java <ide> /* <ide> * $Log: SpringJmsConnector.java,v $ <del> * Revision 1.16 2008-08-21 17:56:20 europe\L190409 <add> * Revision 1.17 2008-08-27 16:23:02 europe\L190409 <add> * improved logging <add> * <add> * Revision 1.16 2008/08/21 17:56:20 Gerrit van Brakel <[email protected]> <ide> * removed ifsa specific timing evaluation, that was not working <ide> * <ide> * Revision 1.15 2008/06/30 14:18:27 Gerrit van Brakel <[email protected]> <ide> long onMessageEnd= System.currentTimeMillis(); <ide> <ide> log.info(getLogPrefix()+"A) JMSMessageTime ["+DateUtils.format(jmsTimestamp)+"]"); <del> log.info(getLogPrefix()+"B) onMessageStart ["+DateUtils.format(onMessageStart)+"] diff ["+(onMessageStart-jmsTimestamp)+"]"); <del> log.info(getLogPrefix()+"C) onMessageEnd ["+DateUtils.format(onMessageEnd)+"] diff ["+(onMessageEnd-onMessageStart)+"]"); <add> log.info(getLogPrefix()+"B) onMessageStart ["+DateUtils.format(onMessageStart)+"] diff (~'queing' time) ["+(onMessageStart-jmsTimestamp)+"]"); <add> log.info(getLogPrefix()+"C) onMessageEnd ["+DateUtils.format(onMessageEnd)+"] diff (process time) ["+(onMessageEnd-onMessageStart)+"]"); <ide> } <ide> <ide> // boolean simulateCrashAfterCommit=true;
Java
apache-2.0
6cbf3d2517da2120f4b21c3a7a4dc241fd1c5a4e
0
teetime-framework/teetime,teetime-framework/teetime,ChristianWulf/teetime,ChristianWulf/teetime
package teetime.stage.taskfarm; import teetime.framework.AbstractCompositeStage; import teetime.framework.ConfigurationContext; import teetime.framework.InputPort; import teetime.framework.OutputPort; import teetime.framework.exceptionHandling.TaskFarmInvalidPipeException; import teetime.framework.pipe.IMonitorablePipe; import teetime.framework.pipe.IPipe; public class TaskFarmStage<I, O, TFS extends TaskFarmDuplicable<I, O>> extends AbstractCompositeStage { private final TaskFarmConfiguration<I, O, TFS> configuration; public TaskFarmStage(final TFS workerStage, final ConfigurationContext context) { super(context); configuration = new TaskFarmConfiguration<I, O, TFS>(workerStage); init(workerStage); } public InputPort<I> getInputPort() { return configuration.getDistributor().getInputPort(); } public OutputPort<O> getOutputPort() { return configuration.getMerger().getOutputPort(); } private void init(final TFS includedStage) { addThreadableStage(configuration.getMerger()); addThreadableStage(configuration.getFirstStage().getInputPort().getOwningStage()); InputPort<I> stageInputPort = includedStage.getInputPort(); connectPorts(configuration.getDistributor().getNewOutputPort(), stageInputPort); OutputPort<O> stageOutputPort = includedStage.getOutputPort(); connectPorts(stageOutputPort, configuration.getMerger().getNewInputPort()); // TODO: Check pipes at start somehow... Here, it would only be an InstantiationPipe. // checkIfPipeIsMonitorable(stageInputPort.getPipe()); // checkIfPipeIsMonitorable(stageOutputPort.getPipe()); configuration.getTriples().add(new TaskFarmTriple<I, O, TFS>( stageInputPort.getPipe(), stageOutputPort.getPipe(), includedStage)); } private void checkIfPipeIsMonitorable(final IPipe pipe) { if (!(pipe instanceof IMonitorablePipe)) { throw new TaskFarmInvalidPipeException("Pipe is not monitorable, which is required for a Task Farm. Instead \"" + pipe.getClass().getSimpleName() + "\" was used."); } } public TaskFarmConfiguration<I, O, TFS> getConfiguration() { return this.configuration; } }
src/main/java/teetime/stage/taskfarm/TaskFarmStage.java
package teetime.stage.taskfarm; import teetime.framework.AbstractCompositeStage; import teetime.framework.ConfigurationContext; import teetime.framework.InputPort; import teetime.framework.OutputPort; import teetime.framework.exceptionHandling.TaskFarmInvalidPipeException; import teetime.framework.pipe.IMonitorablePipe; import teetime.framework.pipe.IPipe; public class TaskFarmStage<I, O, TFS extends TaskFarmDuplicable<I, O>> extends AbstractCompositeStage { private final TaskFarmConfiguration<I, O, TFS> configuration; public TaskFarmStage(final TFS workerStage, final ConfigurationContext context) { super(context); configuration = new TaskFarmConfiguration<I, O, TFS>(workerStage); init(workerStage); } public InputPort<I> getInputPort() { return configuration.getDistributor().getInputPort(); } public OutputPort<O> getOutputPort() { return configuration.getMerger().getOutputPort(); } private void init(final TFS includedStage) { addThreadableStage(configuration.getMerger()); addThreadableStage(configuration.getFirstStage().getInputPort().getOwningStage()); InputPort<I> stageInputPort = includedStage.getInputPort(); connectPorts(configuration.getDistributor().getNewOutputPort(), stageInputPort); OutputPort<O> stageOutputPort = includedStage.getOutputPort(); connectPorts(stageOutputPort, configuration.getMerger().getNewInputPort()); // TODO: Check pipes at start somehow... Here, it would only be an InstantiationPipe. // checkIfPipeIsMonitorable(stageInputPort.getPipe()); // checkIfPipeIsMonitorable(stageOutputPort.getPipe()); // configuration.getTriples().add(new TaskFarmTriple<I, O, TFS>( // (IMonitorablePipe) stageInputPort.getPipe(), // (IMonitorablePipe) stageOutputPort.getPipe(), // includedStage)); } private void checkIfPipeIsMonitorable(final IPipe pipe) { if (!(pipe instanceof IMonitorablePipe)) { throw new TaskFarmInvalidPipeException("Pipe is not monitorable, which is required for a Task Farm. Instead \"" + pipe.getClass().getSimpleName() + "\" was used."); } } public TaskFarmConfiguration<I, O, TFS> getConfiguration() { return this.configuration; } }
TFS now adds first stage + pipes to triples
src/main/java/teetime/stage/taskfarm/TaskFarmStage.java
TFS now adds first stage + pipes to triples
<ide><path>rc/main/java/teetime/stage/taskfarm/TaskFarmStage.java <ide> // TODO: Check pipes at start somehow... Here, it would only be an InstantiationPipe. <ide> // checkIfPipeIsMonitorable(stageInputPort.getPipe()); <ide> // checkIfPipeIsMonitorable(stageOutputPort.getPipe()); <del> // configuration.getTriples().add(new TaskFarmTriple<I, O, TFS>( <del> // (IMonitorablePipe) stageInputPort.getPipe(), <del> // (IMonitorablePipe) stageOutputPort.getPipe(), <del> // includedStage)); <add> <add> configuration.getTriples().add(new TaskFarmTriple<I, O, TFS>( <add> stageInputPort.getPipe(), <add> stageOutputPort.getPipe(), <add> includedStage)); <ide> } <ide> <ide> private void checkIfPipeIsMonitorable(final IPipe pipe) {
JavaScript
mit
7e46efcd12cbc911900d41903347e60d5ff03ed5
0
HiFaraz/identity-desk
'use strict'; /** * Module dependencies. */ import { ACCEPTED, OK, SEE_OTHER } from 'http-codes'; import { Router } from 'express'; import { clone } from 'lodash'; import { STATUS_CODES as httpCodeMessage } from 'http'; import queryString from 'querystring'; import request from 'request-promise'; import url from 'url'; module.exports = class CorePOSTAuthenticator { /** * @param {string} name * @param {Object} config * @param {Object} dependencies */ constructor(name, config, dependencies) { this.debug = require('debug')( `identity-desk:authentication:authenticator:${name}`, ); this.dependencies = dependencies; this.name = name; this.router = Router(); this.config = clone(config); this.debug('initializing'); this.router.post( '/', async (req, res, next) => { this.debug('new request', req.path, req.body); const middleware = { authenticator: () => (req, res, next) => { this.debug('enter hub request handler'); return this.hubToAuthenticator()(req, res, next); }, hub: this.clientToHub.bind(this), }[req.body[config.authenticatorTargetParameter]]; if (middleware) { return middleware()(req, res, next); } else { return next(); } }, this.dependencies.session, this.appToClient(), ); } appToClient() { const { config, debug } = this; return async function(req, res, next) { debug('enter app request handler'); try { const middlewareTarget = { [config.authenticatorTargetParameter]: 'hub', }; const { body: user, statusCode } = await post( formatURL(req), Object.assign({}, req.body, middlewareTarget), ); debug('hub middleware responded', formatURL(req), statusCode, user); if ([ACCEPTED, OK].includes(statusCode)) { // ACCEPTED can be used by magic link authenticators, which use a non-HTTP protocal (like Email or other platforms) to deliver the magic link if (statusCode === OK) { req.identityDesk.set({ user }); } res.redirect(SEE_OTHER, config.successRedirect); // SEE OTHER (303) is the spec for a GET redirect from a POST request, though most browsers allow FOUND (302) as well (technically this is not allowed) } else { const query = queryString.stringify({ reason: httpCodeMessage[statusCode], }); res.redirect(SEE_OTHER, `${config.failureRedirect}?${query}`); // SEE OTHER (303) is the spec for a GET redirect from a POST request, though most browsers allow FOUND (302) as well (technically this is not allowed) } } catch (error) { debug('error when making a POST request to hub middleware', error); next(error); } }; } clientToHub() { const { config, debug, dependencies, name } = this; return async function(req, res, next) { debug('enter client request handler'); try { const middlewareTarget = { [config.authenticatorTargetParameter]: 'authenticator', }; const { body: account, statusCode } = await post( formatURL(req), Object.assign({}, req.body, middlewareTarget), ); debug( 'authenticator middleware responded', formatURL(req), statusCode, account, ); // TODO consider storing the login attempt in the DB // TODO this is where we need to consider on-boarding and checking links with the master identity const { Authentication$Account, Core$Identity, } = dependencies.database.models; const identity = await Core$Identity.findOne({ attributes: ['id'], include: [ { attributes: [], model: Authentication$Account, where: { authenticatorAccountId: account.id, // authenticator must return an id authenticatorName: name, }, }, ], raw: true, }); // return the minimum to record successful authentication, rest can be queried by applications later res.status(statusCode).json( statusCode === OK ? { account, authenticator: name, id: identity.id, // master user ID internal to the hub, not the authenticator user ID // TODO replace with real ID from DB lookup } : {}, ); } catch (error) { debug( 'error when making a POST request to authenticator middleware', error, ); next(error); } }; } /** * Override this with your authenticator route * Do not put your authenticator route in the constructor */ hubToAuthenticator() { /** * Example code: * * return (req, res, next) => { * * } */ } }; /** * Send a POST request * * @param {string} uri * @param {Object} body * @return {Object} */ function post(uri, body) { return request({ // unless statusCode is 200, body = {} body, json: true, // encodes/stringifies the request body as JSON method: 'POST', resolveWithFullResponse: true, // return more than just the response body simple: false, // do not throw on non 2xx HTTP codes uri, }); } /** * Format a URL * * @param {IncomingMessage} req * @param {Object} query * @return {string} */ function formatURL(req, query) { // discards original query parameters // to keep them, make sure to provide them in `query` return url.format({ host: req.headers.host, pathname: req.originalUrl.split('?')[0], protocol: req.protocol, query, }); }
src/authentication/authenticator/post.js
'use strict'; /** * Module dependencies. */ import { ACCEPTED, OK, SEE_OTHER } from 'http-codes'; import { Router } from 'express'; import { clone } from 'lodash'; import { STATUS_CODES as httpCodeMessage } from 'http'; import queryString from 'querystring'; import request from 'request-promise'; import url from 'url'; module.exports = class CorePOSTAuthenticator { /** * @param {string} name * @param {Object} config * @param {Object} dependencies */ constructor(name, config, dependencies) { this.debug = require('debug')( `identity-desk:authentication:authenticator:${name}`, ); this.dependencies = dependencies; this.name = name; this.router = Router(); this.config = clone(config); this.debug('initializing'); this.router.post( '/', async (req, res, next) => { this.debug('new request', req.path, req.body); const middleware = { authenticator: () => (req, res, next) => { this.debug('enter hub request handler'); return this.hubToAuthenticator()(req, res, next); }, hub: this.clientToHub.bind(this), }[req.body[config.authenticatorTargetParameter]]; if (middleware) { return middleware()(req, res, next); } else { return next(); } }, this.dependencies.session, this.appToClient(), ); } appToClient() { const { config, debug } = this; return async function(req, res, next) { debug('enter app request handler'); try { const middlewareTarget = { [config.authenticatorTargetParameter]: 'hub', }; const { body: user, statusCode } = await post( formatURL(req), Object.assign({}, req.body, middlewareTarget), ); debug('hub middleware responded', formatURL(req), statusCode, user); if ([ACCEPTED, OK].includes(statusCode)) { // ACCEPTED can be used by magic link authenticators, which use a non-HTTP protocal (like Email or other platforms) to deliver the magic link if (statusCode === OK) { req.identityDesk.set({ user }); } res.redirect(SEE_OTHER, config.successRedirect); // SEE OTHER (303) is the spec for a GET redirect from a POST request, though most browsers allow FOUND (302) as well (technically this is not allowed) } else { const query = queryString.stringify({ reason: httpCodeMessage[statusCode], }); res.redirect(SEE_OTHER, `${config.failureRedirect}?${query}`); // SEE OTHER (303) is the spec for a GET redirect from a POST request, though most browsers allow FOUND (302) as well (technically this is not allowed) } } catch (error) { debug('error when making a POST request to hub middleware', error); next(error); } }; } clientToHub() { const { config, debug, dependencies, name } = this; return async function(req, res, next) { debug('enter client request handler'); try { const middlewareTarget = { [config.authenticatorTargetParameter]: 'authenticator', }; const { body: account, statusCode } = await post( formatURL(req), Object.assign({}, req.body, middlewareTarget), ); debug( 'authenticator middleware responded', formatURL(req), statusCode, account, ); // TODO consider storing the login attempt in the DB // TODO this is where we need to consider on-boarding and checking links with the master identity const { Authentication$Account, Core$Identity, } = dependencies.database.models; const identity = await Core$Identity.findOne({ attributes: ['id'], include: [ { attributes: [], model: Authentication$Account, where: { authenticatorAccountId: account.id, authenticatorName: name, }, }, ], raw: true, }); res.status(statusCode).json( statusCode === OK ? { id: identity.id, // master user ID internal to the hub, not the authenticator user ID // TODO replace with real ID from DB lookup [name]: account, // TODO attach linked users from all other authenticators before sending } : {}, ); } catch (error) { debug( 'error when making a POST request to authenticator middleware', error, ); next(error); } }; } /** * Override this with your authenticator route * Do not put your authenticator route in the constructor */ hubToAuthenticator() { /** * Example code: * * return (req, res, next) => { * * } */ } }; /** * Send a POST request * * @param {string} uri * @param {Object} body * @return {Object} */ function post(uri, body) { return request({ // unless statusCode is 200, body = {} body, json: true, // encodes/stringifies the request body as JSON method: 'POST', resolveWithFullResponse: true, // return more than just the response body simple: false, // do not throw on non 2xx HTTP codes uri, }); } /** * Format a URL * * @param {IncomingMessage} req * @param {Object} query * @return {string} */ function formatURL(req, query) { // discards original query parameters // to keep them, make sure to provide them in `query` return url.format({ host: req.headers.host, pathname: req.originalUrl.split('?')[0], protocol: req.protocol, query, }); }
Simplify authenticator success payload to client Remove concept of merging all linked accounts into the payload, keep it to the minimum
src/authentication/authenticator/post.js
Simplify authenticator success payload to client
<ide><path>rc/authentication/authenticator/post.js <ide> attributes: [], <ide> model: Authentication$Account, <ide> where: { <del> authenticatorAccountId: account.id, <add> authenticatorAccountId: account.id, // authenticator must return an id <ide> authenticatorName: name, <ide> }, <ide> }, <ide> raw: true, <ide> }); <ide> <add> // return the minimum to record successful authentication, rest can be queried by applications later <ide> res.status(statusCode).json( <ide> statusCode === OK <ide> ? { <add> account, <add> authenticator: name, <ide> id: identity.id, // master user ID internal to the hub, not the authenticator user ID // TODO replace with real ID from DB lookup <del> [name]: account, // TODO attach linked users from all other authenticators before sending <ide> } <ide> : {}, <ide> );
Java
apache-2.0
error: pathspec 'formats/src/main/java/au/gov/amsa/util/netcdf/NetCdfWriter.java' did not match any file(s) known to git
74fd7d9a04ec78ca0b35d9f3d4073047644573a7
1
amsa-code/risky,amsa-code/risky,amsa-code/risky,amsa-code/risky,amsa-code/risky
package au.gov.amsa.util.netcdf; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.function.Function; import ucar.ma2.DataType; import ucar.nc2.Attribute; import ucar.nc2.Dimension; import ucar.nc2.NetcdfFileWriter; import ucar.nc2.NetcdfFileWriter.Version; import ucar.nc2.Variable; import com.google.common.base.Optional; public class NetCdfWriter { private final NetcdfFileWriter f; private final Map<String, Var<?, ?>> variables = new HashMap<>(); private final int numRecords; public NetCdfWriter(File file, int numRecords) { this.numRecords = numRecords; try { f = NetcdfFileWriter.createNew(Version.netcdf3, file.getPath()); // add version attribute f.addGroupAttribute(null, new Attribute("version", "0.1")); } catch (IOException e) { throw new RuntimeException(e); } } public <T, R> Var<T, R> addVariable(String standardName, Optional<String> longName, Optional<String> units, Optional<String> encoding, Class<R> cls, Function<? super T, R> function) { Dimension dimension = f.addDimension(null, standardName, numRecords); Variable variable = f.addVariable(null, standardName, toDataType(cls), Arrays.asList(dimension)); if (units.isPresent()) variable.addAttribute(new Attribute("units", units.get())); if (units.isPresent()) variable.addAttribute(new Attribute("encoding", encoding.get())); return new Var<T, R>(variable, function); } public <T, R> void write(Var<T, R> variable, T record) { } private static DataType toDataType(Class<?> cls) { return DataType.DOUBLE; } public static class Var<T, R> { private final Variable variable; private final Function<? super T, R> function; public Var(Variable variable, Function<? super T, R> function) { this.variable = variable; this.function = function; } public Variable variable() { return variable; } public Function<? super T, R> function() { return function; } } }
formats/src/main/java/au/gov/amsa/util/netcdf/NetCdfWriter.java
netcdfwriter dev
formats/src/main/java/au/gov/amsa/util/netcdf/NetCdfWriter.java
netcdfwriter dev
<ide><path>ormats/src/main/java/au/gov/amsa/util/netcdf/NetCdfWriter.java <add>package au.gov.amsa.util.netcdf; <add> <add>import java.io.File; <add>import java.io.IOException; <add>import java.util.Arrays; <add>import java.util.HashMap; <add>import java.util.Map; <add>import java.util.function.Function; <add> <add>import ucar.ma2.DataType; <add>import ucar.nc2.Attribute; <add>import ucar.nc2.Dimension; <add>import ucar.nc2.NetcdfFileWriter; <add>import ucar.nc2.NetcdfFileWriter.Version; <add>import ucar.nc2.Variable; <add> <add>import com.google.common.base.Optional; <add> <add>public class NetCdfWriter { <add> <add> private final NetcdfFileWriter f; <add> private final Map<String, Var<?, ?>> variables = new HashMap<>(); <add> private final int numRecords; <add> <add> public NetCdfWriter(File file, int numRecords) { <add> this.numRecords = numRecords; <add> try { <add> f = NetcdfFileWriter.createNew(Version.netcdf3, file.getPath()); <add> // add version attribute <add> f.addGroupAttribute(null, new Attribute("version", "0.1")); <add> } catch (IOException e) { <add> throw new RuntimeException(e); <add> } <add> } <add> <add> public <T, R> Var<T, R> addVariable(String standardName, Optional<String> longName, <add> Optional<String> units, Optional<String> encoding, Class<R> cls, <add> Function<? super T, R> function) { <add> Dimension dimension = f.addDimension(null, standardName, numRecords); <add> Variable variable = f.addVariable(null, standardName, toDataType(cls), <add> Arrays.asList(dimension)); <add> if (units.isPresent()) <add> variable.addAttribute(new Attribute("units", units.get())); <add> if (units.isPresent()) <add> variable.addAttribute(new Attribute("encoding", encoding.get())); <add> return new Var<T, R>(variable, function); <add> } <add> <add> public <T, R> void write(Var<T, R> variable, T record) { <add> <add> } <add> <add> private static DataType toDataType(Class<?> cls) { <add> return DataType.DOUBLE; <add> } <add> <add> public static class Var<T, R> { <add> <add> private final Variable variable; <add> private final Function<? super T, R> function; <add> <add> public Var(Variable variable, Function<? super T, R> function) { <add> this.variable = variable; <add> this.function = function; <add> } <add> <add> public Variable variable() { <add> return variable; <add> } <add> <add> public Function<? super T, R> function() { <add> return function; <add> } <add> <add> } <add> <add>}
Java
mit
6dd65a7252c6486e26769dc9a611d6127e927309
0
sunshinezxf/Selling,sunshinezxf/Selling,sunshinezxf/Selling
package selling.sunshine.controller; import org.apache.shiro.SecurityUtils; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import selling.sunshine.form.CustomerForm; import selling.sunshine.model.Agent; import selling.sunshine.model.Customer; import selling.sunshine.model.User; import selling.sunshine.pagination.DataTablePage; import selling.sunshine.pagination.DataTableParam; import selling.sunshine.service.CustomerService; import selling.sunshine.utils.ResponseCode; import selling.sunshine.utils.ResultData; import javax.validation.Valid; /** * Created by sunshine on 4/11/16. */ @RequestMapping("/customer") @RestController public class CustomerController { @Autowired private CustomerService customerService; @RequestMapping(method = RequestMethod.GET, value = "/overview") public ModelAndView overview() { ModelAndView view = new ModelAndView(); view.setViewName("/backend/customer/overview"); return view; } @ResponseBody @RequestMapping(method = RequestMethod.POST, value = "/overview") public DataTablePage<Customer> overview(DataTableParam param) { DataTablePage<Customer> page = new DataTablePage<Customer>(); return page; } @ResponseBody @RequestMapping(method = RequestMethod.POST, value = "/add") public ResultData addCustomer(@Valid CustomerForm customerForm, BindingResult result) { ResultData resultData = new ResultData(); if (result.hasErrors()) { resultData.setResponseCode(ResponseCode.RESPONSE_ERROR); return resultData; } Subject subject = SecurityUtils.getSubject(); Agent agent = null; if (subject != null) { Session session = subject.getSession(); User user = (User) session.getAttribute("current"); agent = user.getAgent(); } Customer customer = new Customer(customerForm.getName(), customerForm.getAddress(), customerForm.getPhone(), agent); resultData = customerService.createCustomer(customer); return resultData; } @ResponseBody @RequestMapping(method = RequestMethod.POST, value = "/modify") public ResultData updateCustomer() { ResultData result = new ResultData(); return result; } }
src/main/java/selling/sunshine/controller/CustomerController.java
package selling.sunshine.controller; import org.apache.shiro.SecurityUtils; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import selling.sunshine.form.CustomerForm; import selling.sunshine.model.Agent; import selling.sunshine.model.Customer; import selling.sunshine.model.User; import selling.sunshine.service.CustomerService; import selling.sunshine.utils.ResponseCode; import selling.sunshine.utils.ResultData; import javax.validation.Valid; /** * Created by sunshine on 4/11/16. */ @RequestMapping("/customer") @RestController public class CustomerController { @Autowired private CustomerService customerService; @RequestMapping(method = RequestMethod.GET, value = "/overview") public ModelAndView overview() { ModelAndView view = new ModelAndView(); view.setViewName("/backend/customer/overview"); return view; } @ResponseBody @RequestMapping(method = RequestMethod.POST, value = "/add") public ResultData addCustomer(@Valid CustomerForm customerForm, BindingResult result) { ResultData resultData = new ResultData(); if (result.hasErrors()) { resultData.setResponseCode(ResponseCode.RESPONSE_ERROR); return resultData; } Subject subject = SecurityUtils.getSubject(); Agent agent = null; if (subject != null) { Session session = subject.getSession(); User user = (User) session.getAttribute("current"); agent = user.getAgent(); } Customer customer = new Customer(customerForm.getName(), customerForm.getAddress(), customerForm.getPhone(), agent); resultData = customerService.createCustomer(customer); return resultData; } @ResponseBody @RequestMapping(method = RequestMethod.POST, value = "/modify") public ResultData updateCustomer() { ResultData result = new ResultData(); return result; } }
add interface customer overview for post method
src/main/java/selling/sunshine/controller/CustomerController.java
add interface customer overview for post method
<ide><path>rc/main/java/selling/sunshine/controller/CustomerController.java <ide> import selling.sunshine.model.Agent; <ide> import selling.sunshine.model.Customer; <ide> import selling.sunshine.model.User; <add>import selling.sunshine.pagination.DataTablePage; <add>import selling.sunshine.pagination.DataTableParam; <ide> import selling.sunshine.service.CustomerService; <ide> import selling.sunshine.utils.ResponseCode; <ide> import selling.sunshine.utils.ResultData; <ide> ModelAndView view = new ModelAndView(); <ide> view.setViewName("/backend/customer/overview"); <ide> return view; <add> } <add> <add> @ResponseBody <add> @RequestMapping(method = RequestMethod.POST, value = "/overview") <add> public DataTablePage<Customer> overview(DataTableParam param) { <add> DataTablePage<Customer> page = new DataTablePage<Customer>(); <add> <add> return page; <ide> } <ide> <ide> @ResponseBody
Java
mit
931d4dd8a11313dd31666eaee2fe76605c2c76e6
0
tobiatesan/serleena-android,tobiatesan/serleena-android
/////////////////////////////////////////////////////////////////////////////// // // This file is part of Serleena. // // The MIT License (MIT) // // Copyright (C) 2015 Antonio Cavestro, Gabriele Pozzan, Matteo Lisotto, // Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// /** * Name: ExperienceSelectionPresenterTest.java * Package: com.kyloth.serleena.presenters; * Author: Gabriele Pozzan * * History: * Version Programmer Changes * 1.0.0 Gabriele Pozzan Creazione file scrittura * codice e documentazione Javadoc */ package com.kyloth.serleena.presenters; import org.junit.Test; import org.junit.Before; import org.junit.Rule; import org.junit.rules.ExpectedException; import static org.mockito.Mockito.*; import static org.junit.Assert.*; import java.util.ArrayList; import com.kyloth.serleena.model.IExperience; import com.kyloth.serleena.model.ISerleenaDataSource; import com.kyloth.serleena.presentation.IExperienceSelectionPresenter; import com.kyloth.serleena.presentation.IExperienceSelectionView; import com.kyloth.serleena.presentation.ISerleenaActivity; /** * Contiene i test di unità per la classe ExperienceSelectionPresenter. * * @author Gabriele Pozzan <[email protected]> * @version 1.0.0 */ public class ExperienceSelectionPresenterTest { private ISerleenaActivity activity; private IExperienceSelectionView view; private ISerleenaDataSource source; private IExperience exp_1; private IExperience exp_2; private IExperience exp_3; private ArrayList<IExperience> exp_list; @Rule public ExpectedException exception = ExpectedException.none(); /** * Inizializza i campi dati necessari a condurre i test. */ @Before public void initialize() { activity = mock(ISerleenaActivity.class); view = mock(IExperienceSelectionView.class); source = mock(ISerleenaDataSource.class); exp_1 = mock(IExperience.class); exp_2 = mock(IExperience.class); exp_3 = mock(IExperience.class); exp_list = new ArrayList<IExperience>(); exp_list.add(exp_1); exp_list.add(exp_2); exp_list.add(exp_3); when(activity.getDataSource()).thenReturn(source); when(source.getExperiences()).thenReturn(exp_list); } /** * Verifica che il costruttore lanci un'eccezione IllegalArgumentException * al tentativo di costruire un oggetto con view nulla. */ @Test(expected = IllegalArgumentException.class) public void constructorShouldThrowExceptionWhenNnullView() { new ExperienceSelectionPresenter(null, activity); } /** * Verifica che il costruttore lanci un'eccezione IllegalArgumentException * al tentativo di costruire un oggetto con activity nulla. */ @Test(expected = IllegalArgumentException.class) public void constructorShouldThrowExceptionWhenNullActivity() { new ExperienceSelectionPresenter(view, null); } /** * Verifica che il costruttore lanci un'eccezione IllegalArgumentException * al tentativo di costruire un oggetto con entrambi i parametri null. */ @Test(expected = IllegalArgumentException.class) public void constructorShouldThrowExceptionWhenNullArguments() { new ExperienceSelectionPresenter(null, null); } }
serleena/app/src/test/java/com/kyloth/serleena/presenters/ExperienceSelectionPresenterTest.java
/////////////////////////////////////////////////////////////////////////////// // // This file is part of Serleena. // // The MIT License (MIT) // // Copyright (C) 2015 Antonio Cavestro, Gabriele Pozzan, Matteo Lisotto, // Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// /** * Name: ExperienceSelectionPresenterTest.java * Package: com.kyloth.serleena.presenters; * Author: Gabriele Pozzan * * History: * Version Programmer Changes * 1.0.0 Gabriele Pozzan Creazione file scrittura * codice e documentazione Javadoc */ package com.kyloth.serleena.presenters; import org.junit.Test; import org.junit.Before; import org.junit.Rule; import org.junit.rules.ExpectedException; import static org.mockito.Mockito.*; import static org.junit.Assert.*; import java.util.ArrayList; import com.kyloth.serleena.model.IExperience; import com.kyloth.serleena.model.ISerleenaDataSource; import com.kyloth.serleena.presentation.IExperienceSelectionPresenter; import com.kyloth.serleena.presentation.IExperienceSelectionView; import com.kyloth.serleena.presentation.ISerleenaActivity; /** * Contiene i test di unità per la classe ExperienceSelectionPresenter. * * @author Gabriele Pozzan <[email protected]> * @version 1.0.0 */ public class ExperienceSelectionPresenterTest { private ISerleenaActivity activity; private IExperienceSelectionView view; private ISerleenaDataSource source; private IExperience exp_1; private IExperience exp_2; private IExperience exp_3; private ArrayList<IExperience> exp_list; @Rule public ExpectedException exception = ExpectedException.none(); /** * Inizializza i campi dati necessari a condurre i test. */ @Before public void initialize() { activity = mock(ISerleenaActivity.class); view = mock(IExperienceSelectionView.class); source = mock(ISerleenaDataSource.class); exp_1 = mock(IExperience.class); exp_2 = mock(IExperience.class); exp_3 = mock(IExperience.class); exp_list = new ArrayList<IExperience>(); exp_list.add(exp_1); exp_list.add(exp_2); exp_list.add(exp_3); when(activity.getDataSource()).thenReturn(source); when(source.getExperiences()).thenReturn(exp_list); } /** * Verifica che il costruttore lanci un'eccezione IllegalArgumentException * al tentativo di costruire un oggetto con view nulla. */ @Test(expected = IllegalArgumentException.class) public void constructorShouldThrowExceptionWhenNnullView() { new ExperienceSelectionPresenter(null, activity); } /** * Verifica che il costruttore lanci un'eccezione IllegalArgumentException * al tentativo di costruire un oggetto con activity nulla. */ @Test(expected = IllegalArgumentException.class) public void constructorShouldThrowExceptionWhenNullActivity() { new ExperienceSelectionPresenter(view, null); } }
PRES/TEST: Aggiungi test in ExperienceSelectionPresenterTest Viene aggiungo un test di null check sul costruttore di oggetto ExperienceSelectionPresenterTest
serleena/app/src/test/java/com/kyloth/serleena/presenters/ExperienceSelectionPresenterTest.java
PRES/TEST: Aggiungi test in ExperienceSelectionPresenterTest
<ide><path>erleena/app/src/test/java/com/kyloth/serleena/presenters/ExperienceSelectionPresenterTest.java <ide> new ExperienceSelectionPresenter(view, null); <ide> } <ide> <add> /** <add> * Verifica che il costruttore lanci un'eccezione IllegalArgumentException <add> * al tentativo di costruire un oggetto con entrambi i parametri null. <add> */ <add> @Test(expected = IllegalArgumentException.class) <add> public void constructorShouldThrowExceptionWhenNullArguments() { <add> new ExperienceSelectionPresenter(null, null); <add> } <add> <ide> }
Java
apache-2.0
30b70f64b9deeecb20398ef8eecd3969ffdedecd
0
alexeyzyabkin/matinee,alexeyzyabkin/matinee
package com.letionik.matinee.config; import org.hibernate.jpa.HibernatePersistenceProvider; import org.modelmapper.AbstractConverter; import org.modelmapper.ModelMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.PropertiesLoaderUtils; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.util.StringUtils; import javax.annotation.Resource; import javax.sql.DataSource; import java.io.IOException; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; import java.util.Properties; /** * Created by Alexey Zyabkin on 20.09.2015. */ @Configuration @EnableTransactionManagement @EnableJpaRepositories("com.letionik.matinee.repository") public class DataConfig { private static final Logger log = LoggerFactory.getLogger(DataConfig.class); private static final String STAND_SYSTEM_PROPERTY_NAME = "stand"; private static final String DEV_PROPERTIES_PATH_TEMPLATE = "/dev/{stand}.properties"; private static final String PROP_DATABASE_DRIVER = "db.driver"; private static final String PROP_DATABASE_PASSWORD = "db.password"; private static final String PROP_DATABASE_URL = "db.url"; private static final String PROP_DATABASE_USERNAME = "db.username"; private static final String PROP_HIBERNATE_DIALECT = "hibernate.dialect"; private static final String PROP_HIBERNATE_SHOW_SQL = "hibernate.show_sql"; private static final String PROP_ENTITY_MANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan"; private static final String PROP_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto"; private static final String OPENSHIFT_MYSQL_DB_USERNAME = "OPENSHIFT_MYSQL_DB_USERNAME"; private static final String OPENSHIFT_MYSQL_DB_PASSWORD = "OPENSHIFT_MYSQL_DB_PASSWORD"; private static final String OPENSHIFT_MYSQL_DB_HOST = "OPENSHIFT_MYSQL_DB_HOST"; private static final String OPENSHIFT_MYSQL_DB_PORT = "OPENSHIFT_MYSQL_DB_PORT"; private static final String OPENSHIFT_APP_NAME = "OPENSHIFT_APP_NAME"; private static final String DB_CONNECTION_PATTERN = "jdbc:mysql://%s:%s/%s"; @Resource private Environment env; @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(env.getRequiredProperty(PROP_DATABASE_DRIVER)); boolean testPhase = !StringUtils.isEmpty(env.getProperty(PROP_DATABASE_URL)); if (testPhase) { dataSource.setUrl(env.getRequiredProperty(PROP_DATABASE_URL)); dataSource.setUsername(env.getRequiredProperty(PROP_DATABASE_USERNAME)); dataSource.setPassword(env.getRequiredProperty(PROP_DATABASE_PASSWORD)); } else { String stand = env.getProperty(STAND_SYSTEM_PROPERTY_NAME); if (StringUtils.isEmpty(stand)) { dataSource.setUrl(String.format(DB_CONNECTION_PATTERN, env.getRequiredProperty(OPENSHIFT_MYSQL_DB_HOST), env.getRequiredProperty(OPENSHIFT_MYSQL_DB_PORT), env.getRequiredProperty(OPENSHIFT_APP_NAME))); dataSource.setUsername(env.getRequiredProperty(OPENSHIFT_MYSQL_DB_USERNAME)); dataSource.setPassword(env.getRequiredProperty(OPENSHIFT_MYSQL_DB_PASSWORD)); } else { try { Properties devProperties = PropertiesLoaderUtils.loadProperties(new ClassPathResource(DEV_PROPERTIES_PATH_TEMPLATE.replace("{stand}", stand))); dataSource.setUrl(devProperties.getProperty(PROP_DATABASE_URL)); dataSource.setUsername(devProperties.getProperty(PROP_DATABASE_USERNAME)); dataSource.setPassword(devProperties.getProperty(PROP_DATABASE_PASSWORD)); } catch (IOException e) { log.error("Can not read the file with developer's settings. Stand : " + stand, e); } } } return dataSource; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); entityManagerFactoryBean.setDataSource(dataSource()); entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class); entityManagerFactoryBean.setPackagesToScan(env.getRequiredProperty(PROP_ENTITY_MANAGER_PACKAGES_TO_SCAN)); entityManagerFactoryBean.setJpaProperties(getHibernateProperties()); return entityManagerFactoryBean; } @Bean public JpaTransactionManager transactionManager() { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); return transactionManager; } @Bean public ModelMapper modelMapper() { ModelMapper modelMapper = new ModelMapper(); modelMapper.addConverter(new AbstractConverter<Date, LocalDateTime>() { @Override protected LocalDateTime convert(Date source) { if (source == null) return null; return LocalDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault()); } }); modelMapper.addConverter(new AbstractConverter<LocalDateTime, Date>() { @Override protected Date convert(LocalDateTime source) { if (source == null) return null; return Date.from(source.atZone(ZoneId.systemDefault()).toInstant()); } }); return modelMapper; } private Properties getHibernateProperties() { Properties properties = new Properties(); properties.put(PROP_HIBERNATE_DIALECT, env.getRequiredProperty(PROP_HIBERNATE_DIALECT)); properties.put(PROP_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROP_HIBERNATE_SHOW_SQL)); properties.put(PROP_HIBERNATE_HBM2DDL_AUTO, env.getRequiredProperty(PROP_HIBERNATE_HBM2DDL_AUTO)); return properties; } }
backend/src/main/java/com/letionik/matinee/config/DataConfig.java
package com.letionik.matinee.config; import org.hibernate.jpa.HibernatePersistenceProvider; import org.modelmapper.AbstractConverter; import org.modelmapper.ModelMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.PropertiesLoaderUtils; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.util.StringUtils; import javax.annotation.Resource; import javax.sql.DataSource; import java.io.IOException; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; import java.util.Properties; /** * Created by Alexey Zyabkin on 20.09.2015. */ @Configuration @EnableTransactionManagement @EnableJpaRepositories("com.letionik.matinee.repository") public class DataConfig { private static final Logger log = LoggerFactory.getLogger(DataConfig.class); private static final String STAND_SYSTEM_PROPERTY_NAME = "stand"; private static final String DEV_PROPERTIES_PATH_TEMPLATE = "/dev/{stand}.properties"; private static final String PROP_DATABASE_DRIVER = "db.driver"; private static final String PROP_DATABASE_PASSWORD = "db.password"; private static final String PROP_DATABASE_URL = "db.url"; private static final String PROP_DATABASE_USERNAME = "db.username"; private static final String PROP_HIBERNATE_DIALECT = "hibernate.dialect"; private static final String PROP_HIBERNATE_SHOW_SQL = "hibernate.show_sql"; private static final String PROP_ENTITY_MANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan"; private static final String PROP_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto"; private static final String OPENSHIFT_MYSQL_DB_USERNAME = "OPENSHIFT_MYSQL_DB_USERNAME"; private static final String OPENSHIFT_MYSQL_DB_PASSWORD = "OPENSHIFT_MYSQL_DB_PASSWORD"; private static final String OPENSHIFT_MYSQL_DB_HOST = "OPENSHIFT_MYSQL_DB_HOST"; private static final String OPENSHIFT_MYSQL_DB_PORT = "OPENSHIFT_MYSQL_DB_PORT"; private static final String OPENSHIFT_APP_NAME = "OPENSHIFT_APP_NAME"; private static final String DB_CONNECTION_PATTERN = "jdbc:mysql://%s:%s/%s"; @Resource private Environment env; @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(env.getRequiredProperty(PROP_DATABASE_DRIVER)); boolean testPhase = !StringUtils.isEmpty(env.getProperty(PROP_DATABASE_URL)); if (testPhase) { dataSource.setUrl(env.getRequiredProperty(PROP_DATABASE_URL)); dataSource.setUsername(env.getRequiredProperty(PROP_DATABASE_USERNAME)); dataSource.setPassword(env.getRequiredProperty(PROP_DATABASE_PASSWORD)); } else { String stand = env.getProperty(STAND_SYSTEM_PROPERTY_NAME); if (StringUtils.isEmpty(stand)) { dataSource.setUrl(String.format(DB_CONNECTION_PATTERN, OPENSHIFT_MYSQL_DB_HOST, OPENSHIFT_MYSQL_DB_PORT, OPENSHIFT_APP_NAME)); dataSource.setUsername(env.getRequiredProperty(OPENSHIFT_MYSQL_DB_USERNAME)); dataSource.setPassword(env.getRequiredProperty(OPENSHIFT_MYSQL_DB_PASSWORD)); } try { Properties devProperties = PropertiesLoaderUtils.loadProperties(new ClassPathResource(DEV_PROPERTIES_PATH_TEMPLATE.replace("{stand}", stand))); dataSource.setUrl(devProperties.getProperty(PROP_DATABASE_URL)); dataSource.setUsername(devProperties.getProperty(PROP_DATABASE_USERNAME)); dataSource.setPassword(devProperties.getProperty(PROP_DATABASE_PASSWORD)); } catch (IOException e) { log.error("Can not read the file with developer's settings. Stand : " + stand, e); } } return dataSource; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); entityManagerFactoryBean.setDataSource(dataSource()); entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class); entityManagerFactoryBean.setPackagesToScan(env.getRequiredProperty(PROP_ENTITY_MANAGER_PACKAGES_TO_SCAN)); entityManagerFactoryBean.setJpaProperties(getHibernateProperties()); return entityManagerFactoryBean; } @Bean public JpaTransactionManager transactionManager() { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); return transactionManager; } @Bean public ModelMapper modelMapper() { ModelMapper modelMapper = new ModelMapper(); modelMapper.addConverter(new AbstractConverter<Date, LocalDateTime>() { @Override protected LocalDateTime convert(Date source) { if (source == null) return null; return LocalDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault()); } }); modelMapper.addConverter(new AbstractConverter<LocalDateTime, Date>() { @Override protected Date convert(LocalDateTime source) { if (source == null) return null; return Date.from(source.atZone(ZoneId.systemDefault()).toInstant()); } }); return modelMapper; } private Properties getHibernateProperties() { Properties properties = new Properties(); properties.put(PROP_HIBERNATE_DIALECT, env.getRequiredProperty(PROP_HIBERNATE_DIALECT)); properties.put(PROP_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROP_HIBERNATE_SHOW_SQL)); properties.put(PROP_HIBERNATE_HBM2DDL_AUTO, env.getRequiredProperty(PROP_HIBERNATE_HBM2DDL_AUTO)); return properties; } }
DB properties using change
backend/src/main/java/com/letionik/matinee/config/DataConfig.java
DB properties using change
<ide><path>ackend/src/main/java/com/letionik/matinee/config/DataConfig.java <ide> } else { <ide> String stand = env.getProperty(STAND_SYSTEM_PROPERTY_NAME); <ide> if (StringUtils.isEmpty(stand)) { <del> dataSource.setUrl(String.format(DB_CONNECTION_PATTERN, OPENSHIFT_MYSQL_DB_HOST, OPENSHIFT_MYSQL_DB_PORT, OPENSHIFT_APP_NAME)); <add> dataSource.setUrl(String.format(DB_CONNECTION_PATTERN, env.getRequiredProperty(OPENSHIFT_MYSQL_DB_HOST), env.getRequiredProperty(OPENSHIFT_MYSQL_DB_PORT), env.getRequiredProperty(OPENSHIFT_APP_NAME))); <ide> dataSource.setUsername(env.getRequiredProperty(OPENSHIFT_MYSQL_DB_USERNAME)); <ide> dataSource.setPassword(env.getRequiredProperty(OPENSHIFT_MYSQL_DB_PASSWORD)); <del> } <del> try { <del> Properties devProperties = PropertiesLoaderUtils.loadProperties(new ClassPathResource(DEV_PROPERTIES_PATH_TEMPLATE.replace("{stand}", stand))); <del> dataSource.setUrl(devProperties.getProperty(PROP_DATABASE_URL)); <del> dataSource.setUsername(devProperties.getProperty(PROP_DATABASE_USERNAME)); <del> dataSource.setPassword(devProperties.getProperty(PROP_DATABASE_PASSWORD)); <del> } catch (IOException e) { <del> log.error("Can not read the file with developer's settings. Stand : " + stand, e); <add> } else { <add> try { <add> Properties devProperties = PropertiesLoaderUtils.loadProperties(new ClassPathResource(DEV_PROPERTIES_PATH_TEMPLATE.replace("{stand}", stand))); <add> dataSource.setUrl(devProperties.getProperty(PROP_DATABASE_URL)); <add> dataSource.setUsername(devProperties.getProperty(PROP_DATABASE_USERNAME)); <add> dataSource.setPassword(devProperties.getProperty(PROP_DATABASE_PASSWORD)); <add> } catch (IOException e) { <add> log.error("Can not read the file with developer's settings. Stand : " + stand, e); <add> } <ide> } <ide> } <ide> return dataSource;
Java
unlicense
4d1c6247b6a2216567d7db713ab7e76543c1f6f5
0
SleepyTrousers/EnderIO,HenryLoenwind/EnderIO
package crazypants.enderio.base.diagnostics; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.annotation.Nonnull; import crazypants.enderio.api.EnderIOAPIProps; import crazypants.enderio.base.EnderIO; import crazypants.enderio.base.Log; import net.minecraft.block.Block; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.client.FMLClientHandler; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.ICrashCallable; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.ModAPIManager; import net.minecraftforge.fml.common.ModContainer; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; @EventBusSubscriber(modid = EnderIO.MODID) public class EnderIOCrashCallable implements ICrashCallable { @SubscribeEvent(priority = EventPriority.HIGHEST) public static void register(@Nonnull RegistryEvent.Register<Block> event) { FMLCommonHandler.instance().registerCrashCallable(new EnderIOCrashCallable()); } private List<String> collectData() { List<String> result = new ArrayList<String>(); if (FMLCommonHandler.instance().getSide() == Side.CLIENT && FMLClientHandler.instance().hasOptifine()) { result.add(" * Optifine is installed. This is NOT supported."); } for (ModContainer modContainer : ModAPIManager.INSTANCE.getAPIList()) { String apiVersionString = modContainer.getVersion(); if (apiVersionString == null) { apiVersionString = ""; } // if ("appliedenergistics2|API".equals(modContainer.getModId())) { // if ("rv1".equals(apiVersionString) || "rv2".equals(apiVersionString) || "rv3".equals(apiVersionString)) { // result.add(" * An unsupportted old AE2 API is installed (" + apiVersionString + " from " // + modContainer.getSource().getName() + ")."); // result.add(" Ender IO was build against API version rv4 and will NOT work with older versions."); // } else if (!"rv4".equals(apiVersionString)) { // result.add(" * An unknown AE2 API is installed (" + apiVersionString + " from " // + modContainer.getSource().getName() + ")."); // result.add(" Ender IO was build against API version rv4 and may or may not work with a newer version."); // } // } else if (modContainer.getModId() != null && modContainer.getModId().startsWith("EnderIOAPI")) { if (!EnderIOAPIProps.VERSION.equals(apiVersionString)) { result.add(" * Another mod is shipping a version of our API that doesn't match our version (" + apiVersionString + " from " + modContainer.getSource().getName() + "). That may not actually work."); } else if (modContainer.getSource().getName() != null && (!modContainer.getSource().getName().startsWith("EnderIO") && !modContainer.getSource().getName().startsWith("enderio") && !modContainer .getSource().getName().equals("bin"))) { result.add(" * Our API got loaded from " + modContainer.getSource().getName() + ". That's unexpected."); } } } String badBrand = null; for (String brand : FMLCommonHandler.instance().getModName().split(",")) { if (brand != null && !brand.equals("fml") && !brand.equals("forge")) { if (badBrand == null) { badBrand = brand; } else { badBrand += ", " + brand; } } } if (badBrand != null) { result.add("An unsupported base software is installed: '" + badBrand + "'. This is NOT supported."); } return result; } @Override public String call() throws Exception { String msg = ""; List<String> data = collectData(); if (data.isEmpty()) { msg += "No known problems detected.\n"; } else { msg += "Found the following problem(s) with your installation (That does NOT mean that Ender IO caused the crash or was involved in it in " + "any way. We add this information to help finding common problems, not as an invitation to post any crash you encounter to " + "Ender IO's issue tracker. Always check the stack trace above to see which mod is most likely failing.):\n"; for (String string : data) { msg += " " + string + "\n"; } msg += " This may (look up the meaning of 'may' in the dictionary if you're not sure what it means) have caused the error. " + "Try reproducing the crash WITHOUT this/these mod(s) before reporting it.\n"; } msg += "\tDetailed Tesla API diagnostics:\n"; for (String string : teslaDiagnostics()) { msg += " " + string + "\n"; } if (stopScreenMessage != null) { for (String s : stopScreenMessage) { msg += s + "\n"; } } Collection<IDiagnosticsTracker> trackers = DiagnosticsRegistry.getActiveTrackers(); if (trackers != null && !trackers.isEmpty()) { for (IDiagnosticsTracker tracker : trackers) { msg += "\t" + tracker.getActivityDescription() + "\n"; for (String string : tracker.getLines()) { msg += " " + string + "\n"; } } } msg += "\n"; msg += "\t!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"; msg += "\t!!!You are looking at the diagnostics information, not at the crash. Scroll up!!!\n"; msg += "\t!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"; return msg; } @Override public String getLabel() { return EnderIO.MOD_NAME; } // adapted from http://stackoverflow.com/a/19494116/4105897 public static String whereFrom(String c) { if (c == null) { return null; } try { return whereFrom(Class.forName(c)); }catch(Exception e) { return null; } } public static String whereFrom(Class<?> c) { if (c == null) { return null; } try { ClassLoader loader = c.getClassLoader(); if (loader == null) { // Try the bootstrap classloader - obtained from the ultimate parent of the System Class Loader. loader = ClassLoader.getSystemClassLoader(); while (loader != null && loader.getParent() != null) { loader = loader.getParent(); } } if (loader != null) { String name = c.getCanonicalName(); URL resource = loader.getResource(name.replace(".", "/") + ".class"); if (resource != null) { return resource.toString(); } } } catch (Throwable t) { } return "<unknown>"; } public static List<String> teslaDiagnostics() { List<String> result = new ArrayList<String>(); apiDiagnostics(result, "Tesla", "net.darkhax.tesla.", "Tesla"); apiDiagnostics(result, "Tesla", "net.darkhax.tesla.capability.", "TeslaCapabilities"); apiDiagnostics(result, "Tesla", "net.darkhax.tesla.api.", "ITeslaConsumer", "ITeslaHolder", "ITeslaProducer"); apiDiagnostics(result, "Tesla", "net.darkhax.tesla.api.implementation.", "BaseTeslaContainer", "BaseTeslaContainerProvider", "InfiniteTeslaConsumer", "InfiniteTeslaConsumerProvider", "InfiniteTeslaProducer", "InfiniteTeslaProducerProvider"); return result; } public static void apiDiagnostics(List<String> result, String displayName, String prefix, String... clazzes) { for (String clazz : clazzes) { try { Class<?> forName = Class.forName(prefix + clazz); result.add(" * " + displayName + " API class '" + clazz + "' is loaded from: " + whereFrom(forName)); } catch (ClassNotFoundException e) { result.add(" * " + displayName + " API class '" + clazz + "' could not be loaded (reason: " + e + ")"); if (Log.LOGGER.isDebugEnabled()) { // e.printStackTrace(); Log.debug("Hey, you wanted diagnostics output? Guess what you're not getting it. Too many people reported it as bug. Deal with it."); } } } } private static String[] stopScreenMessage = null; public static void registerStopScreenMessage(String... message) { stopScreenMessage = message; } }
src/main/java/crazypants/enderio/base/diagnostics/EnderIOCrashCallable.java
package crazypants.enderio.base.diagnostics; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.annotation.Nonnull; import crazypants.enderio.api.EnderIOAPIProps; import crazypants.enderio.base.EnderIO; import crazypants.enderio.base.Log; import net.minecraft.block.Block; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.client.FMLClientHandler; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.ICrashCallable; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.ModAPIManager; import net.minecraftforge.fml.common.ModContainer; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; @EventBusSubscriber(modid = EnderIO.MODID) public class EnderIOCrashCallable implements ICrashCallable { @SubscribeEvent(priority = EventPriority.HIGHEST) public static void register(@Nonnull RegistryEvent.Register<Block> event) { FMLCommonHandler.instance().registerCrashCallable(new EnderIOCrashCallable()); } private List<String> collectData() { List<String> result = new ArrayList<String>(); if (FMLCommonHandler.instance().getSide() == Side.CLIENT && FMLClientHandler.instance().hasOptifine()) { result.add(" * Optifine is installed. This is NOT supported."); } for (ModContainer modContainer : ModAPIManager.INSTANCE.getAPIList()) { String apiVersionString = modContainer.getVersion(); if (apiVersionString == null) { apiVersionString = ""; } if ("appliedenergistics2|API".equals(modContainer.getModId())) { if ("rv1".equals(apiVersionString) || "rv2".equals(apiVersionString) || "rv3".equals(apiVersionString)) { result.add(" * An unsupportted old AE2 API is installed (" + apiVersionString + " from " + modContainer.getSource().getName() + ")."); result.add(" Ender IO was build against API version rv4 and will NOT work with older versions."); } else if (!"rv4".equals(apiVersionString)) { result.add(" * An unknown AE2 API is installed (" + apiVersionString + " from " + modContainer.getSource().getName() + ")."); result.add(" Ender IO was build against API version rv4 and may or may not work with a newer version."); } } else if (modContainer.getModId() != null && modContainer.getModId().startsWith("EnderIOAPI")) { if (!EnderIOAPIProps.VERSION.equals(apiVersionString)) { result.add(" * Another mod is shipping a version of our API that doesn't match our version (" + apiVersionString + " from " + modContainer.getSource().getName() + "). That may not actually work."); } else if (modContainer.getSource().getName() != null && (!modContainer.getSource().getName().startsWith("EnderIO") && !modContainer.getSource().getName().startsWith("enderio") && !modContainer .getSource().getName().equals("bin"))) { result.add(" * Our API got loaded from " + modContainer.getSource().getName() + ". That's unexpected."); } } } String badBrand = null; for (String brand : FMLCommonHandler.instance().getModName().split(",")) { if (brand != null && !brand.equals("fml") && !brand.equals("forge")) { if (badBrand == null) { badBrand = brand; } else { badBrand += ", " + brand; } } } if (badBrand != null) { result.add("An unsupported base software is installed: '" + badBrand + "'. This is NOT supported."); } return result; } @Override public String call() throws Exception { String msg = ""; List<String> data = collectData(); if (data.isEmpty()) { msg += "No known problems detected.\n"; } else { msg += "Found the following problem(s) with your installation (That does NOT mean that Ender IO caused the crash or was involved in it in " + "any way. We add this information to help finding common problems, not as an invitation to post any crash you encounter to " + "Ender IO's issue tracker. Always check the stack trace above to see which mod is most likely failing.):\n"; for (String string : data) { msg += " " + string + "\n"; } msg += " This may (look up the meaning of 'may' in the dictionary if you're not sure what it means) have caused the error. " + "Try reproducing the crash WITHOUT this/these mod(s) before reporting it.\n"; } msg += "\tDetailed Tesla API diagnostics:\n"; for (String string : teslaDiagnostics()) { msg += " " + string + "\n"; } if (stopScreenMessage != null) { for (String s : stopScreenMessage) { msg += s + "\n"; } } Collection<IDiagnosticsTracker> trackers = DiagnosticsRegistry.getActiveTrackers(); if (trackers != null && !trackers.isEmpty()) { for (IDiagnosticsTracker tracker : trackers) { msg += "\t" + tracker.getActivityDescription() + "\n"; for (String string : tracker.getLines()) { msg += " " + string + "\n"; } } } msg += "\n"; msg += "\t!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"; msg += "\t!!!You are looking at the diagnostics information, not at the crash. Scroll up!!!\n"; msg += "\t!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"; return msg; } @Override public String getLabel() { return EnderIO.MOD_NAME; } // adapted from http://stackoverflow.com/a/19494116/4105897 public static String whereFrom(String c) { if (c == null) { return null; } try { return whereFrom(Class.forName(c)); }catch(Exception e) { return null; } } public static String whereFrom(Class<?> c) { if (c == null) { return null; } try { ClassLoader loader = c.getClassLoader(); if (loader == null) { // Try the bootstrap classloader - obtained from the ultimate parent of the System Class Loader. loader = ClassLoader.getSystemClassLoader(); while (loader != null && loader.getParent() != null) { loader = loader.getParent(); } } if (loader != null) { String name = c.getCanonicalName(); URL resource = loader.getResource(name.replace(".", "/") + ".class"); if (resource != null) { return resource.toString(); } } } catch (Throwable t) { } return "<unknown>"; } public static List<String> teslaDiagnostics() { List<String> result = new ArrayList<String>(); apiDiagnostics(result, "Tesla", "net.darkhax.tesla.", "Tesla"); apiDiagnostics(result, "Tesla", "net.darkhax.tesla.capability.", "TeslaCapabilities"); apiDiagnostics(result, "Tesla", "net.darkhax.tesla.api.", "ITeslaConsumer", "ITeslaHolder", "ITeslaProducer"); apiDiagnostics(result, "Tesla", "net.darkhax.tesla.api.implementation.", "BaseTeslaContainer", "BaseTeslaContainerProvider", "InfiniteTeslaConsumer", "InfiniteTeslaConsumerProvider", "InfiniteTeslaProducer", "InfiniteTeslaProducerProvider"); return result; } public static void apiDiagnostics(List<String> result, String displayName, String prefix, String... clazzes) { for (String clazz : clazzes) { try { Class<?> forName = Class.forName(prefix + clazz); result.add(" * " + displayName + " API class '" + clazz + "' is loaded from: " + whereFrom(forName)); } catch (ClassNotFoundException e) { result.add(" * " + displayName + " API class '" + clazz + "' could not be loaded (reason: " + e + ")"); if (Log.LOGGER.isDebugEnabled()) { // e.printStackTrace(); Log.debug("Hey, you wanted diagnostics output? Guess what you're not getting it. Too many people reported it as bug. Deal with it."); } } } } private static String[] stopScreenMessage = null; public static void registerStopScreenMessage(String... message) { stopScreenMessage = message; } }
Removed AE2 API diagnostics from base
src/main/java/crazypants/enderio/base/diagnostics/EnderIOCrashCallable.java
Removed AE2 API diagnostics from base
<ide><path>rc/main/java/crazypants/enderio/base/diagnostics/EnderIOCrashCallable.java <ide> if (apiVersionString == null) { <ide> apiVersionString = ""; <ide> } <del> if ("appliedenergistics2|API".equals(modContainer.getModId())) { <del> if ("rv1".equals(apiVersionString) || "rv2".equals(apiVersionString) || "rv3".equals(apiVersionString)) { <del> result.add(" * An unsupportted old AE2 API is installed (" + apiVersionString + " from " <del> + modContainer.getSource().getName() + ")."); <del> result.add(" Ender IO was build against API version rv4 and will NOT work with older versions."); <del> } else if (!"rv4".equals(apiVersionString)) { <del> result.add(" * An unknown AE2 API is installed (" + apiVersionString + " from " <del> + modContainer.getSource().getName() + ")."); <del> result.add(" Ender IO was build against API version rv4 and may or may not work with a newer version."); <del> } <del> } else if (modContainer.getModId() != null && modContainer.getModId().startsWith("EnderIOAPI")) { <add> // if ("appliedenergistics2|API".equals(modContainer.getModId())) { <add> // if ("rv1".equals(apiVersionString) || "rv2".equals(apiVersionString) || "rv3".equals(apiVersionString)) { <add> // result.add(" * An unsupportted old AE2 API is installed (" + apiVersionString + " from " <add> // + modContainer.getSource().getName() + ")."); <add> // result.add(" Ender IO was build against API version rv4 and will NOT work with older versions."); <add> // } else if (!"rv4".equals(apiVersionString)) { <add> // result.add(" * An unknown AE2 API is installed (" + apiVersionString + " from " <add> // + modContainer.getSource().getName() + ")."); <add> // result.add(" Ender IO was build against API version rv4 and may or may not work with a newer version."); <add> // } <add> // } else <add> if (modContainer.getModId() != null && modContainer.getModId().startsWith("EnderIOAPI")) { <ide> if (!EnderIOAPIProps.VERSION.equals(apiVersionString)) { <ide> result.add(" * Another mod is shipping a version of our API that doesn't match our version (" + apiVersionString <ide> + " from " + modContainer.getSource().getName() + "). That may not actually work.");
Java
apache-2.0
93eb53db6f5066ac102f11e5253dcb7d6c33b679
0
kishorejangid/manifoldcf,apache/manifoldcf,apache/manifoldcf,apache/manifoldcf,apache/manifoldcf,kishorejangid/manifoldcf,apache/manifoldcf,kishorejangid/manifoldcf,kishorejangid/manifoldcf,kishorejangid/manifoldcf,apache/manifoldcf,kishorejangid/manifoldcf
/* $Id: DBInterfacePostgreSQL.java 999670 2010-09-21 22:18:19Z kwright $ */ /** * 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 org.apache.manifoldcf.core.database; import org.apache.manifoldcf.core.interfaces.*; import org.apache.manifoldcf.core.system.ManifoldCF; import org.apache.manifoldcf.core.system.Logging; import java.util.*; public class DBInterfacePostgreSQL extends Database implements IDBInterface { public static final String _rcsid = "@(#)$Id: DBInterfacePostgreSQL.java 999670 2010-09-21 22:18:19Z kwright $"; /** PostgreSQL host name property */ public static final String postgresqlHostnameProperty = "org.apache.manifoldcf.postgresql.hostname"; /** PostgreSQL port property */ public static final String postgresqlPortProperty = "org.apache.manifoldcf.postgresql.port"; /** PostgreSQL ssl property */ public static final String postgresqlSslProperty = "org.apache.manifoldcf.postgresql.ssl"; private static final String _defaultUrl = "jdbc:postgresql://localhost/"; private static final String _driver = "org.postgresql.Driver"; /** A lock manager handle. */ protected final ILockManager lockManager; // Database cache key protected final String cacheKey; // Postgresql serializable transactions are broken in that transactions that occur within them do not in fact work properly. // So, once we enter the serializable realm, STOP any additional transactions from doing anything at all. protected int serializableDepth = 0; // This is where we keep track of tables that we need to analyze on transaction exit protected List<String> tablesToAnalyze = new ArrayList<String>(); // Keep track of tables to reindex on transaction exit protected List<String> tablesToReindex = new ArrayList<String>(); // This is where we keep temporary table statistics, which accumulate until they reach a threshold, and then are added into shared memory. /** Accumulated reindex statistics. This map is keyed by the table name, and contains TableStatistics values. */ protected static Map<String,TableStatistics> currentReindexStatistics = new HashMap<String,TableStatistics>(); /** Table reindex thresholds, as read from configuration information. Keyed by table name, contains Integer values. */ protected static Map<String,Integer> reindexThresholds = new HashMap<String,Integer>(); /** Accumulated analyze statistics. This map is keyed by the table name, and contains TableStatistics values. */ protected static Map<String,TableStatistics> currentAnalyzeStatistics = new HashMap<String,TableStatistics>(); /** Table analyze thresholds, as read from configuration information. Keyed by table name, contains Integer values. */ protected static Map<String,Integer> analyzeThresholds = new HashMap<String,Integer>(); /** The number of inserts, deletes, etc. before we update the shared area. */ protected static final int commitThreshold = 100; // Lock and shared datum name prefixes (to be combined with table names) protected static final String statslockReindexPrefix = "statslock-reindex-"; protected static final String statsReindexPrefix = "stats-reindex-"; protected static final String statslockAnalyzePrefix = "statslock-analyze-"; protected static final String statsAnalyzePrefix = "stats-analyze-"; public DBInterfacePostgreSQL(IThreadContext tc, String databaseName, String userName, String password) throws ManifoldCFException { super(tc,getJdbcUrl(tc,databaseName),_driver,databaseName,userName,password); cacheKey = CacheKeyFactory.makeDatabaseKey(this.databaseName); lockManager = LockManagerFactory.make(tc); } private static String getJdbcUrl(final IThreadContext tc, final String databaseName) throws ManifoldCFException { String jdbcUrl = _defaultUrl + databaseName; final String hostname = LockManagerFactory.getProperty(tc,postgresqlHostnameProperty); final String ssl = LockManagerFactory.getProperty(tc,postgresqlSslProperty); final String port = LockManagerFactory.getProperty(tc,postgresqlPortProperty); if (hostname != null && hostname.length() > 0) { jdbcUrl = "jdbc:postgresql://" + hostname; if (port != null && port.length() > 0) { jdbcUrl += ":" + port; } jdbcUrl += "/" + databaseName; if (ssl != null && ssl.equals("true")) { jdbcUrl += "?ssl=true"; } } return jdbcUrl; } /** Initialize. This method is called once per JVM instance, in order to set up * database communication. */ @Override public void openDatabase() throws ManifoldCFException { // Nothing to do } /** Uninitialize. This method is called during JVM shutdown, in order to close * all database communication. */ @Override public void closeDatabase() throws ManifoldCFException { // Nothing to do } /** Get the database general cache key. *@return the general cache key for the database. */ @Override public String getDatabaseCacheKey() { return cacheKey; } /** Perform an insert operation. *@param tableName is the name of the table. *@param invalidateKeys are the cache keys that should be * invalidated. *@param parameterMap is the map of column name/values to write. */ @Override public void performInsert(String tableName, Map<String,Object> parameterMap, StringSet invalidateKeys) throws ManifoldCFException { List paramArray = new ArrayList(); StringBuilder bf = new StringBuilder(); bf.append("INSERT INTO "); bf.append(tableName); bf.append(" (") ; StringBuilder values = new StringBuilder(" VALUES ("); // loop for cols Iterator<Map.Entry<String,Object>> it = parameterMap.entrySet().iterator(); boolean first = true; while (it.hasNext()) { Map.Entry<String,Object> e = it.next(); String key = e.getKey(); Object o = e.getValue(); if (o != null) { paramArray.add(o); if (!first) { bf.append(','); values.append(','); } bf.append(key); values.append('?'); first = false; } } bf.append(')'); values.append(')'); bf.append(values); // Do the modification performModification(bf.toString(),paramArray,invalidateKeys); } /** Perform an update operation. *@param tableName is the name of the table. *@param invalidateKeys are the cache keys that should be invalidated. *@param parameterMap is the map of column name/values to write. *@param whereClause is the where clause describing the match (including the WHERE), or null if none. *@param whereParameters are the parameters that come with the where clause, if any. */ @Override public void performUpdate(String tableName, Map<String,Object> parameterMap, String whereClause, List whereParameters, StringSet invalidateKeys) throws ManifoldCFException { List paramArray = new ArrayList(); StringBuilder bf = new StringBuilder(); bf.append("UPDATE "); bf.append(tableName); bf.append(" SET ") ; // loop for parameters Iterator<Map.Entry<String,Object>> it = parameterMap.entrySet().iterator(); boolean first = true; while (it.hasNext()) { Map.Entry<String,Object> e = it.next(); String key = e.getKey(); Object o = e.getValue(); if (!first) { bf.append(','); } bf.append(key); bf.append('='); if (o == null) { bf.append("NULL"); } else { bf.append('?'); paramArray.add(o); } first = false; } if (whereClause != null) { bf.append(' '); bf.append(whereClause); if (whereParameters != null) { for (int i = 0; i < whereParameters.size(); i++) { Object value = whereParameters.get(i); paramArray.add(value); } } } // Do the modification performModification(bf.toString(),paramArray,invalidateKeys); } /** Perform a delete operation. *@param tableName is the name of the table to delete from. *@param invalidateKeys are the cache keys that should be invalidated. *@param whereClause is the where clause describing the match (including the WHERE), or null if none. *@param whereParameters are the parameters that come with the where clause, if any. */ @Override public void performDelete(String tableName, String whereClause, List whereParameters, StringSet invalidateKeys) throws ManifoldCFException { StringBuilder bf = new StringBuilder(); bf.append("DELETE FROM "); bf.append(tableName); if (whereClause != null) { bf.append(' '); bf.append(whereClause); } else whereParameters = null; // Do the modification performModification(bf.toString(),whereParameters,invalidateKeys); } /** Perform a table creation operation. *@param tableName is the name of the table to create. *@param columnMap is the map describing the columns and types. NOTE that these are abstract * types, which will be mapped to the proper types for the actual database inside this * layer. *@param invalidateKeys are the cache keys that should be invalidated, if any. */ @Override public void performCreate(String tableName, Map<String,ColumnDescription> columnMap, StringSet invalidateKeys) throws ManifoldCFException { StringBuilder queryBuffer = new StringBuilder("CREATE TABLE "); queryBuffer.append(tableName); queryBuffer.append('('); Iterator<String> iter = columnMap.keySet().iterator(); boolean first = true; while (iter.hasNext()) { String columnName = iter.next(); ColumnDescription cd = columnMap.get(columnName); if (!first) queryBuffer.append(','); else first = false; appendDescription(queryBuffer,columnName,cd,false); } queryBuffer.append(')'); performModification(queryBuffer.toString(),null,invalidateKeys); } protected static void appendDescription(StringBuilder queryBuffer, String columnName, ColumnDescription cd, boolean forceNull) { queryBuffer.append(columnName); queryBuffer.append(' '); queryBuffer.append(mapType(cd.getTypeString())); if (forceNull || cd.getIsNull()) queryBuffer.append(" NULL"); else queryBuffer.append(" NOT NULL"); if (cd.getIsPrimaryKey()) queryBuffer.append(" PRIMARY KEY"); if (cd.getReferenceTable() != null) { queryBuffer.append(" REFERENCES "); queryBuffer.append(cd.getReferenceTable()); queryBuffer.append('('); queryBuffer.append(cd.getReferenceColumn()); queryBuffer.append(") ON DELETE"); if (cd.getReferenceCascade()) queryBuffer.append(" CASCADE"); else queryBuffer.append(" RESTRICT"); } } /** Perform a table alter operation. *@param tableName is the name of the table to alter. *@param columnMap is the map describing the columns and types to add. These * are in the same form as for performCreate. *@param columnModifyMap is the map describing the columns to be changed. The key is the * existing column name, and the value is the new type of the column. Data will be copied from * the old column to the new. *@param columnDeleteList is the list of column names to delete. *@param invalidateKeys are the cache keys that should be invalidated, if any. */ @Override public void performAlter(String tableName, Map<String,ColumnDescription> columnMap, Map<String,ColumnDescription> columnModifyMap, List<String> columnDeleteList, StringSet invalidateKeys) throws ManifoldCFException { beginTransaction(TRANSACTION_ENCLOSING); try { if (columnDeleteList != null) { int i = 0; while (i < columnDeleteList.size()) { String columnName = columnDeleteList.get(i++); performModification("ALTER TABLE ONLY "+tableName+" DROP "+columnName,null,invalidateKeys); } } // Do the modifies. This involves renaming each column to a temp column, then creating a new one, then copying if (columnModifyMap != null) { Iterator<String> iter = columnModifyMap.keySet().iterator(); while (iter.hasNext()) { String columnName = iter.next(); ColumnDescription cd = columnModifyMap.get(columnName); String renameColumn = "__temp__"; // Rename current column performModification("ALTER TABLE ONLY "+tableName+" RENAME "+columnName+" TO "+renameColumn,null,invalidateKeys); // Create new column StringBuilder sb = new StringBuilder(); appendDescription(sb,columnName,cd,true); performModification("ALTER TABLE ONLY "+tableName+" ADD "+sb.toString(),null,invalidateKeys); // Copy old data to new performModification("UPDATE "+tableName+" SET "+columnName+"="+renameColumn,null,invalidateKeys); // Make the column null, if it needs it if (cd.getIsNull() == false) performModification("ALTER TABLE ONLY "+tableName+" ALTER "+columnName+" SET NOT NULL",null,invalidateKeys); // Drop old column performModification("ALTER TABLE ONLY "+tableName+" DROP "+renameColumn,null,invalidateKeys); } } // Now, do the adds if (columnMap != null) { Iterator<String> iter = columnMap.keySet().iterator(); while (iter.hasNext()) { String columnName = iter.next(); ColumnDescription cd = columnMap.get(columnName); StringBuilder sb = new StringBuilder(); appendDescription(sb,columnName,cd,false); performModification("ALTER TABLE ONLY "+tableName+" ADD "+sb.toString(),null,invalidateKeys); } } } catch (ManifoldCFException e) { signalRollback(); throw e; } catch (Error e) { signalRollback(); throw e; } finally { endTransaction(); } } /** Map a standard type into a postgresql type. *@param inputType is the input type. *@return the output type. */ protected static String mapType(String inputType) { if (inputType.equalsIgnoreCase("longtext")) return "text"; if (inputType.equalsIgnoreCase("blob")) return "bytea"; return inputType; } /** Add an index to a table. *@param tableName is the name of the table to add the index for. *@param unique is a boolean that if true describes a unique index. *@param columnList is the list of columns that need to be included * in the index, in order. */ @Override public void addTableIndex(String tableName, boolean unique, List<String> columnList) throws ManifoldCFException { String[] columns = new String[columnList.size()]; int i = 0; while (i < columns.length) { columns[i] = columnList.get(i); i++; } performAddIndex(null,tableName,new IndexDescription(unique,columns)); } /** Add an index to a table. *@param tableName is the name of the table to add the index for. *@param indexName is the optional name of the table index. If null, a name will be chosen automatically. *@param description is the index description. */ @Override public void performAddIndex(String indexName, String tableName, IndexDescription description) throws ManifoldCFException { String[] columnNames = description.getColumnNames(); if (columnNames.length == 0) return; if (indexName == null) // Build an index name indexName = "I"+IDFactory.make(context); StringBuilder queryBuffer = new StringBuilder("CREATE "); if (description.getIsUnique()) queryBuffer.append("UNIQUE "); queryBuffer.append("INDEX "); queryBuffer.append(indexName); queryBuffer.append(" ON "); queryBuffer.append(tableName); queryBuffer.append(" ("); int i = 0; while (i < columnNames.length) { String colName = columnNames[i]; if (i > 0) queryBuffer.append(','); queryBuffer.append(colName); i++; } queryBuffer.append(')'); performModification(queryBuffer.toString(),null,null); } /** Remove an index. *@param indexName is the name of the index to remove. *@param tableName is the table the index belongs to. */ @Override public void performRemoveIndex(String indexName, String tableName) throws ManifoldCFException { performModification("DROP INDEX "+indexName,null,null); } /** Perform a table drop operation. *@param tableName is the name of the table to drop. *@param invalidateKeys are the cache keys that should be invalidated, if any. */ @Override public void performDrop(String tableName, StringSet invalidateKeys) throws ManifoldCFException { performModification("DROP TABLE "+tableName,null,invalidateKeys); } /** Create user and database. *@param adminUserName is the admin user name. *@param adminPassword is the admin password. *@param invalidateKeys are the cache keys that should be invalidated, if any. */ @Override public void createUserAndDatabase(String adminUserName, String adminPassword, StringSet invalidateKeys) throws ManifoldCFException { // Create a connection to the master database, using the credentials supplied Database masterDatabase = new DBInterfacePostgreSQL(context,"template1",adminUserName,adminPassword); try { // Create user List params = new ArrayList(); params.add(userName); IResultSet set = masterDatabase.executeQuery("SELECT * FROM pg_user WHERE usename=?",params, null,null,null,true,-1,null,null); if (set.getRowCount() == 0) { // We have to quote the password. Due to a postgresql bug, parameters don't work for this field. StringBuilder sb = new StringBuilder(); sb.append("'"); int i = 0; while (i < password.length()) { char x = password.charAt(i); if (x == '\'') sb.append("'"); sb.append(x); i++; } sb.append("'"); String quotedPassword = sb.toString(); masterDatabase.executeQuery("CREATE USER "+userName+" PASSWORD "+quotedPassword,null, null,invalidateKeys,null,false,0,null,null); } // Create database params.clear(); params.add(databaseName); set = masterDatabase.executeQuery("SELECT * FROM pg_database WHERE datname=?",params, null,null,null,true,-1,null,null); if (set.getRowCount() == 0) { masterDatabase.executeQuery("CREATE DATABASE "+databaseName+" OWNER "+ userName+" ENCODING 'utf8'",null,null,invalidateKeys,null,false,0,null,null); } } catch (ManifoldCFException e) { throw reinterpretException(e); } } /** Drop user and database. *@param adminUserName is the admin user name. *@param adminPassword is the admin password. *@param invalidateKeys are the cache keys that should be invalidated, if any. */ @Override public void dropUserAndDatabase(String adminUserName, String adminPassword, StringSet invalidateKeys) throws ManifoldCFException { // Create a connection to the master database, using the credentials supplied Database masterDatabase = new DBInterfacePostgreSQL(context,"template1",adminUserName,adminPassword); try { // Drop database masterDatabase.executeQuery("DROP DATABASE "+databaseName,null,null,invalidateKeys,null,false,0,null,null); // Drop user masterDatabase.executeQuery("DROP USER "+userName,null,null,invalidateKeys,null,false,0,null,null); } catch (ManifoldCFException e) { throw reinterpretException(e); } } /** Reinterpret an exception tossed by the database layer. We need to disambiguate the various kinds of exception that * should be thrown. *@param theException is the exception to reinterpret *@return the reinterpreted exception to throw. */ protected ManifoldCFException reinterpretException(ManifoldCFException theException) { if (Logging.db.isDebugEnabled()) Logging.db.debug("Reinterpreting exception '"+theException.getMessage()+"'. The exception type is "+Integer.toString(theException.getErrorCode())); if (theException.getErrorCode() != ManifoldCFException.DATABASE_CONNECTION_ERROR) return theException; Throwable e = theException.getCause(); if (!(e instanceof java.sql.SQLException)) { //e.printStackTrace(); return theException; } if (Logging.db.isDebugEnabled()) Logging.db.debug("Exception "+theException.getMessage()+" is possibly a transaction abort signal"); java.sql.SQLException sqlException = (java.sql.SQLException)e; String message = sqlException.getMessage(); String sqlState = sqlException.getSQLState(); // If connection is closed, presume we are shutting down if (sqlState != null && sqlState.equals("08003")) return new ManifoldCFException(message,e,ManifoldCFException.INTERRUPTED); // Could not serialize if (sqlState != null && sqlState.equals("40001")) return new ManifoldCFException(message,e,ManifoldCFException.DATABASE_TRANSACTION_ABORT); // Deadlock detected if (sqlState != null && sqlState.equals("40P01")) return new ManifoldCFException(message,e,ManifoldCFException.DATABASE_TRANSACTION_ABORT); // Note well: We also have to treat 'duplicate key' as a transaction abort, since this is what you get when two threads attempt to // insert the same row. (Everything only works, then, as long as there is a unique constraint corresponding to every bad insert that // one could make.) if (sqlState != null && sqlState.equals("23505")) return new ManifoldCFException(message,e,ManifoldCFException.DATABASE_TRANSACTION_ABORT); // New Postgresql behavior (9.3): sometimes we don't get an exception thrown, but the transaction is dead nonetheless. if (sqlState != null && sqlState.equals("25P02")) return new ManifoldCFException(message,e,ManifoldCFException.DATABASE_TRANSACTION_ABORT); if (Logging.db.isDebugEnabled()) Logging.db.debug("Exception "+theException.getMessage()+" is NOT a transaction abort signal"); //e.printStackTrace(); //System.err.println("sqlstate = "+sqlState); return theException; } /** Perform a general database modification query. *@param query is the query string. *@param params are the parameterized values, if needed. *@param invalidateKeys are the cache keys to invalidate. */ @Override public void performModification(String query, List params, StringSet invalidateKeys) throws ManifoldCFException { try { executeQuery(query,params,null,invalidateKeys,null,false,0,null,null); } catch (ManifoldCFException e) { throw reinterpretException(e); } } /** Get a table's schema. *@param tableName is the name of the table. *@param cacheKeys are the keys against which to cache the query, or null. *@param queryClass is the name of the query class, or null. *@return a map of column names and ColumnDescription objects, describing the schema, or null if the * table doesn't exist. */ @Override public Map<String,ColumnDescription> getTableSchema(String tableName, StringSet cacheKeys, String queryClass) throws ManifoldCFException { StringBuilder query = new StringBuilder(); List list = new ArrayList(); query.append("SELECT pg_attribute.attname AS \"Field\","); query.append("CASE pg_type.typname WHEN 'int2' THEN 'smallint' WHEN 'int4' THEN 'int'"); query.append(" WHEN 'int8' THEN 'bigint' WHEN 'varchar' THEN 'varchar(' || pg_attribute.atttypmod-4 || ')'"); query.append(" WHEN 'text' THEN 'longtext'"); query.append(" WHEN 'bpchar' THEN 'char(' || pg_attribute.atttypmod-4 || ')'"); query.append(" ELSE pg_type.typname END AS \"Type\","); query.append("CASE WHEN pg_attribute.attnotnull THEN '' ELSE 'YES' END AS \"Null\","); query.append("CASE pg_type.typname WHEN 'varchar' THEN substring(pg_attrdef.adsrc from '^(.*).*$') ELSE pg_attrdef.adsrc END AS Default "); query.append("FROM pg_class INNER JOIN pg_attribute ON (pg_class.oid=pg_attribute.attrelid) INNER JOIN pg_type ON (pg_attribute.atttypid=pg_type.oid) "); query.append("LEFT JOIN pg_attrdef ON (pg_class.oid=pg_attrdef.adrelid AND pg_attribute.attnum=pg_attrdef.adnum) "); query.append("WHERE pg_class.relname=? AND pg_attribute.attnum>=1 AND NOT pg_attribute.attisdropped "); query.append("ORDER BY pg_attribute.attnum"); list.add(tableName); IResultSet set = performQuery(query.toString(),list,cacheKeys,queryClass); if (set.getRowCount() == 0) return null; // Digest the result Map<String,ColumnDescription> rval = new HashMap<String,ColumnDescription>(); int i = 0; while (i < set.getRowCount()) { IResultRow row = set.getRow(i++); String fieldName = row.getValue("Field").toString(); String type = row.getValue("Type").toString(); boolean isNull = row.getValue("Null").toString().equals("YES"); boolean isPrimaryKey = false; // row.getValue("Key").toString().equals("PRI"); rval.put(fieldName,new ColumnDescription(type,isPrimaryKey,isNull,null,null,false)); } return rval; } /** Get a table's indexes. *@param tableName is the name of the table. *@param cacheKeys are the keys against which to cache the query, or null. *@param queryClass is the name of the query class, or null. *@return a map of index names and IndexDescription objects, describing the indexes. */ @Override public Map<String,IndexDescription> getTableIndexes(String tableName, StringSet cacheKeys, String queryClass) throws ManifoldCFException { Map<String,IndexDescription> rval = new HashMap<String,IndexDescription>(); String query = "SELECT pg_catalog.pg_get_indexdef(i.indexrelid, 0, true) AS indexdef "+ "FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i "+ "WHERE c.relname = ? AND c.oid = i.indrelid AND i.indexrelid = c2.oid"; List list = new ArrayList(); list.add(tableName); IResultSet result = performQuery(query,list,cacheKeys,queryClass); int i = 0; while (i < result.getRowCount()) { IResultRow row = result.getRow(i++); String indexdef = (String)row.getValue("indexdef"); // Parse the command! boolean isUnique; int parsePosition = 0; int beforeMatch = indexdef.indexOf("CREATE UNIQUE INDEX ",parsePosition); if (beforeMatch == -1) { beforeMatch = indexdef.indexOf("CREATE INDEX ",parsePosition); if (beforeMatch == -1) throw new ManifoldCFException("Cannot parse index description: '"+indexdef+"'"); isUnique = false; parsePosition += "CREATE INDEX ".length(); } else { isUnique = true; parsePosition += "CREATE UNIQUE INDEX ".length(); } int afterMatch = indexdef.indexOf(" ON",parsePosition); if (afterMatch == -1) throw new ManifoldCFException("Cannot parse index description: '"+indexdef+"'"); String indexName = indexdef.substring(parsePosition,afterMatch); parsePosition = afterMatch + " ON".length(); int parenPosition = indexdef.indexOf("(",parsePosition); if (parenPosition == -1) throw new ManifoldCFException("Cannot parse index description: '"+indexdef+"'"); parsePosition = parenPosition + 1; List<String> columns = new ArrayList<String>(); while (true) { int nextIndex = indexdef.indexOf(",",parsePosition); int nextParenIndex = indexdef.indexOf(")",parsePosition); if (nextIndex == -1) nextIndex = nextParenIndex; if (nextIndex == -1) throw new ManifoldCFException("Cannot parse index description: '"+indexdef+"'"); if (nextParenIndex != -1 && nextParenIndex < nextIndex) nextIndex = nextParenIndex; String columnName = indexdef.substring(parsePosition,nextIndex).trim(); columns.add(columnName); if (nextIndex == nextParenIndex) break; parsePosition = nextIndex + 1; } String[] columnNames = new String[columns.size()]; int j = 0; while (j < columnNames.length) { columnNames[j] = columns.get(j); j++; } rval.put(indexName,new IndexDescription(isUnique,columnNames)); } return rval; } /** Get a database's tables. *@param cacheKeys are the cache keys for the query, or null. *@param queryClass is the name of the query class, or null. *@return the set of tables. */ @Override public StringSet getAllTables(StringSet cacheKeys, String queryClass) throws ManifoldCFException { IResultSet set = performQuery("SELECT relname FROM pg_class",null,cacheKeys,queryClass); StringSetBuffer ssb = new StringSetBuffer(); String columnName = "relname"; int i = 0; while (i < set.getRowCount()) { IResultRow row = set.getRow(i++); String value = row.getValue(columnName).toString(); ssb.add(value); } return new StringSet(ssb); } /** Perform a general "data fetch" query. *@param query is the query string. *@param params are the parameterized values, if needed. *@param cacheKeys are the cache keys, if needed (null if no cache desired). *@param queryClass is the LRU class name against which this query would be cached, * or null if no LRU behavior desired. *@return a resultset. */ @Override public IResultSet performQuery(String query, List params, StringSet cacheKeys, String queryClass) throws ManifoldCFException { try { return executeQuery(query,params,cacheKeys,null,queryClass,true,-1,null,null); } catch (ManifoldCFException e) { throw reinterpretException(e); } } /** Perform a general "data fetch" query. *@param query is the query string. *@param params are the parameterized values, if needed. *@param cacheKeys are the cache keys, if needed (null if no cache desired). *@param queryClass is the LRU class name against which this query would be cached, * or null if no LRU behavior desired. *@param maxResults is the maximum number of results returned (-1 for all). *@param returnLimit is a description of how to limit the return result, or null if no limit. *@return a resultset. */ @Override public IResultSet performQuery(String query, List params, StringSet cacheKeys, String queryClass, int maxResults, ILimitChecker returnLimit) throws ManifoldCFException { try { return executeQuery(query,params,cacheKeys,null,queryClass,true,maxResults,null,returnLimit); } catch (ManifoldCFException e) { throw reinterpretException(e); } } /** Perform a general "data fetch" query. *@param query is the query string. *@param params are the parameterized values, if needed. *@param cacheKeys are the cache keys, if needed (null if no cache desired). *@param queryClass is the LRU class name against which this query would be cached, * or null if no LRU behavior desired. *@param maxResults is the maximum number of results returned (-1 for all). *@param resultSpec is a result specification, or null for the standard treatment. *@param returnLimit is a description of how to limit the return result, or null if no limit. *@return a resultset. */ @Override public IResultSet performQuery(String query, List params, StringSet cacheKeys, String queryClass, int maxResults, ResultSpecification resultSpec, ILimitChecker returnLimit) throws ManifoldCFException { try { return executeQuery(query,params,cacheKeys,null,queryClass,true,maxResults,resultSpec,returnLimit); } catch (ManifoldCFException e) { throw reinterpretException(e); } } /** Construct a cast to a double value. * On most databases this cast needs to be explicit, but on some it is implicit (and cannot be in fact * specified). *@param value is the value to be cast. *@return the query chunk needed. */ @Override public String constructDoubleCastClause(String value) { return "CAST("+value+" AS DOUBLE PRECISION)"; } /** Construct a count clause. * On most databases this will be COUNT(col), but on some the count needs to be cast to a BIGINT, so * CAST(COUNT(col) AS BIGINT) will be emitted instead. *@param column is the column string to be counted. *@return the query chunk needed. */ @Override public String constructCountClause(String column) { return "COUNT("+column+")"; } /** Construct a regular-expression match clause. * This method builds both the text part of a regular-expression match. *@param column is the column specifier string. *@param regularExpression is the properly-quoted regular expression string, or "?" if a parameterized value is to be used. *@param caseInsensitive is true of the regular expression match is to be case insensitive. *@return the query chunk needed, not padded with spaces on either side. */ @Override public String constructRegexpClause(String column, String regularExpression, boolean caseInsensitive) { return column + "~" + (caseInsensitive?"*":"") + regularExpression; } /** Construct a regular-expression substring clause. * This method builds an expression that extracts a specified string section from a field, based on * a regular expression. *@param column is the column specifier string. *@param regularExpression is the properly-quoted regular expression string, or "?" if a parameterized value is to be used. *@param caseInsensitive is true if the regular expression match is to be case insensitive. *@return the expression chunk needed, not padded with spaces on either side. */ @Override public String constructSubstringClause(String column, String regularExpression, boolean caseInsensitive) { StringBuilder sb = new StringBuilder(); sb.append("SUBSTRING("); if (caseInsensitive) sb.append("LOWER(").append(column).append(")"); else sb.append(column); sb.append(" FROM "); if (caseInsensitive) sb.append("LOWER(").append(regularExpression).append(")"); else sb.append(regularExpression); sb.append(")"); return sb.toString(); } /** Construct an offset/limit clause. * This method constructs an offset/limit clause in the proper manner for the database in question. *@param offset is the starting offset number. *@param limit is the limit of result rows to return. *@param afterOrderBy is true if this offset/limit comes after an ORDER BY. *@return the proper clause, with no padding spaces on either side. */ @Override public String constructOffsetLimitClause(int offset, int limit, boolean afterOrderBy) { StringBuilder sb = new StringBuilder(); if (offset != 0) sb.append("OFFSET ").append(Integer.toString(offset)); if (limit != -1) { if (offset != 0) sb.append(" "); sb.append("LIMIT ").append(Integer.toString(limit)); } return sb.toString(); } /** Construct a 'distinct on (x)' filter. * This filter wraps a query and returns a new query whose results are similar to POSTGRESQL's DISTINCT-ON feature. * Specifically, for each combination of the specified distinct fields in the result, only the first such row is included in the final * result. *@param outputParameters is a blank list into which to put parameters. Null may be used if the baseParameters parameter is null. *@param baseQuery is the base query, which is another SELECT statement, without parens, * e.g. "SELECT ..." *@param baseParameters are the parameters corresponding to the baseQuery. *@param distinctFields are the fields to consider to be distinct. These should all be keys in otherFields below. *@param orderFields are the otherfield keys that determine the ordering. *@param orderFieldsAscending are true for orderFields that are ordered as ASC, false for DESC. *@param otherFields are the rest of the fields to return, keyed by the AS name, value being the base query column value, e.g. "value AS key" *@return a revised query that performs the necessary DISTINCT ON operation. The list outputParameters will also be appropriately filled in. */ @Override public String constructDistinctOnClause(List outputParameters, String baseQuery, List baseParameters, String[] distinctFields, String[] orderFields, boolean[] orderFieldsAscending, Map<String,String> otherFields) { // Copy arguments if (baseParameters != null) outputParameters.addAll(baseParameters); StringBuilder sb = new StringBuilder("SELECT DISTINCT ON("); int i = 0; while (i < distinctFields.length) { if (i > 0) sb.append(","); sb.append(distinctFields[i++]); } sb.append(") "); Iterator<String> iter = otherFields.keySet().iterator(); boolean needComma = false; while (iter.hasNext()) { String fieldName = iter.next(); String columnValue = otherFields.get(fieldName); if (needComma) sb.append(","); needComma = true; sb.append("txxx1.").append(columnValue).append(" AS ").append(fieldName); } sb.append(" FROM (").append(baseQuery).append(") txxx1"); if (distinctFields.length > 0 || orderFields.length > 0) { sb.append(" ORDER BY "); int k = 0; i = 0; while (i < distinctFields.length) { if (k > 0) sb.append(","); sb.append(distinctFields[i]).append(" ASC"); k++; i++; } i = 0; while (i < orderFields.length) { if (k > 0) sb.append(","); sb.append(orderFields[i]).append(" "); if (orderFieldsAscending[i]) sb.append("ASC"); else sb.append("DESC"); i++; k++; } } return sb.toString(); } /** Obtain the maximum number of individual items that should be * present in an IN clause. Exceeding this amount will potentially cause the query performance * to drop. *@return the maximum number of IN clause members. */ @Override public int getMaxInClause() { return 100; } /** Obtain the maximum number of individual clauses that should be * present in a sequence of OR clauses. Exceeding this amount will potentially cause the query performance * to drop. *@return the maximum number of OR clause members. */ @Override public int getMaxOrClause() { return 25; } /* Calculate the number of values a particular clause can have, given the values for all the other clauses. * For example, if in the expression x AND y AND z, x has 2 values and z has 1, find out how many values x can legally have * when using the buildConjunctionClause() method below. */ @Override public int findConjunctionClauseMax(ClauseDescription[] otherClauseDescriptions) { // This implementation uses "OR" return getMaxOrClause(); } /* Construct a conjunction clause, e.g. x AND y AND z, where there is expected to be an index (x,y,z,...), and where x, y, or z * can have multiple distinct values, The proper implementation of this method differs from database to database, because some databases * only permit index operations when there are OR's between clauses, such as x1 AND y1 AND z1 OR x2 AND y2 AND z2 ..., where others * only recognize index operations when there are lists specified for each, such as x IN (x1,x2) AND y IN (y1,y2) AND z IN (z1,z2). */ @Override public String buildConjunctionClause(List outputParameters, ClauseDescription[] clauseDescriptions) { // This implementation uses "OR" instead of "IN ()" for multiple values, since this generates better plans in Postgresql 9.x. StringBuilder sb = new StringBuilder(); for (int i = 0 ; i < clauseDescriptions.length ; i++) { ClauseDescription cd = clauseDescriptions[i]; if (i > 0) sb.append(" AND "); String columnName = cd.getColumnName(); List values = cd.getValues(); String operation = cd.getOperation(); String joinColumn = cd.getJoinColumnName(); if (values != null) { if (values.size() > 1) { sb.append(" ("); for (int j = 0 ; j < values.size() ; j++) { if (j > 0) sb.append(" OR "); sb.append(columnName).append(operation).append("?"); outputParameters.add(values.get(j)); } sb.append(")"); } else { sb.append(columnName).append(operation).append("?"); outputParameters.add(values.get(0)); } } else if (joinColumn != null) { sb.append(columnName).append(operation).append(joinColumn); } else sb.append(columnName).append(operation); } return sb.toString(); } /** For windowed report queries, e.g. maxActivity or maxBandwidth, obtain the maximum number of rows * that can reasonably be expected to complete in an acceptable time. *@return the maximum number of rows. */ @Override public int getWindowedReportMaxRows() { return 5000; } /** Begin a database transaction. This method call MUST be paired with an endTransaction() call, * or database handles will be lost. If the transaction should be rolled back, then signalRollback() should * be called before the transaction is ended. * It is strongly recommended that the code that uses transactions be structured so that a try block * starts immediately after this method call. The body of the try block will contain all direct or indirect * calls to executeQuery(). After this should be a catch for every exception type, including Error, which should call the * signalRollback() method, and rethrow the exception. Then, after that a finally{} block which calls endTransaction(). */ @Override public void beginTransaction() throws ManifoldCFException { beginTransaction(TRANSACTION_ENCLOSING); } /** Begin a database transaction. This method call MUST be paired with an endTransaction() call, * or database handles will be lost. If the transaction should be rolled back, then signalRollback() should * be called before the transaction is ended. * It is strongly recommended that the code that uses transactions be structured so that a try block * starts immediately after this method call. The body of the try block will contain all direct or indirect * calls to executeQuery(). After this should be a catch for every exception type, including Error, which should call the * signalRollback() method, and rethrow the exception. Then, after that a finally{} block which calls endTransaction(). *@param transactionType is the kind of transaction desired. */ @Override public void beginTransaction(int transactionType) throws ManifoldCFException { if (getCurrentTransactionType() == TRANSACTION_SERIALIZED) { serializableDepth++; return; } if (transactionType == TRANSACTION_ENCLOSING) { transactionType = getCurrentTransactionType(); } switch (transactionType) { case TRANSACTION_READCOMMITTED: super.beginTransaction(TRANSACTION_READCOMMITTED); break; case TRANSACTION_SERIALIZED: super.beginTransaction(TRANSACTION_SERIALIZED); try { performModification("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE",null,null); } catch (Error e) { super.signalRollback(); super.endTransaction(); throw e; } catch (ManifoldCFException e) { super.signalRollback(); super.endTransaction(); throw e; } break; default: throw new ManifoldCFException("Bad transaction type: "+Integer.toString(transactionType)); } } /** Signal that a rollback should occur on the next endTransaction(). */ @Override public void signalRollback() { if (serializableDepth == 0) super.signalRollback(); } /** End a database transaction, either performing a commit or a rollback (depending on whether * signalRollback() was called within the transaction). */ @Override public void endTransaction() throws ManifoldCFException { if (serializableDepth > 0) { serializableDepth--; return; } super.endTransaction(); if (getTransactionID() == null) { int i = 0; while (i < tablesToAnalyze.size()) { analyzeTableInternal(tablesToAnalyze.get(i++)); } tablesToAnalyze.clear(); i = 0; while (i < tablesToReindex.size()) { reindexTableInternal(tablesToReindex.get(i++)); } tablesToReindex.clear(); } } /** Abstract method to start a transaction */ @Override protected void startATransaction() throws ManifoldCFException { try { executeViaThread((connection==null)?null:connection.getConnection(),"START TRANSACTION",null,false,0,null,null); } catch (ManifoldCFException e) { throw reinterpretException(e); } } /** Abstract method to commit a transaction */ @Override protected void commitCurrentTransaction() throws ManifoldCFException { try { executeViaThread((connection==null)?null:connection.getConnection(),"COMMIT",null,false,0,null,null); } catch (ManifoldCFException e) { throw reinterpretException(e); } } /** Abstract method to roll back a transaction */ @Override protected void rollbackCurrentTransaction() throws ManifoldCFException { try { executeViaThread((connection==null)?null:connection.getConnection(),"ROLLBACK",null,false,0,null,null); } catch (ManifoldCFException e) { throw reinterpretException(e); } } /** Abstract method for explaining a query */ @Override protected void explainQuery(String query, List params) throws ManifoldCFException { // We really can't retry at this level; it's not clear what the transaction nesting is etc. // So if the EXPLAIN fails due to deadlock, we just give up. IResultSet x; String queryType = "EXPLAIN "; if ("SELECT".equalsIgnoreCase(query.substring(0,6))) queryType += "ANALYZE "; x = executeUncachedQuery(queryType+query,params,true, -1,null,null); for (int k = 0; k < x.getRowCount(); k++) { IResultRow row = x.getRow(k); Iterator<String> iter = row.getColumns(); String colName = (String)iter.next(); Logging.db.warn(" Plan: "+row.getValue(colName).toString()); } Logging.db.warn(""); if (query.indexOf("jobqueue") != -1) { // Dump jobqueue stats x = executeUncachedQuery("select n_distinct, most_common_vals, most_common_freqs from pg_stats where tablename='jobqueue' and attname='status'",null,true,-1,null,null); for (int k = 0; k < x.getRowCount(); k++) { IResultRow row = x.getRow(k); Logging.db.warn(" Stats: n_distinct="+row.getValue("n_distinct").toString()+" most_common_vals="+row.getValue("most_common_vals").toString()+" most_common_freqs="+row.getValue("most_common_freqs").toString()); } Logging.db.warn(""); } } /** Read a datum, presuming zero if the datum does not exist. */ protected int readDatum(String datumName) throws ManifoldCFException { byte[] bytes = lockManager.readData(datumName); if (bytes == null) return 0; return (((int)bytes[0]) & 0xff) + ((((int)bytes[1]) & 0xff) << 8) + ((((int)bytes[2]) & 0xff) << 16) + ((((int)bytes[3]) & 0xff) << 24); } /** Write a datum, presuming zero if the datum does not exist. */ protected void writeDatum(String datumName, int value) throws ManifoldCFException { byte[] bytes = new byte[4]; bytes[0] = (byte)(value & 0xff); bytes[1] = (byte)((value >> 8) & 0xff); bytes[2] = (byte)((value >> 16) & 0xff); bytes[3] = (byte)((value >> 24) & 0xff); lockManager.writeData(datumName,bytes); } /** Analyze a table. *@param tableName is the name of the table to analyze/calculate statistics for. */ public void analyzeTable(String tableName) throws ManifoldCFException { String tableStatisticsLock = statslockAnalyzePrefix+tableName; lockManager.enterWriteCriticalSection(tableStatisticsLock); try { TableStatistics ts = currentAnalyzeStatistics.get(tableName); // Lock this table's statistics files lockManager.enterWriteLock(tableStatisticsLock); try { String eventDatum = statsAnalyzePrefix+tableName; // Time to reindex this table! analyzeTableInternal(tableName); // Now, clear out the data writeDatum(eventDatum,0); if (ts != null) ts.reset(); } finally { lockManager.leaveWriteLock(tableStatisticsLock); } } finally { lockManager.leaveWriteCriticalSection(tableStatisticsLock); } } /** Reindex a table. *@param tableName is the name of the table to rebuild indexes for. */ public void reindexTable(String tableName) throws ManifoldCFException { String tableStatisticsLock; // Reindexing. tableStatisticsLock = statslockReindexPrefix+tableName; lockManager.enterWriteCriticalSection(tableStatisticsLock); try { TableStatistics ts = currentReindexStatistics.get(tableName); // Lock this table's statistics files lockManager.enterWriteLock(tableStatisticsLock); try { String eventDatum = statsReindexPrefix+tableName; // Time to reindex this table! reindexTableInternal(tableName); // Now, clear out the data writeDatum(eventDatum,0); if (ts != null) ts.reset(); } finally { lockManager.leaveWriteLock(tableStatisticsLock); } } finally { lockManager.leaveWriteCriticalSection(tableStatisticsLock); } } protected void analyzeTableInternal(String tableName) throws ManifoldCFException { if (getTransactionID() == null) performModification("ANALYZE "+tableName,null,null); else tablesToAnalyze.add(tableName); } protected void reindexTableInternal(String tableName) throws ManifoldCFException { if (getTransactionID() == null) { long sleepAmt = 0L; while (true) { try { performModification("REINDEX TABLE "+tableName,null,null); break; } catch (ManifoldCFException e) { if (e.getErrorCode() == e.DATABASE_TRANSACTION_ABORT) { sleepAmt = getSleepAmt(); continue; } throw e; } finally { sleepFor(sleepAmt); } } } else tablesToReindex.add(tableName); } /** Note a number of inserts, modifications, or deletions to a specific table. This is so we can decide when to do appropriate maintenance. *@param tableName is the name of the table being modified. *@param insertCount is the number of inserts. *@param modifyCount is the number of updates. *@param deleteCount is the number of deletions. */ @Override protected void noteModificationsNoTransactions(String tableName, int insertCount, int modifyCount, int deleteCount) throws ManifoldCFException { String tableStatisticsLock; int eventCount; // Reindexing. // Here we count tuple deletion. So we want to know the deletecount + modifycount. eventCount = modifyCount + deleteCount; tableStatisticsLock = statslockReindexPrefix+tableName; lockManager.enterWriteCriticalSection(tableStatisticsLock); try { Integer threshold = reindexThresholds.get(tableName); int reindexThreshold; if (threshold == null) { // Look for this parameter; if we don't find it, use a default value. reindexThreshold = lockManager.getSharedConfiguration().getIntProperty("org.apache.manifoldcf.db.postgres.reindex."+tableName,250000); reindexThresholds.put(tableName,new Integer(reindexThreshold)); } else reindexThreshold = threshold.intValue(); TableStatistics ts = currentReindexStatistics.get(tableName); if (ts == null) { ts = new TableStatistics(); currentReindexStatistics.put(tableName,ts); } ts.add(eventCount); // Check if we have passed threshold yet for this table, for committing the data to the shared area if (ts.getEventCount() >= commitThreshold) { // Lock this table's statistics files lockManager.enterWriteLock(tableStatisticsLock); try { String eventDatum = statsReindexPrefix+tableName; int oldEventCount = readDatum(eventDatum); oldEventCount += ts.getEventCount(); if (oldEventCount >= reindexThreshold) { // Time to reindex this table! reindexTableInternal(tableName); // Now, clear out the data writeDatum(eventDatum,0); } else writeDatum(eventDatum,oldEventCount); ts.reset(); } finally { lockManager.leaveWriteLock(tableStatisticsLock); } } } finally { lockManager.leaveWriteCriticalSection(tableStatisticsLock); } // Analysis. // Here we count tuple addition. eventCount = modifyCount + insertCount; tableStatisticsLock = statslockAnalyzePrefix+tableName; lockManager.enterWriteCriticalSection(tableStatisticsLock); try { Integer threshold = analyzeThresholds.get(tableName); int analyzeThreshold; if (threshold == null) { // Look for this parameter; if we don't find it, use a default value. analyzeThreshold = lockManager.getSharedConfiguration().getIntProperty("org.apache.manifoldcf.db.postgres.analyze."+tableName,2000); analyzeThresholds.put(tableName,new Integer(analyzeThreshold)); } else analyzeThreshold = threshold.intValue(); TableStatistics ts = currentAnalyzeStatistics.get(tableName); if (ts == null) { ts = new TableStatistics(); currentAnalyzeStatistics.put(tableName,ts); } ts.add(eventCount); // Check if we have passed threshold yet for this table, for committing the data to the shared area if (ts.getEventCount() >= commitThreshold) { // Lock this table's statistics files lockManager.enterWriteLock(tableStatisticsLock); try { String eventDatum = statsAnalyzePrefix+tableName; int oldEventCount = readDatum(eventDatum); oldEventCount += ts.getEventCount(); if (oldEventCount >= analyzeThreshold) { // Time to reindex this table! analyzeTableInternal(tableName); // Now, clear out the data writeDatum(eventDatum,0); } else writeDatum(eventDatum,oldEventCount); ts.reset(); } finally { lockManager.leaveWriteLock(tableStatisticsLock); } } } finally { lockManager.leaveWriteCriticalSection(tableStatisticsLock); } } /** Table accumulation records. */ protected static class TableStatistics { protected int eventCount = 0; public TableStatistics() { } public void reset() { eventCount = 0; } public void add(int eventCount) { this.eventCount += eventCount; } public int getEventCount() { return eventCount; } } }
framework/core/src/main/java/org/apache/manifoldcf/core/database/DBInterfacePostgreSQL.java
/* $Id: DBInterfacePostgreSQL.java 999670 2010-09-21 22:18:19Z kwright $ */ /** * 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 org.apache.manifoldcf.core.database; import org.apache.manifoldcf.core.interfaces.*; import org.apache.manifoldcf.core.system.ManifoldCF; import org.apache.manifoldcf.core.system.Logging; import java.util.*; public class DBInterfacePostgreSQL extends Database implements IDBInterface { public static final String _rcsid = "@(#)$Id: DBInterfacePostgreSQL.java 999670 2010-09-21 22:18:19Z kwright $"; /** PostgreSQL host name property */ public static final String postgresqlHostnameProperty = "org.apache.manifoldcf.postgresql.hostname"; /** PostgreSQL port property */ public static final String postgresqlPortProperty = "org.apache.manifoldcf.postgresql.port"; /** PostgreSQL ssl property */ public static final String postgresqlSslProperty = "org.apache.manifoldcf.postgresql.ssl"; private static final String _defaultUrl = "jdbc:postgresql://localhost/"; private static final String _driver = "org.postgresql.Driver"; /** A lock manager handle. */ protected final ILockManager lockManager; // Database cache key protected final String cacheKey; // Postgresql serializable transactions are broken in that transactions that occur within them do not in fact work properly. // So, once we enter the serializable realm, STOP any additional transactions from doing anything at all. protected int serializableDepth = 0; // This is where we keep track of tables that we need to analyze on transaction exit protected List<String> tablesToAnalyze = new ArrayList<String>(); // Keep track of tables to reindex on transaction exit protected List<String> tablesToReindex = new ArrayList<String>(); // This is where we keep temporary table statistics, which accumulate until they reach a threshold, and then are added into shared memory. /** Accumulated reindex statistics. This map is keyed by the table name, and contains TableStatistics values. */ protected static Map<String,TableStatistics> currentReindexStatistics = new HashMap<String,TableStatistics>(); /** Table reindex thresholds, as read from configuration information. Keyed by table name, contains Integer values. */ protected static Map<String,Integer> reindexThresholds = new HashMap<String,Integer>(); /** Accumulated analyze statistics. This map is keyed by the table name, and contains TableStatistics values. */ protected static Map<String,TableStatistics> currentAnalyzeStatistics = new HashMap<String,TableStatistics>(); /** Table analyze thresholds, as read from configuration information. Keyed by table name, contains Integer values. */ protected static Map<String,Integer> analyzeThresholds = new HashMap<String,Integer>(); /** The number of inserts, deletes, etc. before we update the shared area. */ protected static final int commitThreshold = 100; // Lock and shared datum name prefixes (to be combined with table names) protected static final String statslockReindexPrefix = "statslock-reindex-"; protected static final String statsReindexPrefix = "stats-reindex-"; protected static final String statslockAnalyzePrefix = "statslock-analyze-"; protected static final String statsAnalyzePrefix = "stats-analyze-"; public DBInterfacePostgreSQL(IThreadContext tc, String databaseName, String userName, String password) throws ManifoldCFException { super(tc,getJdbcUrl(tc,databaseName),_driver,databaseName,userName,password); cacheKey = CacheKeyFactory.makeDatabaseKey(this.databaseName); lockManager = LockManagerFactory.make(tc); } private static String getJdbcUrl(final IThreadContext tc, final String databaseName) throws ManifoldCFException { String jdbcUrl = _defaultUrl + databaseName; final String hostname = LockManagerFactory.getProperty(tc,postgresqlHostnameProperty); final String ssl = LockManagerFactory.getProperty(tc,postgresqlSslProperty); final String port = LockManagerFactory.getProperty(tc,postgresqlPortProperty); if (hostname != null && hostname.length() > 0) { jdbcUrl = "jdbc:postgresql://" + hostname; if (port != null && port.length() > 0) { jdbcUrl += ":" + port; } jdbcUrl += "/" + databaseName; if (ssl != null && ssl.equals("true")) { jdbcUrl += "?ssl=true"; } } return jdbcUrl; } /** Initialize. This method is called once per JVM instance, in order to set up * database communication. */ @Override public void openDatabase() throws ManifoldCFException { // Nothing to do } /** Uninitialize. This method is called during JVM shutdown, in order to close * all database communication. */ @Override public void closeDatabase() throws ManifoldCFException { // Nothing to do } /** Get the database general cache key. *@return the general cache key for the database. */ @Override public String getDatabaseCacheKey() { return cacheKey; } /** Perform an insert operation. *@param tableName is the name of the table. *@param invalidateKeys are the cache keys that should be * invalidated. *@param parameterMap is the map of column name/values to write. */ @Override public void performInsert(String tableName, Map<String,Object> parameterMap, StringSet invalidateKeys) throws ManifoldCFException { List paramArray = new ArrayList(); StringBuilder bf = new StringBuilder(); bf.append("INSERT INTO "); bf.append(tableName); bf.append(" (") ; StringBuilder values = new StringBuilder(" VALUES ("); // loop for cols Iterator<Map.Entry<String,Object>> it = parameterMap.entrySet().iterator(); boolean first = true; while (it.hasNext()) { Map.Entry<String,Object> e = it.next(); String key = e.getKey(); Object o = e.getValue(); if (o != null) { paramArray.add(o); if (!first) { bf.append(','); values.append(','); } bf.append(key); values.append('?'); first = false; } } bf.append(')'); values.append(')'); bf.append(values); // Do the modification performModification(bf.toString(),paramArray,invalidateKeys); } /** Perform an update operation. *@param tableName is the name of the table. *@param invalidateKeys are the cache keys that should be invalidated. *@param parameterMap is the map of column name/values to write. *@param whereClause is the where clause describing the match (including the WHERE), or null if none. *@param whereParameters are the parameters that come with the where clause, if any. */ @Override public void performUpdate(String tableName, Map<String,Object> parameterMap, String whereClause, List whereParameters, StringSet invalidateKeys) throws ManifoldCFException { List paramArray = new ArrayList(); StringBuilder bf = new StringBuilder(); bf.append("UPDATE "); bf.append(tableName); bf.append(" SET ") ; // loop for parameters Iterator<Map.Entry<String,Object>> it = parameterMap.entrySet().iterator(); boolean first = true; while (it.hasNext()) { Map.Entry<String,Object> e = it.next(); String key = e.getKey(); Object o = e.getValue(); if (!first) { bf.append(','); } bf.append(key); bf.append('='); if (o == null) { bf.append("NULL"); } else { bf.append('?'); paramArray.add(o); } first = false; } if (whereClause != null) { bf.append(' '); bf.append(whereClause); if (whereParameters != null) { for (int i = 0; i < whereParameters.size(); i++) { Object value = whereParameters.get(i); paramArray.add(value); } } } // Do the modification performModification(bf.toString(),paramArray,invalidateKeys); } /** Perform a delete operation. *@param tableName is the name of the table to delete from. *@param invalidateKeys are the cache keys that should be invalidated. *@param whereClause is the where clause describing the match (including the WHERE), or null if none. *@param whereParameters are the parameters that come with the where clause, if any. */ @Override public void performDelete(String tableName, String whereClause, List whereParameters, StringSet invalidateKeys) throws ManifoldCFException { StringBuilder bf = new StringBuilder(); bf.append("DELETE FROM "); bf.append(tableName); if (whereClause != null) { bf.append(' '); bf.append(whereClause); } else whereParameters = null; // Do the modification performModification(bf.toString(),whereParameters,invalidateKeys); } /** Perform a table creation operation. *@param tableName is the name of the table to create. *@param columnMap is the map describing the columns and types. NOTE that these are abstract * types, which will be mapped to the proper types for the actual database inside this * layer. *@param invalidateKeys are the cache keys that should be invalidated, if any. */ @Override public void performCreate(String tableName, Map<String,ColumnDescription> columnMap, StringSet invalidateKeys) throws ManifoldCFException { StringBuilder queryBuffer = new StringBuilder("CREATE TABLE "); queryBuffer.append(tableName); queryBuffer.append('('); Iterator<String> iter = columnMap.keySet().iterator(); boolean first = true; while (iter.hasNext()) { String columnName = iter.next(); ColumnDescription cd = columnMap.get(columnName); if (!first) queryBuffer.append(','); else first = false; appendDescription(queryBuffer,columnName,cd,false); } queryBuffer.append(')'); performModification(queryBuffer.toString(),null,invalidateKeys); } protected static void appendDescription(StringBuilder queryBuffer, String columnName, ColumnDescription cd, boolean forceNull) { queryBuffer.append(columnName); queryBuffer.append(' '); queryBuffer.append(mapType(cd.getTypeString())); if (forceNull || cd.getIsNull()) queryBuffer.append(" NULL"); else queryBuffer.append(" NOT NULL"); if (cd.getIsPrimaryKey()) queryBuffer.append(" PRIMARY KEY"); if (cd.getReferenceTable() != null) { queryBuffer.append(" REFERENCES "); queryBuffer.append(cd.getReferenceTable()); queryBuffer.append('('); queryBuffer.append(cd.getReferenceColumn()); queryBuffer.append(") ON DELETE"); if (cd.getReferenceCascade()) queryBuffer.append(" CASCADE"); else queryBuffer.append(" RESTRICT"); } } /** Perform a table alter operation. *@param tableName is the name of the table to alter. *@param columnMap is the map describing the columns and types to add. These * are in the same form as for performCreate. *@param columnModifyMap is the map describing the columns to be changed. The key is the * existing column name, and the value is the new type of the column. Data will be copied from * the old column to the new. *@param columnDeleteList is the list of column names to delete. *@param invalidateKeys are the cache keys that should be invalidated, if any. */ @Override public void performAlter(String tableName, Map<String,ColumnDescription> columnMap, Map<String,ColumnDescription> columnModifyMap, List<String> columnDeleteList, StringSet invalidateKeys) throws ManifoldCFException { beginTransaction(TRANSACTION_ENCLOSING); try { if (columnDeleteList != null) { int i = 0; while (i < columnDeleteList.size()) { String columnName = columnDeleteList.get(i++); performModification("ALTER TABLE ONLY "+tableName+" DROP "+columnName,null,invalidateKeys); } } // Do the modifies. This involves renaming each column to a temp column, then creating a new one, then copying if (columnModifyMap != null) { Iterator<String> iter = columnModifyMap.keySet().iterator(); while (iter.hasNext()) { String columnName = iter.next(); ColumnDescription cd = columnModifyMap.get(columnName); String renameColumn = "__temp__"; // Rename current column performModification("ALTER TABLE ONLY "+tableName+" RENAME "+columnName+" TO "+renameColumn,null,invalidateKeys); // Create new column StringBuilder sb = new StringBuilder(); appendDescription(sb,columnName,cd,true); performModification("ALTER TABLE ONLY "+tableName+" ADD "+sb.toString(),null,invalidateKeys); // Copy old data to new performModification("UPDATE "+tableName+" SET "+columnName+"="+renameColumn,null,invalidateKeys); // Make the column null, if it needs it if (cd.getIsNull() == false) performModification("ALTER TABLE ONLY "+tableName+" ALTER "+columnName+" SET NOT NULL",null,invalidateKeys); // Drop old column performModification("ALTER TABLE ONLY "+tableName+" DROP "+renameColumn,null,invalidateKeys); } } // Now, do the adds if (columnMap != null) { Iterator<String> iter = columnMap.keySet().iterator(); while (iter.hasNext()) { String columnName = iter.next(); ColumnDescription cd = columnMap.get(columnName); StringBuilder sb = new StringBuilder(); appendDescription(sb,columnName,cd,false); performModification("ALTER TABLE ONLY "+tableName+" ADD "+sb.toString(),null,invalidateKeys); } } } catch (ManifoldCFException e) { signalRollback(); throw e; } catch (Error e) { signalRollback(); throw e; } finally { endTransaction(); } } /** Map a standard type into a postgresql type. *@param inputType is the input type. *@return the output type. */ protected static String mapType(String inputType) { if (inputType.equalsIgnoreCase("longtext")) return "text"; if (inputType.equalsIgnoreCase("blob")) return "bytea"; return inputType; } /** Add an index to a table. *@param tableName is the name of the table to add the index for. *@param unique is a boolean that if true describes a unique index. *@param columnList is the list of columns that need to be included * in the index, in order. */ @Override public void addTableIndex(String tableName, boolean unique, List<String> columnList) throws ManifoldCFException { String[] columns = new String[columnList.size()]; int i = 0; while (i < columns.length) { columns[i] = columnList.get(i); i++; } performAddIndex(null,tableName,new IndexDescription(unique,columns)); } /** Add an index to a table. *@param tableName is the name of the table to add the index for. *@param indexName is the optional name of the table index. If null, a name will be chosen automatically. *@param description is the index description. */ @Override public void performAddIndex(String indexName, String tableName, IndexDescription description) throws ManifoldCFException { String[] columnNames = description.getColumnNames(); if (columnNames.length == 0) return; if (indexName == null) // Build an index name indexName = "I"+IDFactory.make(context); StringBuilder queryBuffer = new StringBuilder("CREATE "); if (description.getIsUnique()) queryBuffer.append("UNIQUE "); queryBuffer.append("INDEX "); queryBuffer.append(indexName); queryBuffer.append(" ON "); queryBuffer.append(tableName); queryBuffer.append(" ("); int i = 0; while (i < columnNames.length) { String colName = columnNames[i]; if (i > 0) queryBuffer.append(','); queryBuffer.append(colName); i++; } queryBuffer.append(')'); performModification(queryBuffer.toString(),null,null); } /** Remove an index. *@param indexName is the name of the index to remove. *@param tableName is the table the index belongs to. */ @Override public void performRemoveIndex(String indexName, String tableName) throws ManifoldCFException { performModification("DROP INDEX "+indexName,null,null); } /** Perform a table drop operation. *@param tableName is the name of the table to drop. *@param invalidateKeys are the cache keys that should be invalidated, if any. */ @Override public void performDrop(String tableName, StringSet invalidateKeys) throws ManifoldCFException { performModification("DROP TABLE "+tableName,null,invalidateKeys); } /** Create user and database. *@param adminUserName is the admin user name. *@param adminPassword is the admin password. *@param invalidateKeys are the cache keys that should be invalidated, if any. */ @Override public void createUserAndDatabase(String adminUserName, String adminPassword, StringSet invalidateKeys) throws ManifoldCFException { // Create a connection to the master database, using the credentials supplied Database masterDatabase = new DBInterfacePostgreSQL(context,"template1",adminUserName,adminPassword); try { // Create user List params = new ArrayList(); params.add(userName); IResultSet set = masterDatabase.executeQuery("SELECT * FROM pg_user WHERE usename=?",params, null,null,null,true,-1,null,null); if (set.getRowCount() == 0) { // We have to quote the password. Due to a postgresql bug, parameters don't work for this field. StringBuilder sb = new StringBuilder(); sb.append("'"); int i = 0; while (i < password.length()) { char x = password.charAt(i); if (x == '\'') sb.append("'"); sb.append(x); i++; } sb.append("'"); String quotedPassword = sb.toString(); masterDatabase.executeQuery("CREATE USER "+userName+" PASSWORD "+quotedPassword,null, null,invalidateKeys,null,false,0,null,null); } // Create database params.clear(); params.add(databaseName); set = masterDatabase.executeQuery("SELECT * FROM pg_database WHERE datname=?",params, null,null,null,true,-1,null,null); if (set.getRowCount() == 0) { masterDatabase.executeQuery("CREATE DATABASE "+databaseName+" OWNER "+ userName+" ENCODING 'utf8'",null,null,invalidateKeys,null,false,0,null,null); } } catch (ManifoldCFException e) { throw reinterpretException(e); } } /** Drop user and database. *@param adminUserName is the admin user name. *@param adminPassword is the admin password. *@param invalidateKeys are the cache keys that should be invalidated, if any. */ @Override public void dropUserAndDatabase(String adminUserName, String adminPassword, StringSet invalidateKeys) throws ManifoldCFException { // Create a connection to the master database, using the credentials supplied Database masterDatabase = new DBInterfacePostgreSQL(context,"template1",adminUserName,adminPassword); try { // Drop database masterDatabase.executeQuery("DROP DATABASE "+databaseName,null,null,invalidateKeys,null,false,0,null,null); // Drop user masterDatabase.executeQuery("DROP USER "+userName,null,null,invalidateKeys,null,false,0,null,null); } catch (ManifoldCFException e) { throw reinterpretException(e); } } /** Reinterpret an exception tossed by the database layer. We need to disambiguate the various kinds of exception that * should be thrown. *@param theException is the exception to reinterpret *@return the reinterpreted exception to throw. */ protected ManifoldCFException reinterpretException(ManifoldCFException theException) { if (Logging.db.isDebugEnabled()) Logging.db.debug("Reinterpreting exception '"+theException.getMessage()+"'. The exception type is "+Integer.toString(theException.getErrorCode())); if (theException.getErrorCode() != ManifoldCFException.DATABASE_CONNECTION_ERROR) return theException; Throwable e = theException.getCause(); if (!(e instanceof java.sql.SQLException)) { //e.printStackTrace(); return theException; } if (Logging.db.isDebugEnabled()) Logging.db.debug("Exception "+theException.getMessage()+" is possibly a transaction abort signal"); java.sql.SQLException sqlException = (java.sql.SQLException)e; String message = sqlException.getMessage(); String sqlState = sqlException.getSQLState(); // Could not serialize if (sqlState != null && sqlState.equals("40001")) return new ManifoldCFException(message,e,ManifoldCFException.DATABASE_TRANSACTION_ABORT); // Deadlock detected if (sqlState != null && sqlState.equals("40P01")) return new ManifoldCFException(message,e,ManifoldCFException.DATABASE_TRANSACTION_ABORT); // Note well: We also have to treat 'duplicate key' as a transaction abort, since this is what you get when two threads attempt to // insert the same row. (Everything only works, then, as long as there is a unique constraint corresponding to every bad insert that // one could make.) if (sqlState != null && sqlState.equals("23505")) return new ManifoldCFException(message,e,ManifoldCFException.DATABASE_TRANSACTION_ABORT); // New Postgresql behavior (9.3): sometimes we don't get an exception thrown, but the transaction is dead nonetheless. if (sqlState != null && sqlState.equals("25P02")) return new ManifoldCFException(message,e,ManifoldCFException.DATABASE_TRANSACTION_ABORT); if (Logging.db.isDebugEnabled()) Logging.db.debug("Exception "+theException.getMessage()+" is NOT a transaction abort signal"); //e.printStackTrace(); //System.err.println("sqlstate = "+sqlState); return theException; } /** Perform a general database modification query. *@param query is the query string. *@param params are the parameterized values, if needed. *@param invalidateKeys are the cache keys to invalidate. */ @Override public void performModification(String query, List params, StringSet invalidateKeys) throws ManifoldCFException { try { executeQuery(query,params,null,invalidateKeys,null,false,0,null,null); } catch (ManifoldCFException e) { throw reinterpretException(e); } } /** Get a table's schema. *@param tableName is the name of the table. *@param cacheKeys are the keys against which to cache the query, or null. *@param queryClass is the name of the query class, or null. *@return a map of column names and ColumnDescription objects, describing the schema, or null if the * table doesn't exist. */ @Override public Map<String,ColumnDescription> getTableSchema(String tableName, StringSet cacheKeys, String queryClass) throws ManifoldCFException { StringBuilder query = new StringBuilder(); List list = new ArrayList(); query.append("SELECT pg_attribute.attname AS \"Field\","); query.append("CASE pg_type.typname WHEN 'int2' THEN 'smallint' WHEN 'int4' THEN 'int'"); query.append(" WHEN 'int8' THEN 'bigint' WHEN 'varchar' THEN 'varchar(' || pg_attribute.atttypmod-4 || ')'"); query.append(" WHEN 'text' THEN 'longtext'"); query.append(" WHEN 'bpchar' THEN 'char(' || pg_attribute.atttypmod-4 || ')'"); query.append(" ELSE pg_type.typname END AS \"Type\","); query.append("CASE WHEN pg_attribute.attnotnull THEN '' ELSE 'YES' END AS \"Null\","); query.append("CASE pg_type.typname WHEN 'varchar' THEN substring(pg_attrdef.adsrc from '^(.*).*$') ELSE pg_attrdef.adsrc END AS Default "); query.append("FROM pg_class INNER JOIN pg_attribute ON (pg_class.oid=pg_attribute.attrelid) INNER JOIN pg_type ON (pg_attribute.atttypid=pg_type.oid) "); query.append("LEFT JOIN pg_attrdef ON (pg_class.oid=pg_attrdef.adrelid AND pg_attribute.attnum=pg_attrdef.adnum) "); query.append("WHERE pg_class.relname=? AND pg_attribute.attnum>=1 AND NOT pg_attribute.attisdropped "); query.append("ORDER BY pg_attribute.attnum"); list.add(tableName); IResultSet set = performQuery(query.toString(),list,cacheKeys,queryClass); if (set.getRowCount() == 0) return null; // Digest the result Map<String,ColumnDescription> rval = new HashMap<String,ColumnDescription>(); int i = 0; while (i < set.getRowCount()) { IResultRow row = set.getRow(i++); String fieldName = row.getValue("Field").toString(); String type = row.getValue("Type").toString(); boolean isNull = row.getValue("Null").toString().equals("YES"); boolean isPrimaryKey = false; // row.getValue("Key").toString().equals("PRI"); rval.put(fieldName,new ColumnDescription(type,isPrimaryKey,isNull,null,null,false)); } return rval; } /** Get a table's indexes. *@param tableName is the name of the table. *@param cacheKeys are the keys against which to cache the query, or null. *@param queryClass is the name of the query class, or null. *@return a map of index names and IndexDescription objects, describing the indexes. */ @Override public Map<String,IndexDescription> getTableIndexes(String tableName, StringSet cacheKeys, String queryClass) throws ManifoldCFException { Map<String,IndexDescription> rval = new HashMap<String,IndexDescription>(); String query = "SELECT pg_catalog.pg_get_indexdef(i.indexrelid, 0, true) AS indexdef "+ "FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i "+ "WHERE c.relname = ? AND c.oid = i.indrelid AND i.indexrelid = c2.oid"; List list = new ArrayList(); list.add(tableName); IResultSet result = performQuery(query,list,cacheKeys,queryClass); int i = 0; while (i < result.getRowCount()) { IResultRow row = result.getRow(i++); String indexdef = (String)row.getValue("indexdef"); // Parse the command! boolean isUnique; int parsePosition = 0; int beforeMatch = indexdef.indexOf("CREATE UNIQUE INDEX ",parsePosition); if (beforeMatch == -1) { beforeMatch = indexdef.indexOf("CREATE INDEX ",parsePosition); if (beforeMatch == -1) throw new ManifoldCFException("Cannot parse index description: '"+indexdef+"'"); isUnique = false; parsePosition += "CREATE INDEX ".length(); } else { isUnique = true; parsePosition += "CREATE UNIQUE INDEX ".length(); } int afterMatch = indexdef.indexOf(" ON",parsePosition); if (afterMatch == -1) throw new ManifoldCFException("Cannot parse index description: '"+indexdef+"'"); String indexName = indexdef.substring(parsePosition,afterMatch); parsePosition = afterMatch + " ON".length(); int parenPosition = indexdef.indexOf("(",parsePosition); if (parenPosition == -1) throw new ManifoldCFException("Cannot parse index description: '"+indexdef+"'"); parsePosition = parenPosition + 1; List<String> columns = new ArrayList<String>(); while (true) { int nextIndex = indexdef.indexOf(",",parsePosition); int nextParenIndex = indexdef.indexOf(")",parsePosition); if (nextIndex == -1) nextIndex = nextParenIndex; if (nextIndex == -1) throw new ManifoldCFException("Cannot parse index description: '"+indexdef+"'"); if (nextParenIndex != -1 && nextParenIndex < nextIndex) nextIndex = nextParenIndex; String columnName = indexdef.substring(parsePosition,nextIndex).trim(); columns.add(columnName); if (nextIndex == nextParenIndex) break; parsePosition = nextIndex + 1; } String[] columnNames = new String[columns.size()]; int j = 0; while (j < columnNames.length) { columnNames[j] = columns.get(j); j++; } rval.put(indexName,new IndexDescription(isUnique,columnNames)); } return rval; } /** Get a database's tables. *@param cacheKeys are the cache keys for the query, or null. *@param queryClass is the name of the query class, or null. *@return the set of tables. */ @Override public StringSet getAllTables(StringSet cacheKeys, String queryClass) throws ManifoldCFException { IResultSet set = performQuery("SELECT relname FROM pg_class",null,cacheKeys,queryClass); StringSetBuffer ssb = new StringSetBuffer(); String columnName = "relname"; int i = 0; while (i < set.getRowCount()) { IResultRow row = set.getRow(i++); String value = row.getValue(columnName).toString(); ssb.add(value); } return new StringSet(ssb); } /** Perform a general "data fetch" query. *@param query is the query string. *@param params are the parameterized values, if needed. *@param cacheKeys are the cache keys, if needed (null if no cache desired). *@param queryClass is the LRU class name against which this query would be cached, * or null if no LRU behavior desired. *@return a resultset. */ @Override public IResultSet performQuery(String query, List params, StringSet cacheKeys, String queryClass) throws ManifoldCFException { try { return executeQuery(query,params,cacheKeys,null,queryClass,true,-1,null,null); } catch (ManifoldCFException e) { throw reinterpretException(e); } } /** Perform a general "data fetch" query. *@param query is the query string. *@param params are the parameterized values, if needed. *@param cacheKeys are the cache keys, if needed (null if no cache desired). *@param queryClass is the LRU class name against which this query would be cached, * or null if no LRU behavior desired. *@param maxResults is the maximum number of results returned (-1 for all). *@param returnLimit is a description of how to limit the return result, or null if no limit. *@return a resultset. */ @Override public IResultSet performQuery(String query, List params, StringSet cacheKeys, String queryClass, int maxResults, ILimitChecker returnLimit) throws ManifoldCFException { try { return executeQuery(query,params,cacheKeys,null,queryClass,true,maxResults,null,returnLimit); } catch (ManifoldCFException e) { throw reinterpretException(e); } } /** Perform a general "data fetch" query. *@param query is the query string. *@param params are the parameterized values, if needed. *@param cacheKeys are the cache keys, if needed (null if no cache desired). *@param queryClass is the LRU class name against which this query would be cached, * or null if no LRU behavior desired. *@param maxResults is the maximum number of results returned (-1 for all). *@param resultSpec is a result specification, or null for the standard treatment. *@param returnLimit is a description of how to limit the return result, or null if no limit. *@return a resultset. */ @Override public IResultSet performQuery(String query, List params, StringSet cacheKeys, String queryClass, int maxResults, ResultSpecification resultSpec, ILimitChecker returnLimit) throws ManifoldCFException { try { return executeQuery(query,params,cacheKeys,null,queryClass,true,maxResults,resultSpec,returnLimit); } catch (ManifoldCFException e) { throw reinterpretException(e); } } /** Construct a cast to a double value. * On most databases this cast needs to be explicit, but on some it is implicit (and cannot be in fact * specified). *@param value is the value to be cast. *@return the query chunk needed. */ @Override public String constructDoubleCastClause(String value) { return "CAST("+value+" AS DOUBLE PRECISION)"; } /** Construct a count clause. * On most databases this will be COUNT(col), but on some the count needs to be cast to a BIGINT, so * CAST(COUNT(col) AS BIGINT) will be emitted instead. *@param column is the column string to be counted. *@return the query chunk needed. */ @Override public String constructCountClause(String column) { return "COUNT("+column+")"; } /** Construct a regular-expression match clause. * This method builds both the text part of a regular-expression match. *@param column is the column specifier string. *@param regularExpression is the properly-quoted regular expression string, or "?" if a parameterized value is to be used. *@param caseInsensitive is true of the regular expression match is to be case insensitive. *@return the query chunk needed, not padded with spaces on either side. */ @Override public String constructRegexpClause(String column, String regularExpression, boolean caseInsensitive) { return column + "~" + (caseInsensitive?"*":"") + regularExpression; } /** Construct a regular-expression substring clause. * This method builds an expression that extracts a specified string section from a field, based on * a regular expression. *@param column is the column specifier string. *@param regularExpression is the properly-quoted regular expression string, or "?" if a parameterized value is to be used. *@param caseInsensitive is true if the regular expression match is to be case insensitive. *@return the expression chunk needed, not padded with spaces on either side. */ @Override public String constructSubstringClause(String column, String regularExpression, boolean caseInsensitive) { StringBuilder sb = new StringBuilder(); sb.append("SUBSTRING("); if (caseInsensitive) sb.append("LOWER(").append(column).append(")"); else sb.append(column); sb.append(" FROM "); if (caseInsensitive) sb.append("LOWER(").append(regularExpression).append(")"); else sb.append(regularExpression); sb.append(")"); return sb.toString(); } /** Construct an offset/limit clause. * This method constructs an offset/limit clause in the proper manner for the database in question. *@param offset is the starting offset number. *@param limit is the limit of result rows to return. *@param afterOrderBy is true if this offset/limit comes after an ORDER BY. *@return the proper clause, with no padding spaces on either side. */ @Override public String constructOffsetLimitClause(int offset, int limit, boolean afterOrderBy) { StringBuilder sb = new StringBuilder(); if (offset != 0) sb.append("OFFSET ").append(Integer.toString(offset)); if (limit != -1) { if (offset != 0) sb.append(" "); sb.append("LIMIT ").append(Integer.toString(limit)); } return sb.toString(); } /** Construct a 'distinct on (x)' filter. * This filter wraps a query and returns a new query whose results are similar to POSTGRESQL's DISTINCT-ON feature. * Specifically, for each combination of the specified distinct fields in the result, only the first such row is included in the final * result. *@param outputParameters is a blank list into which to put parameters. Null may be used if the baseParameters parameter is null. *@param baseQuery is the base query, which is another SELECT statement, without parens, * e.g. "SELECT ..." *@param baseParameters are the parameters corresponding to the baseQuery. *@param distinctFields are the fields to consider to be distinct. These should all be keys in otherFields below. *@param orderFields are the otherfield keys that determine the ordering. *@param orderFieldsAscending are true for orderFields that are ordered as ASC, false for DESC. *@param otherFields are the rest of the fields to return, keyed by the AS name, value being the base query column value, e.g. "value AS key" *@return a revised query that performs the necessary DISTINCT ON operation. The list outputParameters will also be appropriately filled in. */ @Override public String constructDistinctOnClause(List outputParameters, String baseQuery, List baseParameters, String[] distinctFields, String[] orderFields, boolean[] orderFieldsAscending, Map<String,String> otherFields) { // Copy arguments if (baseParameters != null) outputParameters.addAll(baseParameters); StringBuilder sb = new StringBuilder("SELECT DISTINCT ON("); int i = 0; while (i < distinctFields.length) { if (i > 0) sb.append(","); sb.append(distinctFields[i++]); } sb.append(") "); Iterator<String> iter = otherFields.keySet().iterator(); boolean needComma = false; while (iter.hasNext()) { String fieldName = iter.next(); String columnValue = otherFields.get(fieldName); if (needComma) sb.append(","); needComma = true; sb.append("txxx1.").append(columnValue).append(" AS ").append(fieldName); } sb.append(" FROM (").append(baseQuery).append(") txxx1"); if (distinctFields.length > 0 || orderFields.length > 0) { sb.append(" ORDER BY "); int k = 0; i = 0; while (i < distinctFields.length) { if (k > 0) sb.append(","); sb.append(distinctFields[i]).append(" ASC"); k++; i++; } i = 0; while (i < orderFields.length) { if (k > 0) sb.append(","); sb.append(orderFields[i]).append(" "); if (orderFieldsAscending[i]) sb.append("ASC"); else sb.append("DESC"); i++; k++; } } return sb.toString(); } /** Obtain the maximum number of individual items that should be * present in an IN clause. Exceeding this amount will potentially cause the query performance * to drop. *@return the maximum number of IN clause members. */ @Override public int getMaxInClause() { return 100; } /** Obtain the maximum number of individual clauses that should be * present in a sequence of OR clauses. Exceeding this amount will potentially cause the query performance * to drop. *@return the maximum number of OR clause members. */ @Override public int getMaxOrClause() { return 25; } /* Calculate the number of values a particular clause can have, given the values for all the other clauses. * For example, if in the expression x AND y AND z, x has 2 values and z has 1, find out how many values x can legally have * when using the buildConjunctionClause() method below. */ @Override public int findConjunctionClauseMax(ClauseDescription[] otherClauseDescriptions) { // This implementation uses "OR" return getMaxOrClause(); } /* Construct a conjunction clause, e.g. x AND y AND z, where there is expected to be an index (x,y,z,...), and where x, y, or z * can have multiple distinct values, The proper implementation of this method differs from database to database, because some databases * only permit index operations when there are OR's between clauses, such as x1 AND y1 AND z1 OR x2 AND y2 AND z2 ..., where others * only recognize index operations when there are lists specified for each, such as x IN (x1,x2) AND y IN (y1,y2) AND z IN (z1,z2). */ @Override public String buildConjunctionClause(List outputParameters, ClauseDescription[] clauseDescriptions) { // This implementation uses "OR" instead of "IN ()" for multiple values, since this generates better plans in Postgresql 9.x. StringBuilder sb = new StringBuilder(); for (int i = 0 ; i < clauseDescriptions.length ; i++) { ClauseDescription cd = clauseDescriptions[i]; if (i > 0) sb.append(" AND "); String columnName = cd.getColumnName(); List values = cd.getValues(); String operation = cd.getOperation(); String joinColumn = cd.getJoinColumnName(); if (values != null) { if (values.size() > 1) { sb.append(" ("); for (int j = 0 ; j < values.size() ; j++) { if (j > 0) sb.append(" OR "); sb.append(columnName).append(operation).append("?"); outputParameters.add(values.get(j)); } sb.append(")"); } else { sb.append(columnName).append(operation).append("?"); outputParameters.add(values.get(0)); } } else if (joinColumn != null) { sb.append(columnName).append(operation).append(joinColumn); } else sb.append(columnName).append(operation); } return sb.toString(); } /** For windowed report queries, e.g. maxActivity or maxBandwidth, obtain the maximum number of rows * that can reasonably be expected to complete in an acceptable time. *@return the maximum number of rows. */ @Override public int getWindowedReportMaxRows() { return 5000; } /** Begin a database transaction. This method call MUST be paired with an endTransaction() call, * or database handles will be lost. If the transaction should be rolled back, then signalRollback() should * be called before the transaction is ended. * It is strongly recommended that the code that uses transactions be structured so that a try block * starts immediately after this method call. The body of the try block will contain all direct or indirect * calls to executeQuery(). After this should be a catch for every exception type, including Error, which should call the * signalRollback() method, and rethrow the exception. Then, after that a finally{} block which calls endTransaction(). */ @Override public void beginTransaction() throws ManifoldCFException { beginTransaction(TRANSACTION_ENCLOSING); } /** Begin a database transaction. This method call MUST be paired with an endTransaction() call, * or database handles will be lost. If the transaction should be rolled back, then signalRollback() should * be called before the transaction is ended. * It is strongly recommended that the code that uses transactions be structured so that a try block * starts immediately after this method call. The body of the try block will contain all direct or indirect * calls to executeQuery(). After this should be a catch for every exception type, including Error, which should call the * signalRollback() method, and rethrow the exception. Then, after that a finally{} block which calls endTransaction(). *@param transactionType is the kind of transaction desired. */ @Override public void beginTransaction(int transactionType) throws ManifoldCFException { if (getCurrentTransactionType() == TRANSACTION_SERIALIZED) { serializableDepth++; return; } if (transactionType == TRANSACTION_ENCLOSING) { transactionType = getCurrentTransactionType(); } switch (transactionType) { case TRANSACTION_READCOMMITTED: super.beginTransaction(TRANSACTION_READCOMMITTED); break; case TRANSACTION_SERIALIZED: super.beginTransaction(TRANSACTION_SERIALIZED); try { performModification("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE",null,null); } catch (Error e) { super.signalRollback(); super.endTransaction(); throw e; } catch (ManifoldCFException e) { super.signalRollback(); super.endTransaction(); throw e; } break; default: throw new ManifoldCFException("Bad transaction type: "+Integer.toString(transactionType)); } } /** Signal that a rollback should occur on the next endTransaction(). */ @Override public void signalRollback() { if (serializableDepth == 0) super.signalRollback(); } /** End a database transaction, either performing a commit or a rollback (depending on whether * signalRollback() was called within the transaction). */ @Override public void endTransaction() throws ManifoldCFException { if (serializableDepth > 0) { serializableDepth--; return; } super.endTransaction(); if (getTransactionID() == null) { int i = 0; while (i < tablesToAnalyze.size()) { analyzeTableInternal(tablesToAnalyze.get(i++)); } tablesToAnalyze.clear(); i = 0; while (i < tablesToReindex.size()) { reindexTableInternal(tablesToReindex.get(i++)); } tablesToReindex.clear(); } } /** Abstract method to start a transaction */ @Override protected void startATransaction() throws ManifoldCFException { try { executeViaThread((connection==null)?null:connection.getConnection(),"START TRANSACTION",null,false,0,null,null); } catch (ManifoldCFException e) { throw reinterpretException(e); } } /** Abstract method to commit a transaction */ @Override protected void commitCurrentTransaction() throws ManifoldCFException { try { executeViaThread((connection==null)?null:connection.getConnection(),"COMMIT",null,false,0,null,null); } catch (ManifoldCFException e) { throw reinterpretException(e); } } /** Abstract method to roll back a transaction */ @Override protected void rollbackCurrentTransaction() throws ManifoldCFException { try { executeViaThread((connection==null)?null:connection.getConnection(),"ROLLBACK",null,false,0,null,null); } catch (ManifoldCFException e) { throw reinterpretException(e); } } /** Abstract method for explaining a query */ @Override protected void explainQuery(String query, List params) throws ManifoldCFException { // We really can't retry at this level; it's not clear what the transaction nesting is etc. // So if the EXPLAIN fails due to deadlock, we just give up. IResultSet x; String queryType = "EXPLAIN "; if ("SELECT".equalsIgnoreCase(query.substring(0,6))) queryType += "ANALYZE "; x = executeUncachedQuery(queryType+query,params,true, -1,null,null); for (int k = 0; k < x.getRowCount(); k++) { IResultRow row = x.getRow(k); Iterator<String> iter = row.getColumns(); String colName = (String)iter.next(); Logging.db.warn(" Plan: "+row.getValue(colName).toString()); } Logging.db.warn(""); if (query.indexOf("jobqueue") != -1) { // Dump jobqueue stats x = executeUncachedQuery("select n_distinct, most_common_vals, most_common_freqs from pg_stats where tablename='jobqueue' and attname='status'",null,true,-1,null,null); for (int k = 0; k < x.getRowCount(); k++) { IResultRow row = x.getRow(k); Logging.db.warn(" Stats: n_distinct="+row.getValue("n_distinct").toString()+" most_common_vals="+row.getValue("most_common_vals").toString()+" most_common_freqs="+row.getValue("most_common_freqs").toString()); } Logging.db.warn(""); } } /** Read a datum, presuming zero if the datum does not exist. */ protected int readDatum(String datumName) throws ManifoldCFException { byte[] bytes = lockManager.readData(datumName); if (bytes == null) return 0; return (((int)bytes[0]) & 0xff) + ((((int)bytes[1]) & 0xff) << 8) + ((((int)bytes[2]) & 0xff) << 16) + ((((int)bytes[3]) & 0xff) << 24); } /** Write a datum, presuming zero if the datum does not exist. */ protected void writeDatum(String datumName, int value) throws ManifoldCFException { byte[] bytes = new byte[4]; bytes[0] = (byte)(value & 0xff); bytes[1] = (byte)((value >> 8) & 0xff); bytes[2] = (byte)((value >> 16) & 0xff); bytes[3] = (byte)((value >> 24) & 0xff); lockManager.writeData(datumName,bytes); } /** Analyze a table. *@param tableName is the name of the table to analyze/calculate statistics for. */ public void analyzeTable(String tableName) throws ManifoldCFException { String tableStatisticsLock = statslockAnalyzePrefix+tableName; lockManager.enterWriteCriticalSection(tableStatisticsLock); try { TableStatistics ts = currentAnalyzeStatistics.get(tableName); // Lock this table's statistics files lockManager.enterWriteLock(tableStatisticsLock); try { String eventDatum = statsAnalyzePrefix+tableName; // Time to reindex this table! analyzeTableInternal(tableName); // Now, clear out the data writeDatum(eventDatum,0); if (ts != null) ts.reset(); } finally { lockManager.leaveWriteLock(tableStatisticsLock); } } finally { lockManager.leaveWriteCriticalSection(tableStatisticsLock); } } /** Reindex a table. *@param tableName is the name of the table to rebuild indexes for. */ public void reindexTable(String tableName) throws ManifoldCFException { String tableStatisticsLock; // Reindexing. tableStatisticsLock = statslockReindexPrefix+tableName; lockManager.enterWriteCriticalSection(tableStatisticsLock); try { TableStatistics ts = currentReindexStatistics.get(tableName); // Lock this table's statistics files lockManager.enterWriteLock(tableStatisticsLock); try { String eventDatum = statsReindexPrefix+tableName; // Time to reindex this table! reindexTableInternal(tableName); // Now, clear out the data writeDatum(eventDatum,0); if (ts != null) ts.reset(); } finally { lockManager.leaveWriteLock(tableStatisticsLock); } } finally { lockManager.leaveWriteCriticalSection(tableStatisticsLock); } } protected void analyzeTableInternal(String tableName) throws ManifoldCFException { if (getTransactionID() == null) performModification("ANALYZE "+tableName,null,null); else tablesToAnalyze.add(tableName); } protected void reindexTableInternal(String tableName) throws ManifoldCFException { if (getTransactionID() == null) { long sleepAmt = 0L; while (true) { try { performModification("REINDEX TABLE "+tableName,null,null); break; } catch (ManifoldCFException e) { if (e.getErrorCode() == e.DATABASE_TRANSACTION_ABORT) { sleepAmt = getSleepAmt(); continue; } throw e; } finally { sleepFor(sleepAmt); } } } else tablesToReindex.add(tableName); } /** Note a number of inserts, modifications, or deletions to a specific table. This is so we can decide when to do appropriate maintenance. *@param tableName is the name of the table being modified. *@param insertCount is the number of inserts. *@param modifyCount is the number of updates. *@param deleteCount is the number of deletions. */ @Override protected void noteModificationsNoTransactions(String tableName, int insertCount, int modifyCount, int deleteCount) throws ManifoldCFException { String tableStatisticsLock; int eventCount; // Reindexing. // Here we count tuple deletion. So we want to know the deletecount + modifycount. eventCount = modifyCount + deleteCount; tableStatisticsLock = statslockReindexPrefix+tableName; lockManager.enterWriteCriticalSection(tableStatisticsLock); try { Integer threshold = reindexThresholds.get(tableName); int reindexThreshold; if (threshold == null) { // Look for this parameter; if we don't find it, use a default value. reindexThreshold = lockManager.getSharedConfiguration().getIntProperty("org.apache.manifoldcf.db.postgres.reindex."+tableName,250000); reindexThresholds.put(tableName,new Integer(reindexThreshold)); } else reindexThreshold = threshold.intValue(); TableStatistics ts = currentReindexStatistics.get(tableName); if (ts == null) { ts = new TableStatistics(); currentReindexStatistics.put(tableName,ts); } ts.add(eventCount); // Check if we have passed threshold yet for this table, for committing the data to the shared area if (ts.getEventCount() >= commitThreshold) { // Lock this table's statistics files lockManager.enterWriteLock(tableStatisticsLock); try { String eventDatum = statsReindexPrefix+tableName; int oldEventCount = readDatum(eventDatum); oldEventCount += ts.getEventCount(); if (oldEventCount >= reindexThreshold) { // Time to reindex this table! reindexTableInternal(tableName); // Now, clear out the data writeDatum(eventDatum,0); } else writeDatum(eventDatum,oldEventCount); ts.reset(); } finally { lockManager.leaveWriteLock(tableStatisticsLock); } } } finally { lockManager.leaveWriteCriticalSection(tableStatisticsLock); } // Analysis. // Here we count tuple addition. eventCount = modifyCount + insertCount; tableStatisticsLock = statslockAnalyzePrefix+tableName; lockManager.enterWriteCriticalSection(tableStatisticsLock); try { Integer threshold = analyzeThresholds.get(tableName); int analyzeThreshold; if (threshold == null) { // Look for this parameter; if we don't find it, use a default value. analyzeThreshold = lockManager.getSharedConfiguration().getIntProperty("org.apache.manifoldcf.db.postgres.analyze."+tableName,2000); analyzeThresholds.put(tableName,new Integer(analyzeThreshold)); } else analyzeThreshold = threshold.intValue(); TableStatistics ts = currentAnalyzeStatistics.get(tableName); if (ts == null) { ts = new TableStatistics(); currentAnalyzeStatistics.put(tableName,ts); } ts.add(eventCount); // Check if we have passed threshold yet for this table, for committing the data to the shared area if (ts.getEventCount() >= commitThreshold) { // Lock this table's statistics files lockManager.enterWriteLock(tableStatisticsLock); try { String eventDatum = statsAnalyzePrefix+tableName; int oldEventCount = readDatum(eventDatum); oldEventCount += ts.getEventCount(); if (oldEventCount >= analyzeThreshold) { // Time to reindex this table! analyzeTableInternal(tableName); // Now, clear out the data writeDatum(eventDatum,0); } else writeDatum(eventDatum,oldEventCount); ts.reset(); } finally { lockManager.leaveWriteLock(tableStatisticsLock); } } } finally { lockManager.leaveWriteCriticalSection(tableStatisticsLock); } } /** Table accumulation records. */ protected static class TableStatistics { protected int eventCount = 0; public TableStatistics() { } public void reset() { eventCount = 0; } public void add(int eventCount) { this.eventCount += eventCount; } public int getEventCount() { return eventCount; } } }
Handle connection-closed exceptions properly git-svn-id: 4d319e5ed894aec93a653bc5b2159f21e28d8370@1657346 13f79535-47bb-0310-9956-ffa450edef68
framework/core/src/main/java/org/apache/manifoldcf/core/database/DBInterfacePostgreSQL.java
Handle connection-closed exceptions properly
<ide><path>ramework/core/src/main/java/org/apache/manifoldcf/core/database/DBInterfacePostgreSQL.java <ide> java.sql.SQLException sqlException = (java.sql.SQLException)e; <ide> String message = sqlException.getMessage(); <ide> String sqlState = sqlException.getSQLState(); <add> // If connection is closed, presume we are shutting down <add> if (sqlState != null && sqlState.equals("08003")) <add> return new ManifoldCFException(message,e,ManifoldCFException.INTERRUPTED); <ide> // Could not serialize <ide> if (sqlState != null && sqlState.equals("40001")) <ide> return new ManifoldCFException(message,e,ManifoldCFException.DATABASE_TRANSACTION_ABORT);
Java
mit
error: pathspec 'BOJ/14718/Main.java' did not match any file(s) known to git
db539865335713a4fc9a3d01a1003105515f9fd6
1
ISKU/Algorithm
/* * Author: Minho Kim (ISKU) * Date: January 26, 2018 * E-mail: [email protected] * * https://github.com/ISKU/Algorithm * https://www.acmicpc.net/problem/14718 */ import java.util.*; public class Main { public static void main(String... args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int K = sc.nextInt(); Soldier[] sol = new Soldier[N]; for (int i = 0; i < N; i++) sol[i] = new Soldier(sc.nextInt(), sc.nextInt(), sc.nextInt()); Arrays.sort(sol); int min = Integer.MAX_VALUE; for (int x = 0; x < N; x++) { for (int y = 0; y < N; y++) { int count = 0; for (int z = 0; z < N; z++) { if (sol[z].str <= sol[x].str && sol[z].dex <= sol[y].dex) count++; if (count == K) { min = Math.min(min, sol[x].str + sol[y].dex + sol[z].luk); break; } } } } System.out.print(min); } private static class Soldier implements Comparable<Soldier> { public int str, dex, luk; public Soldier(int str, int dex, int luk) { this.str = str; this.dex = dex; this.luk = luk; } @Override public int compareTo(Soldier o) { return this.luk - o.luk; } } }
BOJ/14718/Main.java
BOJ #14718: 용감한 용사 진수
BOJ/14718/Main.java
BOJ #14718: 용감한 용사 진수
<ide><path>OJ/14718/Main.java <add>/* <add> * Author: Minho Kim (ISKU) <add> * Date: January 26, 2018 <add> * E-mail: [email protected] <add> * <add> * https://github.com/ISKU/Algorithm <add> * https://www.acmicpc.net/problem/14718 <add> */ <add> <add>import java.util.*; <add> <add>public class Main { <add> public static void main(String... args) { <add> Scanner sc = new Scanner(System.in); <add> int N = sc.nextInt(); <add> int K = sc.nextInt(); <add> <add> Soldier[] sol = new Soldier[N]; <add> for (int i = 0; i < N; i++) <add> sol[i] = new Soldier(sc.nextInt(), sc.nextInt(), sc.nextInt()); <add> <add> Arrays.sort(sol); <add> int min = Integer.MAX_VALUE; <add> <add> for (int x = 0; x < N; x++) { <add> for (int y = 0; y < N; y++) { <add> int count = 0; <add> <add> for (int z = 0; z < N; z++) { <add> if (sol[z].str <= sol[x].str && sol[z].dex <= sol[y].dex) <add> count++; <add> if (count == K) { <add> min = Math.min(min, sol[x].str + sol[y].dex + sol[z].luk); <add> break; <add> } <add> } <add> } <add> } <add> <add> System.out.print(min); <add> } <add> <add> private static class Soldier implements Comparable<Soldier> { <add> public int str, dex, luk; <add> <add> public Soldier(int str, int dex, int luk) { <add> this.str = str; <add> this.dex = dex; <add> this.luk = luk; <add> } <add> <add> @Override <add> public int compareTo(Soldier o) { <add> return this.luk - o.luk; <add> } <add> } <add>}
Java
apache-2.0
7e9f9b17ddeaf2b4b22692297116c76242ef8fb1
0
tsweets/jdefault
package org.beer30.jdefault; import org.apache.commons.lang.math.RandomUtils; /** * Default Data for generating fake addresses * * @author tsweets * Date: 2/10/14 * Time: 6:11 PM */ public class Address extends DefaultBase { /** * random 3-5 digit number for appending to a street * * @return number string */ public static String buildingNumber() { return bothify((String) fetch("address.building_number")); } /** * Random City * @return string to represent a city */ public static String city() { return parse("address.city"); } /** * random prefix for a city ie "North" "New" * @return prefix string */ public static String cityPrefix() { return fetchString("address.city_prefix"); } /** * random city suffix ie "ton" "port" * @return suffix string */ public static String citySuffix() { return fetchString("address.city_suffix"); } /** * random country - spelled out * @return country string */ public static String country() { return fetchString("address.country"); } /** * Random latitude -90 to 90 * @return latitude string */ public static String latitude() { return RandomUtils.nextInt(180) - 90 + ""; } /** * Random longitude -180 to 180 * @return longitude string */ public static String longitude() { return RandomUtils.nextInt(360) - 180 + ""; } /** * Random secondary address ie "Apt 123" * @return secondary address string */ public static String secondaryAddress() { return numerify(fetchString("address.secondary_address")); } /** * random state - spelled out * @return state string */ public static String state() { return fetchString("address.state"); } /** * random 2 letter state - fifty main US states (no territories) * @return state code string */ public static String stateAbbr() { return stateAbbr(false); } /** * random 2 letter state * * @param allStates include all states * @return state code string */ public static String stateAbbr(boolean allStates) { String state = fetchString("address.state_abbr"); if (allStates == true) { return state; } else { while (state.equalsIgnoreCase("FM") || state.equalsIgnoreCase("FL") || state.equalsIgnoreCase("GU") || state.equalsIgnoreCase("PW") || state.equalsIgnoreCase("PA") || state.equalsIgnoreCase("PR") || state.equalsIgnoreCase("AE") || state.equalsIgnoreCase("AA") || state.equalsIgnoreCase("AP") || state.equalsIgnoreCase("MP") || state.equalsIgnoreCase("VI") || state.equalsIgnoreCase("AS") || state.equalsIgnoreCase("MH")) { state = stateAbbr(true); } } return state; } /** * random street address * @return street address string */ public static String streetAddress() { return streetAddress(false); } /** * random street address * @param includeSecondary append secondary * @return street address string */ public static String streetAddress(boolean includeSecondary) { return numerify(parse("address.street_address") + (includeSecondary ? " " + secondaryAddress() : "")); } /** * random street name * @return street name string */ public static String streetName() { return parse("address.street_name"); } /** * random street suffix ie "Lane", "Ave" * @return street suffix string */ public static String streetSuffix() { return fetchString("address.street_suffix"); } /** * random timezone in Area/Location format ie America/Denver * @return timezone string */ public static String timeZone() { return bothify(fetchString("address.time_zone")); } /** * random 5 digit number to represent a zip code * @return */ public static String zipCode() { return zipCode(false); } /** * random formatted zip code ie ###### or #####-#### or just a normal ###### * @param randomFormat do a random format * @return zip code string */ public static String zipCode(boolean randomFormat) { if (randomFormat) { return bothify(fetchString("address.postcode")); } else { return Utils.randomNumberString(5); } } }
src/main/java/org/beer30/jdefault/Address.java
package org.beer30.jdefault; import org.apache.commons.lang.math.RandomUtils; /** * Default Data for generating fake addresses * * @author tsweets * Date: 2/10/14 * Time: 6:11 PM */ public class Address extends DefaultBase { public static String buildingNumber() { return bothify((String) fetch("address.building_number")); } public static String city() { return parse("address.city"); } public static String cityPrefix() { return fetchString("address.city_prefix"); } public static String citySuffix() { return fetchString("address.city_suffix"); } public static String country() { return fetchString("address.country"); } public static String latitude() { return RandomUtils.nextInt(180) - 90 + ""; } public static String longitude() { return RandomUtils.nextInt(360) - 180 + ""; } public static String secondaryAddress() { return numerify(fetchString("address.secondary_address")); } public static String state() { return fetchString("address.state"); } public static String stateAbbr() { return stateAbbr(true); } public static String stateAbbr(boolean lowerFifty) { String state = fetchString("address.state_abbr"); if (lowerFifty == false) { return state; } else { while (state.equalsIgnoreCase("FM") || state.equalsIgnoreCase("FL") || state.equalsIgnoreCase("GU") || state.equalsIgnoreCase("PW") || state.equalsIgnoreCase("PA") || state.equalsIgnoreCase("PR") || state.equalsIgnoreCase("AE") || state.equalsIgnoreCase("AA") || state.equalsIgnoreCase("AP") || state.equalsIgnoreCase("MP") || state.equalsIgnoreCase("VI") || state.equalsIgnoreCase("AS") || state.equalsIgnoreCase("MH")) { state = stateAbbr(true); } } return state; } public static String streetAddress() { return streetAddress(false); } public static String streetAddress(boolean includeSecondary) { return numerify(parse("address.street_address") + (includeSecondary ? " " + secondaryAddress() : "")); } public static String streetName() { return parse("address.street_name"); } public static String streetSuffix() { return fetchString("address.street_suffix"); } public static String timeZone() { return bothify(fetchString("address.time_zone")); } public static String zipCode() { return zipCode(false); } public static String zipCode(boolean randomFormat) { if (randomFormat) { return bothify(fetchString("address.postcode")); } else { return Utils.randomNumberString(5); } } }
updated docs
src/main/java/org/beer30/jdefault/Address.java
updated docs
<ide><path>rc/main/java/org/beer30/jdefault/Address.java <ide> */ <ide> public class Address extends DefaultBase { <ide> <del> <add> /** <add> * random 3-5 digit number for appending to a street <add> * <add> * @return number string <add> */ <ide> public static String buildingNumber() { <ide> return bothify((String) fetch("address.building_number")); <ide> } <ide> <add> /** <add> * Random City <add> * @return string to represent a city <add> */ <ide> public static String city() { <ide> return parse("address.city"); <ide> <ide> } <ide> <add> /** <add> * random prefix for a city ie "North" "New" <add> * @return prefix string <add> */ <ide> public static String cityPrefix() { <ide> return fetchString("address.city_prefix"); <ide> } <ide> <add> /** <add> * random city suffix ie "ton" "port" <add> * @return suffix string <add> */ <ide> public static String citySuffix() { <ide> return fetchString("address.city_suffix"); <ide> } <ide> <add> /** <add> * random country - spelled out <add> * @return country string <add> */ <ide> public static String country() { <ide> return fetchString("address.country"); <ide> } <ide> <add> /** <add> * Random latitude -90 to 90 <add> * @return latitude string <add> */ <ide> public static String latitude() { <ide> return RandomUtils.nextInt(180) - 90 + ""; <ide> } <ide> <add> /** <add> * Random longitude -180 to 180 <add> * @return longitude string <add> */ <ide> public static String longitude() { <ide> return RandomUtils.nextInt(360) - 180 + ""; <ide> <ide> } <ide> <add> /** <add> * Random secondary address ie "Apt 123" <add> * @return secondary address string <add> */ <ide> public static String secondaryAddress() { <ide> return numerify(fetchString("address.secondary_address")); <ide> } <ide> <add> /** <add> * random state - spelled out <add> * @return state string <add> */ <ide> public static String state() { <ide> return fetchString("address.state"); <ide> } <ide> <add> /** <add> * random 2 letter state - fifty main US states (no territories) <add> * @return state code string <add> */ <ide> public static String stateAbbr() { <del> return stateAbbr(true); <add> return stateAbbr(false); <ide> } <ide> <del> public static String stateAbbr(boolean lowerFifty) { <add> /** <add> * random 2 letter state <add> * <add> * @param allStates include all states <add> * @return state code string <add> */ <add> public static String stateAbbr(boolean allStates) { <ide> String state = fetchString("address.state_abbr"); <del> if (lowerFifty == false) { <add> if (allStates == true) { <ide> return state; <ide> } else { <ide> while (state.equalsIgnoreCase("FM") || state.equalsIgnoreCase("FL") || state.equalsIgnoreCase("GU") <ide> return state; <ide> } <ide> <add> /** <add> * random street address <add> * @return street address string <add> */ <ide> public static String streetAddress() { <ide> return streetAddress(false); <ide> } <ide> <add> /** <add> * random street address <add> * @param includeSecondary append secondary <add> * @return street address string <add> */ <ide> public static String streetAddress(boolean includeSecondary) { <ide> return numerify(parse("address.street_address") + (includeSecondary ? " " + secondaryAddress() : "")); <ide> } <ide> <add> /** <add> * random street name <add> * @return street name string <add> */ <ide> public static String streetName() { <ide> return parse("address.street_name"); <ide> } <ide> <add> /** <add> * random street suffix ie "Lane", "Ave" <add> * @return street suffix string <add> */ <ide> public static String streetSuffix() { <ide> return fetchString("address.street_suffix"); <ide> } <ide> <add> /** <add> * random timezone in Area/Location format ie America/Denver <add> * @return timezone string <add> */ <ide> public static String timeZone() { <ide> return bothify(fetchString("address.time_zone")); <ide> } <ide> <add> /** <add> * random 5 digit number to represent a zip code <add> * @return <add> */ <ide> public static String zipCode() { <ide> return zipCode(false); <ide> } <add> <add> /** <add> * random formatted zip code ie ###### or #####-#### or just a normal ###### <add> * @param randomFormat do a random format <add> * @return zip code string <add> */ <ide> public static String zipCode(boolean randomFormat) { <ide> if (randomFormat) { <ide> return bothify(fetchString("address.postcode"));
Java
apache-2.0
f8375d4e6aefc0b84c14326998ee281f9b34fe63
0
xebia/Xebium,xebia/Xebium,denniebouman/Xebium,xebia/Xebium,rselie/Xebium,denniebouman/Xebium,denniebouman/Xebium,rselie/Xebium,sglebs/Xebium,sglebs/Xebium,sglebs/Xebium,rselie/Xebium,denniebouman/Xebium,sglebs/Xebium,rselie/Xebium,xebia/Xebium
package com.xebia.incubator.xebium.fastseleniumemulation; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.internal.seleniumemulation.AlertOverride; import org.openqa.selenium.internal.seleniumemulation.SeleneseCommand; public class Type extends SeleneseCommand<Void> { private final AlertOverride alertOverride; private final ElementFinder finder; public Type(AlertOverride alertOverride, ElementFinder finder) { this.alertOverride = alertOverride; this.finder = finder; } @Override protected Void handleSeleneseCommand(WebDriver driver, String locator, String value) { alertOverride.replaceAlertMethod(driver); if (value == null) { value = ""; } value = value.replace("\\10", Keys.ENTER); value = value.replace("\\13", Keys.RETURN); value = value.replace("\\27", Keys.ESCAPE); value = value.replace("\\38", Keys.ARROW_UP); value = value.replace("\\40", Keys.ARROW_DOWN); value = value.replace("\\37", Keys.ARROW_LEFT); value = value.replace("\\39", Keys.ARROW_RIGHT); WebElement element = finder.findElement(driver, locator); clear(element); element.sendKeys(value); triggerEvents(element, driver); return null; } // Make sure onchange/onblur are triggered private void triggerEvents(WebElement element, WebDriver driver) { if ("input".equalsIgnoreCase(element.getTagName())) { driver.findElement(By.tagName("body")).click(); } } private void clear(WebElement element) { String tagName = element.getTagName(); if (("input".equalsIgnoreCase(tagName) || "textarea".equalsIgnoreCase(tagName)) && element.isEnabled()) { element.clear(); } } }
src/main/java/com/xebia/incubator/xebium/fastseleniumemulation/Type.java
package com.xebia.incubator.xebium.fastseleniumemulation; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.internal.seleniumemulation.AlertOverride; import org.openqa.selenium.internal.seleniumemulation.SeleneseCommand; public class Type extends SeleneseCommand<Void> { private final AlertOverride alertOverride; private final ElementFinder finder; public Type(AlertOverride alertOverride, ElementFinder finder) { this.alertOverride = alertOverride; this.finder = finder; } @Override protected Void handleSeleneseCommand(WebDriver driver, String locator, String value) { alertOverride.replaceAlertMethod(driver); value = value.replace("\\10", Keys.ENTER); value = value.replace("\\13", Keys.RETURN); value = value.replace("\\27", Keys.ESCAPE); value = value.replace("\\38", Keys.ARROW_UP); value = value.replace("\\40", Keys.ARROW_DOWN); value = value.replace("\\37", Keys.ARROW_LEFT); value = value.replace("\\39", Keys.ARROW_RIGHT); WebElement element = finder.findElement(driver, locator); clear(element); element.sendKeys(value); triggerEvents(driver); return null; } // Make sure onchange/onblur are triggered private void triggerEvents(WebDriver driver) { driver.findElement(By.tagName("body")).click(); } private void clear(WebElement element) { if (isInput(element) && element.isEnabled()) { element.clear(); } } private boolean isInput(WebElement element) { String tagName = element.getTagName(); return "input".equalsIgnoreCase(tagName) || "textarea".equalsIgnoreCase(tagName); } }
Allow empty value for Type
src/main/java/com/xebia/incubator/xebium/fastseleniumemulation/Type.java
Allow empty value for Type
<ide><path>rc/main/java/com/xebia/incubator/xebium/fastseleniumemulation/Type.java <ide> protected Void handleSeleneseCommand(WebDriver driver, String locator, String value) { <ide> alertOverride.replaceAlertMethod(driver); <ide> <add> if (value == null) { <add> value = ""; <add> } <ide> value = value.replace("\\10", Keys.ENTER); <ide> value = value.replace("\\13", Keys.RETURN); <ide> value = value.replace("\\27", Keys.ESCAPE); <ide> <ide> clear(element); <ide> element.sendKeys(value); <del> triggerEvents(driver); <add> triggerEvents(element, driver); <ide> <ide> return null; <ide> } <ide> <ide> // Make sure onchange/onblur are triggered <del> private void triggerEvents(WebDriver driver) { <del> driver.findElement(By.tagName("body")).click(); <add> private void triggerEvents(WebElement element, WebDriver driver) { <add> if ("input".equalsIgnoreCase(element.getTagName())) { <add> driver.findElement(By.tagName("body")).click(); <add> } <ide> } <ide> <ide> private void clear(WebElement element) { <del> if (isInput(element) && element.isEnabled()) { <add> String tagName = element.getTagName(); <add> if (("input".equalsIgnoreCase(tagName) || "textarea".equalsIgnoreCase(tagName)) && element.isEnabled()) { <ide> element.clear(); <ide> } <ide> } <ide> <del> private boolean isInput(WebElement element) { <del> String tagName = element.getTagName(); <del> return "input".equalsIgnoreCase(tagName) || "textarea".equalsIgnoreCase(tagName); <del> } <ide> }
Java
apache-2.0
c14d2408b7596f7c5cf6dd6374244c76e3af6f10
0
eFaps/eFapsApp-Sales
//CHECKSTYLE:OFF package org.efaps.esjp.ci; import org.efaps.admin.program.esjp.EFapsApplication; import org.efaps.admin.program.esjp.EFapsNoUpdate; import org.efaps.admin.program.esjp.EFapsUUID; import org.efaps.ci.CIMsgPhrase; /** * This class is only used in case that the HumanResource App is not installed * to be able to compile the classes. * @author The eFaps Team */ @EFapsUUID("e8633952-4b53-4000-a66c-2ee62e99966e") @EFapsApplication("eFapsApp-Sales") @EFapsNoUpdate public final class CIMsgHumanResource { public static final _EmployeeWithNumberMsgPhrase EmployeeWithNumberMsgPhrase = new _EmployeeWithNumberMsgPhrase("c6686d34-f9d7-4bf4-b9f1-80dad440eac4"); public static class _EmployeeWithNumberMsgPhrase extends CIMsgPhrase { protected _EmployeeWithNumberMsgPhrase(final String _uuid) { super(_uuid); } } }
src/main/efaps/ESJP/org/efaps/esjp/ci/CIMsgHumanResource.java
//CHECKSTYLE:OFF package org.efaps.esjp.ci; import org.efaps.admin.program.esjp.EFapsApplication; import org.efaps.admin.program.esjp.EFapsNoUpdate; import org.efaps.ci.CIMsgPhrase; /** * This class is only used in case that the HumanResource App is not installed * to be able to compile the classes. * @author The eFaps Team */ @EFapsApplication("eFapsApp-Sales") @EFapsNoUpdate public final class CIMsgHumanResource { public static final _EmployeeWithNumberMsgPhrase EmployeeWithNumberMsgPhrase = new _EmployeeWithNumberMsgPhrase("c6686d34-f9d7-4bf4-b9f1-80dad440eac4"); public static class _EmployeeWithNumberMsgPhrase extends CIMsgPhrase { protected _EmployeeWithNumberMsgPhrase(final String _uuid) { super(_uuid); } } }
- adding missing UUID
src/main/efaps/ESJP/org/efaps/esjp/ci/CIMsgHumanResource.java
- adding missing UUID
<ide><path>rc/main/efaps/ESJP/org/efaps/esjp/ci/CIMsgHumanResource.java <ide> package org.efaps.esjp.ci; <ide> import org.efaps.admin.program.esjp.EFapsApplication; <ide> import org.efaps.admin.program.esjp.EFapsNoUpdate; <add>import org.efaps.admin.program.esjp.EFapsUUID; <ide> import org.efaps.ci.CIMsgPhrase; <ide> <ide> /** <ide> * to be able to compile the classes. <ide> * @author The eFaps Team <ide> */ <add>@EFapsUUID("e8633952-4b53-4000-a66c-2ee62e99966e") <ide> @EFapsApplication("eFapsApp-Sales") <ide> @EFapsNoUpdate <ide> public final class CIMsgHumanResource
JavaScript
mit
8778d8238a1c3178c2695347485ee988cf9d6ed1
0
fosfozol/w2ui,agzamovr/w2ui,agzamovr/w2ui,aadrian/w2ui,Connum/w2ui,fosfozol/w2ui,Ebiroll/w2ui,ceedriic/w2ui,fosfozol/w2ui,Ebiroll/w2ui,agzamovr/w2ui,mpf82/w2ui,ceedriic/w2ui,Connum/w2ui,aadrian/w2ui,Ebiroll/w2ui,ceedriic/w2ui,fosfozol/w2ui,fosfozol/w2ui,ram08ece/-http-w2ui.com,cristianofx/w2ui,vitmalina/w2ui,Ebiroll/w2ui,ceedriic/w2ui,Ebiroll/w2ui,mpf82/w2ui,aadrian/w2ui,mpf82/w2ui,Connum/w2ui,ceedriic/w2ui,mpf82/w2ui,vitmalina/w2ui,fosfozol/w2ui,cristianofx/w2ui,aadrian/w2ui,vitmalina/w2ui,Ebiroll/w2ui,vitmalina/w2ui,agzamovr/w2ui,vitmalina/w2ui,ceedriic/w2ui,cristianofx/w2ui,wolfmanx/w2ui,cristianofx/w2ui,Connum/w2ui,Connum/w2ui,wolfmanx/w2ui,cristianofx/w2ui,wolfmanx/w2ui,wolfmanx/w2ui,ltdl/w2ui,mpf82/w2ui,Connum/w2ui,ram08ece/-http-w2ui.com,agzamovr/w2ui,cristianofx/w2ui,vitmalina/w2ui,wolfmanx/w2ui,aadrian/w2ui,mpf82/w2ui,cristianofx/w2ui,Connum/w2ui,agzamovr/w2ui,ltdl/w2ui,vitmalina/w2ui,ltdl/w2ui,fosfozol/w2ui,aadrian/w2ui,ram08ece/-http-w2ui.com,Ebiroll/w2ui,ltdl/w2ui,mpf82/w2ui,agzamovr/w2ui,ram08ece/-http-w2ui.com,aadrian/w2ui,ltdl/w2ui,ceedriic/w2ui,ram08ece/-http-w2ui.com
var w2ui = w2ui || {}; var w2obj = w2obj || {}; // expose object to be able to overwrite default functions /************************************************ * Library: Web 2.0 UI for jQuery * - Following objects are defines * - w2ui - object that will contain all widgets * - w2obj - object with widget prototypes * - w2utils - basic utilities * - $().w2render - common render * - $().w2destroy - common destroy * - $().w2marker - marker plugin * - $().w2tag - tag plugin * - $().w2overlay - overlay plugin * - $().w2menu - menu plugin * - w2utils.event - generic event object * - Dependencies: jQuery * * == NICE TO HAVE == * - overlay should be displayed where more space (on top or on bottom) * - write and article how to replace certain framework functions * - add maxHeight for the w2menu * - add time zone * - TEST On IOS * - $().w2marker() -- only unmarks first instance * - subitems for w2menus() * - add w2utils.lang wrap for all captions in all buttons. * - $().w2date(), $().w2dateTime() * * == 1.5 changes * - date has problems in FF new Date('yyyy-mm-dd') breaks * - bug: w2utils.formatDate('2011-31-01', 'yyyy-dd-mm'); - wrong foratter * - format date and time is buggy * - added decimalSymbol * - renamed size() -> formatSize() * - added cssPrefix() * - added w2utils.settings.weekStarts * - onComplete should pass widget as context (this) * - hidden and disabled in menus * - added menu.item.tooltip for overlay menus * - added w2tag options.id, options.left, options.top * - added w2tag options.position = top|bottom|left|right - default is right * - added $().w2color(color, callBack) * - added custom colors * - added w2menu.options.type = radio|check * - added w2menu items.hotkey * - added options.contextMenu for w2overlay() * - added options.noTip for w2overlay() * - added options.overlayStyle for w2overlay() * - added options.selectable * - Refactored w2tag * - added options.style for w2tag * - added options.hideOnKeyPress for w2tag * - added options.hideOnBlur for w2tag * - events 'eventName:after' syntax * - deprecated onComplete, introduced event.done(func) - can have multiple handlers * - added getCursorPosition, setCursorPosition * - w2tag hideOnClick - hides on document click * - add isDateTime() * - data_format -> dateFormat, time_format -> timeFormat * - implemented w2utils.formatters (used in grid) * ************************************************/ var w2utils = (function ($) { var tmp = {}; // for some temp variables var obj = { version : '1.5.x', settings : { "locale" : "en-us", "dateFormat" : "m/d/yyyy", "timeFormat" : "hh:mi pm", "currencyPrefix" : "$", "currencySuffix" : "", "currencyPrecision" : 2, "groupSymbol" : ",", "decimalSymbol" : ".", "shortmonths" : ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], "fullmonths" : ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], "shortdays" : ["M", "T", "W", "T", "F", "S", "S"], "fulldays" : ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], "weekStarts" : "M", // can be "M" for Monday or "S" for Sunday "dataType" : 'HTTP', // can be HTTP, HTTPJSON, RESTFULL, RESTFULLJSON, JSON (case sensitive) "phrases" : {}, // empty object for english phrases "dateStartYear" : 1950, // start year for date-picker "dateEndYear" : 2020 // end year for date picker }, isBin : isBin, isInt : isInt, isFloat : isFloat, isMoney : isMoney, isHex : isHex, isAlphaNumeric : isAlphaNumeric, isEmail : isEmail, isDate : isDate, isTime : isTime, isDateTime : isDateTime, age : age, interval : interval, date : date, formatSize : formatSize, formatNumber : formatNumber, formatDate : formatDate, formatTime : formatTime, formatDateTime : formatDateTime, stripTags : stripTags, encodeTags : encodeTags, escapeId : escapeId, base64encode : base64encode, base64decode : base64decode, md5 : md5, transition : transition, lock : lock, unlock : unlock, lang : lang, locale : locale, getSize : getSize, getStrWidth : getStrWidth, scrollBarSize : scrollBarSize, checkName : checkName, checkUniqueId : checkUniqueId, parseRoute : parseRoute, cssPrefix : cssPrefix, getCursorPosition : getCursorPosition, setCursorPosition : setCursorPosition, // some internal variables isIOS : ((navigator.userAgent.toLowerCase().indexOf('iphone') != -1 || navigator.userAgent.toLowerCase().indexOf('ipod') != -1 || navigator.userAgent.toLowerCase().indexOf('ipad') != -1) ? true : false), isIE : ((navigator.userAgent.toLowerCase().indexOf('msie') != -1 || navigator.userAgent.toLowerCase().indexOf('trident') != -1 ) ? true : false) }; return obj; function isBin (val) { var re = /^[0-1]+$/; return re.test(val); } function isInt (val) { var re = /^[-+]?[0-9]+$/; return re.test(val); } function isFloat (val) { if (typeof val == 'string') val = val.replace(/\s+/g, '').replace(w2utils.settings.groupSymbol, '').replace(w2utils.settings.decimalSymbol, '.'); return (typeof val === 'number' || (typeof val === 'string' && val !== '')) && !isNaN(Number(val)); } function isMoney (val) { var se = w2utils.settings; var re = new RegExp('^'+ (se.currencyPrefix ? '\\' + se.currencyPrefix + '?' : '') + '[-+]?'+ (se.currencyPrefix ? '\\' + se.currencyPrefix + '?' : '') + '[0-9]*[\\'+ se.decimalSymbol +']?[0-9]+'+ (se.currencySuffix ? '\\' + se.currencySuffix + '?' : '') +'$', 'i'); if (typeof val === 'string') { val = val.replace(new RegExp(se.groupSymbol, 'g'), ''); } if (typeof val === 'object' || val === '') return false; return re.test(val); } function isHex (val) { var re = /^[a-fA-F0-9]+$/; return re.test(val); } function isAlphaNumeric (val) { var re = /^[a-zA-Z0-9_-]+$/; return re.test(val); } function isEmail (val) { var email = /^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; return email.test(val); } function isDate (val, format, retDate) { if (!val) return false; var dt = 'Invalid Date'; var month, day, year; if (format == null) format = w2utils.settings.dateFormat; if (typeof val.getUTCFullYear === 'function') { // date object year = val.getUTCFullYear(); month = val.getUTCMonth(); day = val.getUTCDate(); } else if (parseInt(val) == val && parseInt(val) > 0) { val = new Date(val); year = val.getUTCFullYear(); month = val.getUTCMonth(); day = val.getUTCDate(); } else { val = String(val); // convert month formats if (new RegExp('mon', 'ig').test(format)) { format = format.replace(/month/ig, 'm').replace(/mon/ig, 'm').replace(/dd/ig, 'd').replace(/[, ]/ig, '/').replace(/\/\//g, '/').toLowerCase(); val = val.replace(/[, ]/ig, '/').replace(/\/\//g, '/').toLowerCase(); for (var m = 0, len = w2utils.settings.fullmonths.length; m < len; m++) { var t = w2utils.settings.fullmonths[m]; val = val.replace(new RegExp(t, 'ig'), (parseInt(m) + 1)).replace(new RegExp(t.substr(0, 3), 'ig'), (parseInt(m) + 1)); } } // format date var tmp = val.replace(/-/g, '/').replace(/\./g, '/').toLowerCase().split('/'); var tmp2 = format.replace(/-/g, '/').replace(/\./g, '/').toLowerCase(); if (tmp2 === 'mm/dd/yyyy') { month = tmp[0]; day = tmp[1]; year = tmp[2]; } if (tmp2 === 'm/d/yyyy') { month = tmp[0]; day = tmp[1]; year = tmp[2]; } if (tmp2 === 'dd/mm/yyyy') { month = tmp[1]; day = tmp[0]; year = tmp[2]; } if (tmp2 === 'd/m/yyyy') { month = tmp[1]; day = tmp[0]; year = tmp[2]; } if (tmp2 === 'yyyy/dd/mm') { month = tmp[2]; day = tmp[1]; year = tmp[0]; } if (tmp2 === 'yyyy/d/m') { month = tmp[2]; day = tmp[1]; year = tmp[0]; } if (tmp2 === 'yyyy/mm/dd') { month = tmp[1]; day = tmp[2]; year = tmp[0]; } if (tmp2 === 'yyyy/m/d') { month = tmp[1]; day = tmp[2]; year = tmp[0]; } if (tmp2 === 'mm/dd/yy') { month = tmp[0]; day = tmp[1]; year = tmp[2]; } if (tmp2 === 'm/d/yy') { month = tmp[0]; day = tmp[1]; year = parseInt(tmp[2]) + 1900; } if (tmp2 === 'dd/mm/yy') { month = tmp[1]; day = tmp[0]; year = parseInt(tmp[2]) + 1900; } if (tmp2 === 'd/m/yy') { month = tmp[1]; day = tmp[0]; year = parseInt(tmp[2]) + 1900; } if (tmp2 === 'yy/dd/mm') { month = tmp[2]; day = tmp[1]; year = parseInt(tmp[0]) + 1900; } if (tmp2 === 'yy/d/m') { month = tmp[2]; day = tmp[1]; year = parseInt(tmp[0]) + 1900; } if (tmp2 === 'yy/mm/dd') { month = tmp[1]; day = tmp[2]; year = parseInt(tmp[0]) + 1900; } if (tmp2 === 'yy/m/d') { month = tmp[1]; day = tmp[2]; year = parseInt(tmp[0]) + 1900; } } if (!isInt(year)) return false; if (!isInt(month)) return false; if (!isInt(day)) return false; year = +year; month = +month; day = +day; dt = new Date(year, month - 1, day); // do checks if (month == null) return false; if (String(dt) == 'Invalid Date') return false; if ((dt.getMonth() + 1 !== month) || (dt.getDate() !== day) || (dt.getFullYear() !== year)) return false; if (retDate === true) return dt; else return true; } function isTime (val, retTime) { // Both formats 10:20pm and 22:20 if (val == null) return false; var max, pm; // -- process american format val = String(val); val = val.toUpperCase(); pm = val.indexOf('PM') >= 0; var ampm = (pm || val.indexOf('AM') >= 0); if (ampm) max = 12; else max = 24; val = val.replace('AM', '').replace('PM', ''); val = $.trim(val); // --- var tmp = val.split(':'); var h = parseInt(tmp[0] || 0), m = parseInt(tmp[1] || 0), s = parseInt(tmp[2] || 0); // accept edge case: 3PM is a good timestamp, but 3 (without AM or PM) is NOT: if ((!ampm || tmp.length !== 1) && tmp.length !== 2 && tmp.length !== 3) { return false; } if (tmp[0] === '' || h < 0 || h > max || !this.isInt(tmp[0]) || tmp[0].length > 2) { return false; } if (tmp.length > 1 && (tmp[1] === '' || m < 0 || m > 59 || !this.isInt(tmp[1]) || tmp[1].length !== 2)) { return false; } if (tmp.length > 2 && (tmp[2] === '' || s < 0 || s > 59 || !this.isInt(tmp[2]) || tmp[2].length !== 2)) { return false; } // check the edge cases: 12:01AM is ok, as is 12:01PM, but 24:01 is NOT ok while 24:00 is (midnight; equivalent to 00:00). // meanwhile, there is 00:00 which is ok, but 0AM nor 0PM are okay, while 0:01AM and 0:00AM are. if (!ampm && max === h && (m !== 0 || s !== 0)) { return false; } if (ampm && tmp.length === 1 && h === 0) { return false; } if (retTime === true) { if (pm) h += 12; return { hours: h, minutes: m, seconds: s }; } return true; } function isDateTime (val, format, retDate) { var formats = format.split('|'); if (typeof val.getUTCFullYear === 'function') { // date object if (retDate !== true) return true; return val; } else if (parseInt(val) == val && parseInt(val) > 0) { val = new Date(val); if (retDate !== true) return true; return val; } else { var tmp = String(val).indexOf(' '); var values = [val.substr(0, tmp), val.substr(tmp).trim()]; formats[0] = formats[0].trim(); if (formats[1]) formats[1] = formats[1].trim(); // check var tmp1 = w2utils.isDate(values[0], formats[0], true); var tmp2 = w2utils.isTime(values[1], true); if (tmp1 !== false && tmp2 !== false) { if (retDate !== true) return true; tmp1.setHours(tmp2[0]); tmp1.setMinutes(tmp2[1]); tmp1.setSeconds(tmp2[2]); return tmp1; } else { return false; } } } function age (dateStr) { if (dateStr === '' || dateStr == null || (typeof dateStr == 'object' && !dateStr.getMonth)) return ''; var d1 = new Date(dateStr); if (w2utils.isInt(dateStr)) d1 = new Date(Number(dateStr)); // for unix timestamps if (String(d1) == 'Invalid Date') return ''; var d2 = new Date(); var sec = (d2.getTime() - d1.getTime()) / 1000; var amount = ''; var type = ''; if (sec < 0) { amount = '<span style="color: #aaa">0 sec</span>'; type = ''; } else if (sec < 60) { amount = Math.floor(sec); type = 'sec'; if (sec < 0) { amount = 0; type = 'sec'; } } else if (sec < 60*60) { amount = Math.floor(sec/60); type = 'min'; } else if (sec < 24*60*60) { amount = Math.floor(sec/60/60); type = 'hour'; } else if (sec < 30*24*60*60) { amount = Math.floor(sec/24/60/60); type = 'day'; } else if (sec < 365*24*60*60) { amount = Math.floor(sec/30/24/60/60*10)/10; type = 'month'; } else if (sec < 365*4*24*60*60) { amount = Math.floor(sec/365/24/60/60*10)/10; type = 'year'; } else if (sec >= 365*4*24*60*60) { // factor in leap year shift (only older then 4 years) amount = Math.floor(sec/365.25/24/60/60*10)/10; type = 'year'; } return amount + ' ' + type + (amount > 1 ? 's' : ''); } function interval (value) { var ret = ''; if (value < 1000) { ret = "< 1 sec"; } else if (value < 60000) { ret = Math.floor(value / 1000) + " secs"; } else if (value < 3600000) { ret = Math.floor(value / 60000) + " mins"; } else if (value < 86400000) { ret = Math.floor(value / 3600000 * 10) / 10 + " hours"; } else if (value < 2628000000) { ret = Math.floor(value / 86400000 * 10) / 10 + " days"; } else if (value < 3.1536e+10) { ret = Math.floor(value / 2628000000 * 10) / 10 + " months"; } else { ret = Math.floor(value / 3.1536e+9) / 10 + " years"; } return ret; } function date (dateStr) { if (dateStr === '' || dateStr == null || (typeof dateStr == 'object' && !dateStr.getMonth)) return ''; var d1 = new Date(dateStr); if (w2utils.isInt(dateStr)) d1 = new Date(Number(dateStr)); // for unix timestamps if (String(d1) == 'Invalid Date') return ''; var months = w2utils.settings.shortmonths; var d2 = new Date(); // today var d3 = new Date(); d3.setTime(d3.getTime() - 86400000); // yesterday var dd1 = months[d1.getMonth()] + ' ' + d1.getDate() + ', ' + d1.getFullYear(); var dd2 = months[d2.getMonth()] + ' ' + d2.getDate() + ', ' + d2.getFullYear(); var dd3 = months[d3.getMonth()] + ' ' + d3.getDate() + ', ' + d3.getFullYear(); var time = (d1.getHours() - (d1.getHours() > 12 ? 12 :0)) + ':' + (d1.getMinutes() < 10 ? '0' : '') + d1.getMinutes() + ' ' + (d1.getHours() >= 12 ? 'pm' : 'am'); var time2= (d1.getHours() - (d1.getHours() > 12 ? 12 :0)) + ':' + (d1.getMinutes() < 10 ? '0' : '') + d1.getMinutes() + ':' + (d1.getSeconds() < 10 ? '0' : '') + d1.getSeconds() + ' ' + (d1.getHours() >= 12 ? 'pm' : 'am'); var dsp = dd1; if (dd1 === dd2) dsp = time; if (dd1 === dd3) dsp = w2utils.lang('Yesterday'); return '<span title="'+ dd1 +' ' + time2 +'">'+ dsp +'</span>'; } function formatSize (sizeStr) { if (!w2utils.isFloat(sizeStr) || sizeStr === '') return ''; sizeStr = parseFloat(sizeStr); if (sizeStr === 0) return 0; var sizes = ['Bt', 'KB', 'MB', 'GB', 'TB']; var i = parseInt( Math.floor( Math.log(sizeStr) / Math.log(1024) ) ); return (Math.floor(sizeStr / Math.pow(1024, i) * 10) / 10).toFixed(i === 0 ? 0 : 1) + ' ' + sizes[i]; } function formatNumber (val, fraction, useGrouping) { var options = { minimumFractionDigits : fraction, maximumFractionDigits : fraction, useGrouping : useGrouping }; if (fraction == null || fraction < 0) { options.minimumFractionDigits = 0; options.maximumFractionDigits = 20; } return parseFloat(val).toLocaleString(w2utils.settings.locale, options); } function formatDate (dateStr, format) { // IMPORTANT dateStr HAS TO BE valid JavaScript Date String if (!format) format = this.settings.dateFormat; if (dateStr === '' || dateStr == null || (typeof dateStr == 'object' && !dateStr.getMonth)) return ''; var dt = new Date(dateStr); if (w2utils.isInt(dateStr)) dt = new Date(Number(dateStr)); // for unix timestamps if (String(dt) == 'Invalid Date') return ''; var year = dt.getFullYear(); var month = dt.getMonth(); var date = dt.getDate(); return format.toLowerCase() .replace('month', w2utils.settings.fullmonths[month]) .replace('mon', w2utils.settings.shortmonths[month]) .replace(/yyyy/g, year) .replace(/yyy/g, year) .replace(/yy/g, year > 2000 ? 100 + parseInt(String(year).substr(2)) : String(year).substr(2)) .replace(/(^|[^a-z$])y/g, '$1' + year) // only y's that are not preceded by a letter .replace(/mm/g, (month + 1 < 10 ? '0' : '') + (month + 1)) .replace(/dd/g, (date < 10 ? '0' : '') + date) .replace(/th/g, (date == 1 ? 'st' : 'th')) .replace(/th/g, (date == 2 ? 'nd' : 'th')) .replace(/th/g, (date == 3 ? 'rd' : 'th')) .replace(/(^|[^a-z$])m/g, '$1' + (month + 1)) // only y's that are not preceded by a letter .replace(/(^|[^a-z$])d/g, '$1' + date); // only y's that are not preceded by a letter } function formatTime (dateStr, format) { // IMPORTANT dateStr HAS TO BE valid JavaScript Date String var months = w2utils.settings.shortmonths; var fullMonths = w2utils.settings.fullmonths; if (!format) format = this.settings.timeFormat; if (dateStr === '' || dateStr == null || (typeof dateStr == 'object' && !dateStr.getMonth)) return ''; var dt = new Date(dateStr); if (w2utils.isInt(dateStr)) dt = new Date(Number(dateStr)); // for unix timestamps if (w2utils.isTime(dateStr)) { var tmp = w2utils.isTime(dateStr, true); dt = new Date(); dt.setHours(tmp.hours); dt.setMinutes(tmp.minutes); } if (String(dt) == 'Invalid Date') return ''; var type = 'am'; var hour = dt.getHours(); var h24 = dt.getHours(); var min = dt.getMinutes(); var sec = dt.getSeconds(); if (min < 10) min = '0' + min; if (sec < 10) sec = '0' + sec; if (format.indexOf('am') !== -1 || format.indexOf('pm') !== -1) { if (hour >= 12) type = 'pm'; if (hour > 12) hour = hour - 12; } return format.toLowerCase() .replace('am', type) .replace('pm', type) .replace('hhh', (hour < 10 ? '0' + hour : hour)) .replace('hh24', (h24 < 10 ? '0' + h24 : h24)) .replace('h24', h24) .replace('hh', hour) .replace('mm', min) .replace('mi', min) .replace('ss', sec) .replace(/(^|[^a-z$])h/g, '$1' + hour) // only y's that are not preceded by a letter .replace(/(^|[^a-z$])m/g, '$1' + min) // only y's that are not preceded by a letter .replace(/(^|[^a-z$])s/g, '$1' + sec); // only y's that are not preceded by a letter } function formatDateTime(dateStr, format) { var fmt; if (dateStr === '' || dateStr == null || (typeof dateStr == 'object' && !dateStr.getMonth)) return ''; if (typeof format !== 'string') { fmt = [this.settings.dateFormat, this.settings.timeFormat]; } else { fmt = format.split('|'); fmt[0] = fmt[0].trim(); fmt[1] = fmt[1].trim(); } // older formats support if (fmt[1] == 'h12') fmt[1] = 'h:m pm'; if (fmt[1] == 'h24') fmt[1] = 'h24:m'; return this.formatDate(dateStr, fmt[0]) + ' ' + this.formatTime(dateStr, fmt[1]); } function stripTags (html) { if (html == null) return html; switch (typeof html) { case 'number': break; case 'string': html = $.trim(String(html).replace(/(<([^>]+)>)/ig, "")); break; case 'object': // does not modify original object, but creates a copy if (Array.isArray(html)) { html = $.extend(true, [], html); for (var i = 0; i < html.length; i++) html[i] = this.stripTags(html[i]); } else { html = $.extend(true, {}, html); for (var i in html) html[i] = this.stripTags(html[i]); } break; } return html; } function encodeTags (html) { if (html == null) return html; switch (typeof html) { case 'number': break; case 'string': html = String(html).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;"); break; case 'object': // does not modify original object, but creates a copy if (Array.isArray(html)) { html = $.extend(true, [], html); for (var i = 0; i < html.length; i++) html[i] = this.encodeTags(html[i]); } else { html = $.extend(true, {}, html); for (var i in html) html[i] = this.encodeTags(html[i]); } break; } return html; } function escapeId (id) { if (id === '' || id == null) return ''; return String(id).replace(/([;&,\.\+\*\~'`:"\!\^#$%@\[\]\(\)=<>\|\/? {}\\])/g, '\\$1'); } function base64encode (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; input = utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); } function utf8_encode (string) { string = String(string).replace(/\r\n/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; } return output; } function base64decode (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = keyStr.indexOf(input.charAt(i++)); enc2 = keyStr.indexOf(input.charAt(i++)); enc3 = keyStr.indexOf(input.charAt(i++)); enc4 = keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 !== 64) { output = output + String.fromCharCode(chr2); } if (enc4 !== 64) { output = output + String.fromCharCode(chr3); } } output = utf8_decode(output); function utf8_decode (utftext) { var string = ""; var i = 0; var c = 0, c2, c3; while ( i < utftext.length ) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i+1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; } return output; } function md5(input) { /* * Based on http://pajhome.org.uk/crypt/md5 */ var hexcase = 0; var b64pad = ""; function __pj_crypt_hex_md5(s) { return __pj_crypt_rstr2hex(__pj_crypt_rstr_md5(__pj_crypt_str2rstr_utf8(s))); } function __pj_crypt_b64_md5(s) { return __pj_crypt_rstr2b64(__pj_crypt_rstr_md5(__pj_crypt_str2rstr_utf8(s))); } function __pj_crypt_any_md5(s, e) { return __pj_crypt_rstr2any(__pj_crypt_rstr_md5(__pj_crypt_str2rstr_utf8(s)), e); } function __pj_crypt_hex_hmac_md5(k, d) { return __pj_crypt_rstr2hex(__pj_crypt_rstr_hmac_md5(__pj_crypt_str2rstr_utf8(k), __pj_crypt_str2rstr_utf8(d))); } function __pj_crypt_b64_hmac_md5(k, d) { return __pj_crypt_rstr2b64(__pj_crypt_rstr_hmac_md5(__pj_crypt_str2rstr_utf8(k), __pj_crypt_str2rstr_utf8(d))); } function __pj_crypt_any_hmac_md5(k, d, e) { return __pj_crypt_rstr2any(__pj_crypt_rstr_hmac_md5(__pj_crypt_str2rstr_utf8(k), __pj_crypt_str2rstr_utf8(d)), e); } /* * Calculate the MD5 of a raw string */ function __pj_crypt_rstr_md5(s) { return __pj_crypt_binl2rstr(__pj_crypt_binl_md5(__pj_crypt_rstr2binl(s), s.length * 8)); } /* * Calculate the HMAC-MD5, of a key and some data (raw strings) */ function __pj_crypt_rstr_hmac_md5(key, data) { var bkey = __pj_crypt_rstr2binl(key); if (bkey.length > 16) bkey = __pj_crypt_binl_md5(bkey, key.length * 8); var ipad = Array(16), opad = Array(16); for (var i = 0; i < 16; i++) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } var hash = __pj_crypt_binl_md5(ipad.concat(__pj_crypt_rstr2binl(data)), 512 + data.length * 8); return __pj_crypt_binl2rstr(__pj_crypt_binl_md5(opad.concat(hash), 512 + 128)); } /* * Convert a raw string to a hex string */ function __pj_crypt_rstr2hex(input) { try { hexcase } catch (e) { hexcase = 0; } var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; var output = ""; var x; for (var i = 0; i < input.length; i++) { x = input.charCodeAt(i); output += hex_tab.charAt((x >>> 4) & 0x0F) + hex_tab.charAt(x & 0x0F); } return output; } /* * Convert a raw string to a base-64 string */ function __pj_crypt_rstr2b64(input) { try { b64pad } catch (e) { b64pad = ''; } var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var output = ""; var len = input.length; for (var i = 0; i < len; i += 3) { var triplet = (input.charCodeAt(i) << 16) | (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0) | (i + 2 < len ? input.charCodeAt(i + 2) : 0); for (var j = 0; j < 4; j++) { if (i * 8 + j * 6 > input.length * 8) output += b64pad; else output += tab.charAt((triplet >>> 6 * (3 - j)) & 0x3F); } } return output; } /* * Convert a raw string to an arbitrary string encoding */ function __pj_crypt_rstr2any(input, encoding) { var divisor = encoding.length; var i, j, q, x, quotient; /* Convert to an array of 16-bit big-endian values, forming the dividend */ var dividend = Array(Math.ceil(input.length / 2)); for (i = 0; i < dividend.length; i++) { dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1); } /* * Repeatedly perform a long division. The binary array forms the dividend, * the length of the encoding is the divisor. Once computed, the quotient * forms the dividend for the next step. All remainders are stored for later * use. */ var full_length = Math.ceil(input.length * 8 / (Math.log(encoding.length) / Math.log(2))); var remainders = Array(full_length); for (j = 0; j < full_length; j++) { quotient = Array(); x = 0; for (i = 0; i < dividend.length; i++) { x = (x << 16) + dividend[i]; q = Math.floor(x / divisor); x -= q * divisor; if (quotient.length > 0 || q > 0) quotient[quotient.length] = q; } remainders[j] = x; dividend = quotient; } /* Convert the remainders to the output string */ var output = ""; for (i = remainders.length - 1; i >= 0; i--) output += encoding.charAt(remainders[i]); return output; } /* * Encode a string as utf-8. * For efficiency, this assumes the input is valid utf-16. */ function __pj_crypt_str2rstr_utf8(input) { var output = ""; var i = -1; var x, y; while (++i < input.length) { /* Decode utf-16 surrogate pairs */ x = input.charCodeAt(i); y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0; if (0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF) { x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF); i++; } /* Encode output as utf-8 */ if (x <= 0x7F) output += String.fromCharCode(x); else if (x <= 0x7FF) output += String.fromCharCode(0xC0 | ((x >>> 6) & 0x1F), 0x80 | (x & 0x3F)); else if (x <= 0xFFFF) output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F), 0x80 | ((x >>> 6) & 0x3F), 0x80 | (x & 0x3F)); else if (x <= 0x1FFFFF) output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07), 0x80 | ((x >>> 12) & 0x3F), 0x80 | ((x >>> 6) & 0x3F), 0x80 | (x & 0x3F)); } return output; } /* * Encode a string as utf-16 */ function __pj_crypt_str2rstr_utf16le(input) { var output = ""; for (var i = 0; i < input.length; i++) output += String.fromCharCode(input.charCodeAt(i) & 0xFF, (input.charCodeAt(i) >>> 8) & 0xFF); return output; } function __pj_crypt_str2rstr_utf16be(input) { var output = ""; for (var i = 0; i < input.length; i++) output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF, input.charCodeAt(i) & 0xFF); return output; } /* * Convert a raw string to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ function __pj_crypt_rstr2binl(input) { var output = Array(input.length >> 2); for (var i = 0; i < output.length; i++) output[i] = 0; for (var i = 0; i < input.length * 8; i += 8) output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32); return output; } /* * Convert an array of little-endian words to a string */ function __pj_crypt_binl2rstr(input) { var output = ""; for (var i = 0; i < input.length * 32; i += 8) output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); return output; } /* * Calculate the MD5 of an array of little-endian words, and a bit length. */ function __pj_crypt_binl_md5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << ((len) % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; for (var i = 0; i < x.length; i += 16) { var olda = a; var oldb = b; var oldc = c; var oldd = d; a = __pj_crypt_md5_ff(a, b, c, d, x[i + 0], 7, -680876936); d = __pj_crypt_md5_ff(d, a, b, c, x[i + 1], 12, -389564586); c = __pj_crypt_md5_ff(c, d, a, b, x[i + 2], 17, 606105819); b = __pj_crypt_md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); a = __pj_crypt_md5_ff(a, b, c, d, x[i + 4], 7, -176418897); d = __pj_crypt_md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); c = __pj_crypt_md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); b = __pj_crypt_md5_ff(b, c, d, a, x[i + 7], 22, -45705983); a = __pj_crypt_md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); d = __pj_crypt_md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); c = __pj_crypt_md5_ff(c, d, a, b, x[i + 10], 17, -42063); b = __pj_crypt_md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); a = __pj_crypt_md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); d = __pj_crypt_md5_ff(d, a, b, c, x[i + 13], 12, -40341101); c = __pj_crypt_md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); b = __pj_crypt_md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); a = __pj_crypt_md5_gg(a, b, c, d, x[i + 1], 5, -165796510); d = __pj_crypt_md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); c = __pj_crypt_md5_gg(c, d, a, b, x[i + 11], 14, 643717713); b = __pj_crypt_md5_gg(b, c, d, a, x[i + 0], 20, -373897302); a = __pj_crypt_md5_gg(a, b, c, d, x[i + 5], 5, -701558691); d = __pj_crypt_md5_gg(d, a, b, c, x[i + 10], 9, 38016083); c = __pj_crypt_md5_gg(c, d, a, b, x[i + 15], 14, -660478335); b = __pj_crypt_md5_gg(b, c, d, a, x[i + 4], 20, -405537848); a = __pj_crypt_md5_gg(a, b, c, d, x[i + 9], 5, 568446438); d = __pj_crypt_md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); c = __pj_crypt_md5_gg(c, d, a, b, x[i + 3], 14, -187363961); b = __pj_crypt_md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); a = __pj_crypt_md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); d = __pj_crypt_md5_gg(d, a, b, c, x[i + 2], 9, -51403784); c = __pj_crypt_md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); b = __pj_crypt_md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); a = __pj_crypt_md5_hh(a, b, c, d, x[i + 5], 4, -378558); d = __pj_crypt_md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); c = __pj_crypt_md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); b = __pj_crypt_md5_hh(b, c, d, a, x[i + 14], 23, -35309556); a = __pj_crypt_md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); d = __pj_crypt_md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); c = __pj_crypt_md5_hh(c, d, a, b, x[i + 7], 16, -155497632); b = __pj_crypt_md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); a = __pj_crypt_md5_hh(a, b, c, d, x[i + 13], 4, 681279174); d = __pj_crypt_md5_hh(d, a, b, c, x[i + 0], 11, -358537222); c = __pj_crypt_md5_hh(c, d, a, b, x[i + 3], 16, -722521979); b = __pj_crypt_md5_hh(b, c, d, a, x[i + 6], 23, 76029189); a = __pj_crypt_md5_hh(a, b, c, d, x[i + 9], 4, -640364487); d = __pj_crypt_md5_hh(d, a, b, c, x[i + 12], 11, -421815835); c = __pj_crypt_md5_hh(c, d, a, b, x[i + 15], 16, 530742520); b = __pj_crypt_md5_hh(b, c, d, a, x[i + 2], 23, -995338651); a = __pj_crypt_md5_ii(a, b, c, d, x[i + 0], 6, -198630844); d = __pj_crypt_md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); c = __pj_crypt_md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); b = __pj_crypt_md5_ii(b, c, d, a, x[i + 5], 21, -57434055); a = __pj_crypt_md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); d = __pj_crypt_md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); c = __pj_crypt_md5_ii(c, d, a, b, x[i + 10], 15, -1051523); b = __pj_crypt_md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); a = __pj_crypt_md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); d = __pj_crypt_md5_ii(d, a, b, c, x[i + 15], 10, -30611744); c = __pj_crypt_md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); b = __pj_crypt_md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); a = __pj_crypt_md5_ii(a, b, c, d, x[i + 4], 6, -145523070); d = __pj_crypt_md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); c = __pj_crypt_md5_ii(c, d, a, b, x[i + 2], 15, 718787259); b = __pj_crypt_md5_ii(b, c, d, a, x[i + 9], 21, -343485551); a = __pj_crypt_safe_add(a, olda); b = __pj_crypt_safe_add(b, oldb); c = __pj_crypt_safe_add(c, oldc); d = __pj_crypt_safe_add(d, oldd); } return Array(a, b, c, d); } /* * These functions implement the four basic operations the algorithm uses. */ function __pj_crypt_md5_cmn(q, a, b, x, s, t) { return __pj_crypt_safe_add(__pj_crypt_bit_rol(__pj_crypt_safe_add(__pj_crypt_safe_add(a, q), __pj_crypt_safe_add(x, t)), s), b); } function __pj_crypt_md5_ff(a, b, c, d, x, s, t) { return __pj_crypt_md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function __pj_crypt_md5_gg(a, b, c, d, x, s, t) { return __pj_crypt_md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function __pj_crypt_md5_hh(a, b, c, d, x, s, t) { return __pj_crypt_md5_cmn(b ^ c ^ d, a, b, x, s, t); } function __pj_crypt_md5_ii(a, b, c, d, x, s, t) { return __pj_crypt_md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function __pj_crypt_safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function __pj_crypt_bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } return __pj_crypt_hex_md5(input); } function transition (div_old, div_new, type, callBack) { var width = $(div_old).width(); var height = $(div_old).height(); var time = 0.5; if (!div_old || !div_new) { console.log('ERROR: Cannot do transition when one of the divs is null'); return; } div_old.parentNode.style.cssText += 'perspective: 700; overflow: hidden;'; div_old.style.cssText += '; position: absolute; z-index: 1019; backface-visibility: hidden'; div_new.style.cssText += '; position: absolute; z-index: 1020; backface-visibility: hidden'; switch (type) { case 'slide-left': // init divs div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0)'; div_new.style.cssText += 'overflow: hidden; transform: translate3d('+ width + 'px, 0, 0)'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; transform: translate3d(0, 0, 0)'; div_old.style.cssText += 'transition: '+ time +'s; transform: translate3d(-'+ width +'px, 0, 0)'; }, 1); break; case 'slide-right': // init divs div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0)'; div_new.style.cssText += 'overflow: hidden; transform: translate3d(-'+ width +'px, 0, 0)'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; transform: translate3d(0px, 0, 0)'; div_old.style.cssText += 'transition: '+ time +'s; transform: translate3d('+ width +'px, 0, 0)'; }, 1); break; case 'slide-down': // init divs div_old.style.cssText += 'overflow: hidden; z-index: 1; transform: translate3d(0, 0, 0)'; div_new.style.cssText += 'overflow: hidden; z-index: 0; transform: translate3d(0, 0, 0)'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; transform: translate3d(0, 0, 0)'; div_old.style.cssText += 'transition: '+ time +'s; transform: translate3d(0, '+ height +'px, 0)'; }, 1); break; case 'slide-up': // init divs div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0)'; div_new.style.cssText += 'overflow: hidden; transform: translate3d(0, '+ height +'px, 0)'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; transform: translate3d(0, 0, 0)'; div_old.style.cssText += 'transition: '+ time +'s; transform: translate3d(0, 0, 0)'; }, 1); break; case 'flip-left': // init divs div_old.style.cssText += 'overflow: hidden; transform: rotateY(0deg)'; div_new.style.cssText += 'overflow: hidden; transform: rotateY(-180deg)'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; transform: rotateY(0deg)'; div_old.style.cssText += 'transition: '+ time +'s; transform: rotateY(180deg)'; }, 1); break; case 'flip-right': // init divs div_old.style.cssText += 'overflow: hidden; transform: rotateY(0deg)'; div_new.style.cssText += 'overflow: hidden; transform: rotateY(180deg)'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; transform: rotateY(0deg)'; div_old.style.cssText += 'transition: '+ time +'s; transform: rotateY(-180deg)'; }, 1); break; case 'flip-down': // init divs div_old.style.cssText += 'overflow: hidden; transform: rotateX(0deg)'; div_new.style.cssText += 'overflow: hidden; transform: rotateX(180deg)'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; transform: rotateX(0deg)'; div_old.style.cssText += 'transition: '+ time +'s; transform: rotateX(-180deg)'; }, 1); break; case 'flip-up': // init divs div_old.style.cssText += 'overflow: hidden; transform: rotateX(0deg)'; div_new.style.cssText += 'overflow: hidden; transform: rotateX(-180deg)'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; transform: rotateX(0deg)'; div_old.style.cssText += 'transition: '+ time +'s; transform: rotateX(180deg)'; }, 1); break; case 'pop-in': // init divs div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0)'; div_new.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0); transform: scale(.8); opacity: 0;'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; transform: scale(1); opacity: 1;'; div_old.style.cssText += 'transition: '+ time +'s;'; }, 1); break; case 'pop-out': // init divs div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0); transform: scale(1); opacity: 1;'; div_new.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0); opacity: 0;'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; opacity: 1;'; div_old.style.cssText += 'transition: '+ time +'s; transform: scale(1.7); opacity: 0;'; }, 1); break; default: // init divs div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0)'; div_new.style.cssText += 'overflow: hidden; translate3d(0, 0, 0); opacity: 0;'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; opacity: 1;'; div_old.style.cssText += 'transition: '+ time +'s'; }, 1); break; } setTimeout(function () { if (type === 'slide-down') { $(div_old).css('z-index', '1019'); $(div_new).css('z-index', '1020'); } if (div_new) { $(div_new).css({ 'opacity': '1' }).css(w2utils.cssPrefix({ 'transition': '', 'transform' : '' })); } if (div_old) { $(div_old).css({ 'opacity': '1' }).css(w2utils.cssPrefix({ 'transition': '', 'transform' : '' })); } if (typeof callBack === 'function') callBack(); }, time * 1000); } function lock (box, msg, spinner) { var options = {}; if (typeof msg === 'object') { options = msg; } else { options.msg = msg; options.spinner = spinner; } if (!options.msg && options.msg !== 0) options.msg = ''; w2utils.unlock(box); $(box).prepend( '<div class="w2ui-lock"></div>'+ '<div class="w2ui-lock-msg"></div>' ); var $lock = $(box).find('.w2ui-lock'); var mess = $(box).find('.w2ui-lock-msg'); if (!options.msg) mess.css({ 'background-color': 'transparent', 'border': '0px' }); if (options.spinner === true) options.msg = '<div class="w2ui-spinner" '+ (!options.msg ? 'style="width: 35px; height: 35px"' : '') +'></div>' + options.msg; if (options.opacity != null) $lock.css('opacity', options.opacity); if (typeof $lock.fadeIn == 'function') { $lock.fadeIn(200); mess.html(options.msg).fadeIn(200); } else { $lock.show(); mess.html(options.msg).show(0); } } function unlock (box, speed) { if (isInt(speed)) { $(box).find('.w2ui-lock').fadeOut(speed); setTimeout(function () { $(box).find('.w2ui-lock').remove(); $(box).find('.w2ui-lock-msg').remove(); }, speed); } else { $(box).find('.w2ui-lock').remove(); $(box).find('.w2ui-lock-msg').remove(); } } function getSize (el, type) { var $el = $(el); var bwidth = { left : parseInt($el.css('border-left-width')) || 0, right : parseInt($el.css('border-right-width')) || 0, top : parseInt($el.css('border-top-width')) || 0, bottom : parseInt($el.css('border-bottom-width')) || 0 }; var mwidth = { left : parseInt($el.css('margin-left')) || 0, right : parseInt($el.css('margin-right')) || 0, top : parseInt($el.css('margin-top')) || 0, bottom : parseInt($el.css('margin-bottom')) || 0 }; var pwidth = { left : parseInt($el.css('padding-left')) || 0, right : parseInt($el.css('padding-right')) || 0, top : parseInt($el.css('padding-top')) || 0, bottom : parseInt($el.css('padding-bottom')) || 0 }; switch (type) { case 'top' : return bwidth.top + mwidth.top + pwidth.top; case 'bottom' : return bwidth.bottom + mwidth.bottom + pwidth.bottom; case 'left' : return bwidth.left + mwidth.left + pwidth.left; case 'right' : return bwidth.right + mwidth.right + pwidth.right; case 'width' : return bwidth.left + bwidth.right + mwidth.left + mwidth.right + pwidth.left + pwidth.right + parseInt($el.width()); case 'height' : return bwidth.top + bwidth.bottom + mwidth.top + mwidth.bottom + pwidth.top + pwidth.bottom + parseInt($el.height()); case '+width' : return bwidth.left + bwidth.right + mwidth.left + mwidth.right + pwidth.left + pwidth.right; case '+height' : return bwidth.top + bwidth.bottom + mwidth.top + mwidth.bottom + pwidth.top + pwidth.bottom; } return 0; } function getStrWidth (str, styles) { var w, html = '<div id="_tmp_width" style="position: absolute; top: -900px;'+ styles +'">'+ str +'</div>'; $('body').append(html); w = $('#_tmp_width').width(); $('#_tmp_width').remove(); return w; } function lang (phrase) { var translation = this.settings.phrases[phrase]; if (translation == null) return phrase; else return translation; } function locale (locale) { if (!locale) locale = 'en-us'; // if the locale is an object, not a string, than we assume it's a if(typeof locale !== "string" ) { w2utils.settings = $.extend(true, w2utils.settings, locale); return } if (locale.length === 5) locale = 'locale/'+ locale +'.json'; // clear phrases from language before w2utils.settings.phrases = {}; // load from the file $.ajax({ url : locale, type : "GET", dataType : "JSON", async : false, cache : false, success : function (data, status, xhr) { w2utils.settings = $.extend(true, w2utils.settings, data); }, error : function (xhr, status, msg) { console.log('ERROR: Cannot load locale '+ locale); } }); } function scrollBarSize () { if (tmp.scrollBarSize) return tmp.scrollBarSize; var html = '<div id="_scrollbar_width" style="position: absolute; top: -300px; width: 100px; height: 100px; overflow-y: scroll;">'+ ' <div style="height: 120px">1</div>'+ '</div>'; $('body').append(html); tmp.scrollBarSize = 100 - $('#_scrollbar_width > div').width(); $('#_scrollbar_width').remove(); if (String(navigator.userAgent).indexOf('MSIE') >= 0) tmp.scrollBarSize = tmp.scrollBarSize / 2; // need this for IE9+ return tmp.scrollBarSize; } function checkName (params, component) { // was w2checkNameParam if (!params || params.name == null) { console.log('ERROR: The parameter "name" is required but not supplied in $().'+ component +'().'); return false; } if (w2ui[params.name] != null) { console.log('ERROR: The parameter "name" is not unique. There are other objects already created with the same name (obj: '+ params.name +').'); return false; } if (!w2utils.isAlphaNumeric(params.name)) { console.log('ERROR: The parameter "name" has to be alpha-numeric (a-z, 0-9, dash and underscore). '); return false; } return true; } function checkUniqueId (id, items, itemsDecription, objName) { // was w2checkUniqueId if (!$.isArray(items)) items = [items]; for (var i = 0; i < items.length; i++) { if (items[i].id === id) { console.log('ERROR: The parameter "id='+ id +'" is not unique within the current '+ itemsDecription +'. (obj: '+ objName +')'); return false; } } return true; } function parseRoute(route) { var keys = []; var path = route .replace(/\/\(/g, '(?:/') .replace(/\+/g, '__plus__') .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, function(_, slash, format, key, capture, optional) { keys.push({ name: key, optional: !! optional }); slash = slash || ''; return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')' + (optional || ''); }) .replace(/([\/.])/g, '\\$1') .replace(/__plus__/g, '(.+)') .replace(/\*/g, '(.*)'); return { path : new RegExp('^' + path + '$', 'i'), keys : keys }; } function cssPrefix(field, value, returnString) { var css = {}; var newCSS = {}; var ret = ''; if (!$.isPlainObject(field)) { css[field] = value; } else { css = field; if (value === true) returnString = true; } for (var c in css) { newCSS[c] = css[c]; newCSS['-webkit-'+c] = css[c]; newCSS['-moz-'+c] = css[c].replace('-webkit-', '-moz-'); newCSS['-ms-'+c] = css[c].replace('-webkit-', '-ms-'); newCSS['-o-'+c] = css[c].replace('-webkit-', '-o-'); } if (returnString === true) { for (var c in newCSS) { ret += c + ': ' + newCSS[c] + '; '; } } else { ret = newCSS; } return ret; } function getCursorPosition(input) { if (input == null) return null; var caretOffset = 0; var doc = input.ownerDocument || input.document; var win = doc.defaultView || doc.parentWindow; var sel; if (win.getSelection) { sel = win.getSelection(); if (sel.rangeCount > 0) { var range = sel.getRangeAt(0); var preCaretRange = range.cloneRange(); preCaretRange.selectNodeContents(input); preCaretRange.setEnd(range.endContainer, range.endOffset); caretOffset = preCaretRange.toString().length; } } else if ( (sel = doc.selection) && sel.type != "Control") { var textRange = sel.createRange(); var preCaretTextRange = doc.body.createTextRange(); preCaretTextRange.moveToElementText(input); preCaretTextRange.setEndPoint("EndToEnd", textRange); caretOffset = preCaretTextRange.text.length; } return caretOffset; } function setCursorPosition(input, pos, posEnd) { var range = document.createRange(); var el, sel = window.getSelection(); if (input == null) return; for (var i = 0; i < input.childNodes.length; i++) { var tmp = $(input.childNodes[i]).text(); if (input.childNodes[i].tagName) tmp = $(input.childNodes[i]).html(); if (pos <= tmp.length) { el = input.childNodes[i]; if (el.childNodes && el.childNodes.length > 0) el = el.childNodes[0]; if (el.childNodes && el.childNodes.length > 0) el = el.childNodes[0]; break; } else { pos -= tmp.length; } } if (el == null) return; if (pos > el.length) pos = el.length; range.setStart(el, pos); if (posEnd) { range.setEnd(el, posEnd); } else { range.collapse(true); } sel.removeAllRanges(); sel.addRange(range); } })(jQuery); /*********************************************************** * Formatters object * --- Primariy used in grid * *********************************************************/ w2utils.formatters = { 'number': function (value, params) { if (parseInt(params) > 20) params = 20; if (parseInt(params) < 0) params = 0; if (value == null || value == '') return ''; return w2utils.formatNumber(parseFloat(value), params, true); }, 'float': function (value, params) { return w2utils.formatters['number'](value, params); }, 'int': function (value, params) { return w2utils.formatters['number'](value, 0); }, 'money': function (value, params) { if (value == null || value == '') return ''; var data = w2utils.formatNumber(Number(value), w2utils.settings.currencyPrecision || 2); return (w2utils.settings.currencyPrefix || '') + data + (w2utils.settings.currencySuffix || ''); }, 'currency': function (value, params) { return w2utils.formatters['money'](value, params); }, 'percent': function (value, params) { if (value == null || value == '') return ''; return w2utils.formatNumber(value, params || 1) + '%'; }, 'size': function (value, params) { if (value == null || value == '') return ''; return w2utils.formatSize(parseInt(value)); }, 'date': function (value, params) { if (params == null || params == '') params = w2utils.settings.dateFormat; if (value == null || value == 0) return ''; var dt = w2utils.isDateTime(value, params, true); if (dt == '') dt = w2utils.isDate(value, params, true); return '<span title="'+ dt +'">' + w2utils.formatDate(dt, params) + '</span>'; }, 'datetime': function (value, params) { if (params == null || params == '') params = w2utils.settings.dateFormat + '|' + w2utils.settings.timeFormat; if (value == null || value == 0) return ''; var dt = w2utils.isDateTime(value, params, true); if (dt == '') dt = w2utils.isDate(value, params, true); return '<span title="'+ dt +'">' + w2utils.formatDateTime(dt, params) + '</span>'; }, 'time': function (value, params) { if (params == null || params == '') params = w2utils.settings.timeFormat; if (params == 'h12') params = 'hh:mi pm'; if (params == 'h24') params = 'h24:mi'; if (value == null || value == 0) return ''; var dt = w2utils.isDateTime(value, params, true); if (dt == '') dt = w2utils.isDate(value, params, true); return '<span title="'+ dt +'">' + w2utils.formatTime(value, params) + '</span>'; }, 'timestamp': function (value, params) { if (params == null || params == '') params = w2utils.settings.dateFormat + '|' + w2utils.settings.timeFormat; if (value == null || value == 0) return ''; var dt = w2utils.isDateTime(value, params, true); if (dt == '') dt = w2utils.isDate(value, params, true); return dt.toString ? dt.toString() : ''; }, 'gmt': function (value, params) { if (params == null || params == '') params = w2utils.settings.dateFormat + '|' + w2utils.settings.timeFormat; if (value == null || value == 0) return ''; var dt = w2utils.isDateTime(value, params, true); if (dt == '') dt = w2utils.isDate(value, params, true); return dt.toUTCString ? dt.toUTCString() : ''; }, 'age': function (value, params) { if (value == null || value == 0) return ''; var dt = w2utils.isDateTime(value, params, true); if (dt == '') dt = w2utils.isDate(value, params, true); return '<span title="'+ dt +'">' + w2utils.age(value) + ((' ' + params) || '') + '</span>'; }, 'toggle': function (value, params) { return (value ? 'Yes' : ''); } }; /*********************************************************** * Generic Event Object * --- This object is reused across all other * --- widgets in w2ui. * *********************************************************/ w2utils.event = { on: function (edata, handler) { // allow 'eventName:after' syntax if (typeof edata == 'string' && edata.indexOf(':') != -1) { var tmp = edata.split(':'); if (['complete', 'done'].indexOf(edata[1]) != -1) edata[1] = 'after'; edata = { type : tmp[0], execute : tmp[1] }; } if (!$.isPlainObject(edata)) edata = { type: edata }; edata = $.extend({ type: null, execute: 'before', target: null, onComplete: null }, edata); // errors if (!edata.type) { console.log('ERROR: You must specify event type when calling .on() method of '+ this.name); return; } if (!handler) { console.log('ERROR: You must specify event handler function when calling .on() method of '+ this.name); return; } if (!$.isArray(this.handlers)) this.handlers = []; this.handlers.push({ edata: edata, handler: handler }); }, off: function (edata, handler) { // allow 'eventName:after' syntax if (typeof edata == 'string' && edata.indexOf(':') != -1) { var tmp = edata.split(':'); if (['complete', 'done'].indexOf(edata[1]) != -1) edata[1] = 'after'; edata = { type : tmp[0], execute : tmp[1] } } if (!$.isPlainObject(edata)) edata = { type: edata }; edata = $.extend({}, { type: null, execute: 'before', target: null, onComplete: null }, edata); // errors if (!edata.type) { console.log('ERROR: You must specify event type when calling .off() method of '+ this.name); return; } if (!handler) { handler = null; } // remove handlers var newHandlers = []; for (var h = 0, len = this.handlers.length; h < len; h++) { var t = this.handlers[h]; if ((t.edata.type === edata.type || edata.type === '*') && (t.edata.target === edata.target || edata.target == null) && (t.edata.execute === edata.execute || edata.execute == null) && (t.handler === handler || handler == null)) { // match } else { newHandlers.push(t); } } this.handlers = newHandlers; }, trigger: function (edata) { var edata = $.extend({ type: null, phase: 'before', target: null, doneHandlers: [] }, edata, { isStopped : false, isCancelled : false, done : function (handler) { this.doneHandlers.push(handler); }, preventDefault : function () { this.isCancelled = true; }, stopPropagation : function () { this.isStopped = true; } }); if (edata.phase === 'before') edata.onComplete = null; var args, fun, tmp; if (edata.target == null) edata.target = null; if (!$.isArray(this.handlers)) this.handlers = []; // process events in REVERSE order for (var h = this.handlers.length-1; h >= 0; h--) { var item = this.handlers[h]; if ((item.edata.type === edata.type || item.edata.type === '*') && (item.edata.target === edata.target || item.edata.target == null) && (item.edata.execute === edata.phase || item.edata.execute === '*' || item.edata.phase === '*')) { edata = $.extend({}, item.edata, edata); // check handler arguments args = []; tmp = new RegExp(/\((.*?)\)/).exec(item.handler); if (tmp) args = tmp[1].split(/\s*,\s*/); if (args.length === 2) { item.handler.call(this, edata.target, edata); // old way for back compatibility } else { item.handler.call(this, edata); // new way } if (edata.isStopped === true || edata.stop === true) return edata; // back compatibility edata.stop === true } } // main object events var funName = 'on' + edata.type.substr(0,1).toUpperCase() + edata.type.substr(1); if (edata.phase === 'before' && typeof this[funName] === 'function') { fun = this[funName]; // check handler arguments args = []; tmp = new RegExp(/\((.*?)\)/).exec(fun); if (tmp) args = tmp[1].split(/\s*,\s*/); if (args.length === 2) { fun.call(this, edata.target, edata); // old way for back compatibility } else { fun.call(this, edata); // new way } if (edata.isStopped === true || edata.stop === true) return edata; // back compatibility edata.stop === true } // item object events if (edata.object != null && edata.phase === 'before' && typeof edata.object[funName] === 'function') { fun = edata.object[funName]; // check handler arguments args = []; tmp = new RegExp(/\((.*?)\)/).exec(fun); if (tmp) args = tmp[1].split(/\s*,\s*/); if (args.length === 2) { fun.call(this, edata.target, edata); // old way for back compatibility } else { fun.call(this, edata); // new way } if (edata.isStopped === true || edata.stop === true) return edata; } // execute onComplete if (edata.phase === 'after') { if (typeof edata.onComplete === 'function') edata.onComplete.call(this, edata); for (var i = 0; i < edata.doneHandlers.length; i++) { if (typeof edata.doneHandlers[i] == 'function') { edata.doneHandlers[i].call(this, edata); } } } return edata; } }; /*********************************************************** * Commonly used plugins * --- used primarily in grid and form * *********************************************************/ (function ($) { $.fn.w2render = function (name) { if ($(this).length > 0) { if (typeof name === 'string' && w2ui[name]) w2ui[name].render($(this)[0]); if (typeof name === 'object') name.render($(this)[0]); } }; $.fn.w2destroy = function (name) { if (!name && this.length > 0) name = this.attr('name'); if (typeof name === 'string' && w2ui[name]) w2ui[name].destroy(); if (typeof name === 'object') name.destroy(); }; $.fn.w2marker = function () { var str = Array.prototype.slice.call(arguments, 0); if (Array.isArray(str[0])) str = str[0]; if (str.length == 0 || !str[0]) { // remove marker return $(this).each(clearMarkedText); } else { // add marker return $(this).each(function (index, el) { clearMarkedText(index, el); for (var s = 0; s < str.length; s++) { var tmp = str[s]; if (typeof tmp !== 'string') tmp = String(tmp); // escape regex special chars tmp = tmp.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&").replace(/&/g, '&amp;').replace(/</g, '&gt;').replace(/>/g, '&lt;'); var regex = new RegExp(tmp + '(?!([^<]+)?>)', "gi"); // only outside tags el.innerHTML = el.innerHTML.replace(regex, replaceValue); } function replaceValue(matched) { // mark new return '<span class="w2ui-marker">' + matched + '</span>'; } }); } function clearMarkedText(index, el) { while (el.innerHTML.indexOf('<span class="w2ui-marker">') != -1) { el.innerHTML = el.innerHTML.replace(/\<span class=\"w2ui\-marker\"\>(.*)\<\/span\>/ig, '$1'); // unmark } } }; // -- w2tag - there can be multiple on screen at a time $.fn.w2tag = function (text, options) { // only one argument if (arguments.length == 1 && typeof text == 'object') { options = text; if (options.html != null) text = options.html; } // default options options = $.extend({ id : null, // id for the tag, otherwise input id is used html : text, // or html position : 'right', // can be left, right, top, bottom left : 0, // delta for left coordinate top : 0, // delta for top coordinate style : '', // adition style for the tag css : {}, // add css for input when tag is shown className : '', // add class bubble inputClass : '', // add class for input when tag is shown onShow : null, // callBack when shown onHide : null, // callBack when hidden hideOnKeyPress : true, // hide tag if key pressed hideOnBlur : false, // hide tag on blur hideOnClick : false // hide tag on document click }, options); if (options.name != null && options.id == null) options.id = options.name; // for backward compatibility if (options['class'] != '' && options.inputClass == '') options.inputClass = options['class']; // remove all tags if ($(this).length === 0) { $('.w2ui-tag').each(function (index, el) { var opt = $(el).data('options'); if (opt == null) opt = {}; $($(el).data('taged-el')).removeClass(opt.inputClass); clearInterval($(el).data('timer')); $(el).remove(); }); return; } return $(this).each(function (index, el) { // show or hide tag var origID = (options.id ? options.id : el.id); var tagID = w2utils.escapeId(origID); var $tags = $('#w2ui-tag-'+tagID); if (text === '' || text == null) { // remmove element $tags.css('opacity', 0); clearInterval($tags.data('timer')); $tags.remove(); return; } else if ($tags.length != 0) { // if already present options = $.extend($tags.data('options'), options); $tags.data('options', options); $tags.find('.w2ui-tag-body') .attr('style', options.style) .addClass(options.className) .html(options.html); } else { var originalCSS = ''; if ($(el).length > 0) originalCSS = $(el)[0].style.cssText; // insert $('body').append( '<div onclick="event.stopPropagation()" id="w2ui-tag-'+ origID +'" class="w2ui-tag '+ ($(el).parents('.w2ui-popup').length > 0 ? 'w2ui-tag-popup' : '') + '">'+ ' <div style="margin: -2px 0px 0px -2px; white-space: nowrap;">'+ ' <div class="w2ui-tag-body '+ options.className +'" style="'+ (options.style || '') +'">'+ text +'</div>'+ ' </div>' + '</div>'); $tags = $('#w2ui-tag-'+tagID); $(el).data('w2tag', $tags.get(0)); } // need time out to allow tag to be rendered setTimeout(function () { if (!$(el).offset()) return; var pos = checkIfMoved(true); if (pos == null) return; $tags.css({ opacity : '1', left : pos.left + 'px', top : pos.top + 'px' }) .data('options', options) .data('taged-el', el) .data('position', pos.left + 'x' + pos.top) .data('timer', setTimeout(checkIfMoved, 100)) .find('.w2ui-tag-body').addClass(pos['posClass']); $(el).css(options.css) .off('.w2tag') .addClass(options.inputClass); if (options.hideOnKeyPress) { $(el).on('keypress.w2tag', hideTag); } if (options.hideOnBlur) { $(el).on('blur.w2tag', hideTag); } if (options.hideOnClick) { $(document).on('click.w2tag', hideTag) } if (typeof options.onShow === 'function') options.onShow(); }, 1); // bind event to hide it function hideTag() { $tags = $('#w2ui-tag-'+tagID); if ($tags.length <= 0) return; clearInterval($tags.data('timer')); $tags.remove(); $(document).off('.w2tag'); $(el).off('.w2tag', hideTag) .removeClass(options.inputClass) .removeData('w2tag'); if ($(el).length > 0) $(el)[0].style.cssText = originalCSS; if (typeof options.onHide === 'function') options.onHide(); } function checkIfMoved(skipTransition) { // monitor if destroyed var offset = $(el).offset(); if ($(el).length === 0 || (offset.left === 0 && offset.top === 0) || $tags.find('.w2ui-tag-body').length == 0) { clearInterval($tags.data('timer')); hideTag(); return; } setTimeout(checkIfMoved, 100); // monitor if moved var posClass = 'w2ui-tag-right'; var posLeft = parseInt($(el).offset().left + el.offsetWidth + (options.left ? options.left : 0)); var posTop = parseInt($(el).offset().top + (options.top ? options.top : 0)); var tagBody = $tags.find('.w2ui-tag-body'); var width = tagBody[0].offsetWidth; var height = tagBody[0].offsetHeight; if (options.position == 'top') { posClass = 'w2ui-tag-top'; posLeft = parseInt($(el).offset().left + (options.left ? options.left : 0)) - 14; posTop = parseInt($(el).offset().top + (options.top ? options.top : 0)) - height - 10; } if (options.position == 'bottom') { posClass = 'w2ui-tag-bottom'; posLeft = parseInt($(el).offset().left + (options.left ? options.left : 0)) - 14; posTop = parseInt($(el).offset().top + el.offsetHeight + (options.top ? options.top : 0)) + 10; } if (options.position == 'left') { posClass = 'w2ui-tag-left'; posLeft = parseInt($(el).offset().left + (options.left ? options.left : 0)) - width - 20; posTop = parseInt($(el).offset().top + (options.top ? options.top : 0)); } if ($tags.data('position') !== posLeft + 'x' + posTop && skipTransition !== true) { $tags.css(w2utils.cssPrefix({ 'transition': '.2s' })).css({ left: posLeft + 'px', top : posTop + 'px' }).data('position', posLeft + 'x' + posTop); } return { left: posLeft, top: posTop, posClass: posClass }; } }); }; // w2overlay - appears under the element, there can be only one at a time $.fn.w2overlay = function (html, options) { var obj = this; var name = ''; var defaults = { name : null, // it not null, then allows multiple concurrent overlays html : '', // html text to display align : 'none', // can be none, left, right, both left : 0, // offset left top : 0, // offset top tipLeft : 30, // tip offset left noTip : false, // if true - no tip will be displayed selectable : false, width : 0, // fixed width height : 0, // fixed height maxWidth : null, // max width if any maxHeight : null, // max height if any contextMenu : false, // if true, it will be opened at mouse position style : '', // additional style for main div 'class' : '', // additional class name for main div overlayStyle: '', onShow : null, // event on show onHide : null, // event on hide openAbove : false, // show above control tmp : {} }; if (arguments.length == 1) { if (typeof html == 'object') { options = html; } else { options = { html: html }; } } if (arguments.length == 2) options.html = html; if (!$.isPlainObject(options)) options = {}; options = $.extend({}, defaults, options); if (options.name) name = '-' + options.name; // hide var tmp_hide; if (this.length == 0 || options.html === '' || options.html == null) { if ($('#w2ui-overlay'+ name).length > 0) { tmp_hide = $('#w2ui-overlay'+ name)[0].hide; if (typeof tmp_hide === 'function') tmp_hide(); } else { $('#w2ui-overlay'+ name).remove(); } return $(this); } // hide previous if any if ($('#w2ui-overlay'+ name).length > 0) { tmp_hide = $('#w2ui-overlay'+ name)[0].hide; $(document).off('click', tmp_hide); if (typeof tmp_hide === 'function') tmp_hide(); } if (obj.length > 0 && (obj[0].tagName == null || obj[0].tagName.toUpperCase() == 'BODY')) options.contextMenu = true; if (options.contextMenu && options.originalEvent == null) { console.log('ERROR: for context menu you need to pass options.originalEvent.'); } // append $('body').append( '<div id="w2ui-overlay'+ name +'" style="display: none; left: 0px; top: 0px; '+ options.overlayStyle +'"'+ ' class="w2ui-reset w2ui-overlay '+ ($(this).parents('.w2ui-popup, .w2ui-overlay-popup').length > 0 ? 'w2ui-overlay-popup' : '') +'">'+ ' <style></style>'+ ' <div style="min-width: 100%; '+ options.style +'" class="'+ options['class'] +'"></div>'+ '</div>' ); // init var div1 = $('#w2ui-overlay'+ name); var div2 = div1.find(' > div'); div2.html(options.html); // pick bg color of first div var bc = div2.css('background-color'); if (bc != null && bc !== 'rgba(0, 0, 0, 0)' && bc !== 'transparent') div1.css({ 'background-color': bc, 'border-color': bc }); var offset = $(obj).offset() || {}; div1.data('element', obj.length > 0 ? obj[0] : null) .data('options', options) .data('position', offset.left + 'x' + offset.top) .fadeIn('fast') .on('click', function (event) { // if there is label for input, it will produce 2 click events if (event.target.tagName.toUpperCase() == 'LABEL') event.stopPropagation(); }) .on('mousedown', function (event) { $('#w2ui-overlay'+ name).data('keepOpen', true); if (['INPUT', 'TEXTAREA', 'SELECT'].indexOf(event.target.tagName.toUpperCase()) == -1 && !options.selectable) { event.preventDefault(); } }); div1[0].hide = hide; div1[0].resize = resize; // need time to display setTimeout(function () { resize(); $(document).off('click', hide).on('click', hide); if (typeof options.onShow === 'function') options.onShow(); }, 10); monitor(); return $(this); // monitor position function monitor() { var tmp = $('#w2ui-overlay'+ name); if (tmp.data('element') !== obj[0]) return; // it if it different overlay if (tmp.length === 0) return; var offset = $(obj).offset() || {}; var pos = offset.left + 'x' + offset.top; if (tmp.data('position') !== pos) { hide(); } else { setTimeout(monitor, 250); } } // click anywhere else hides the drop down function hide(event) { if (event && event.button != 0) return; // only for left click button var div1 = $('#w2ui-overlay'+ name); if (div1.data('keepOpen') === true) { div1.removeData('keepOpen'); return; } var result; if (typeof options.onHide === 'function') result = options.onHide(); if (result === false) return; div1.remove(); $(document).off('click', hide); clearInterval(div1.data('timer')); } function resize () { var div1 = $('#w2ui-overlay'+ name); var div2 = div1.find(' > div'); // if goes over the screen, limit height and width if (div1.length > 0) { div2.height('auto').width('auto'); // width/height var overflowX = false; var overflowY = false; var h = div2.height(); var w = div2.width(); if (options.width && options.width < w) w = options.width; if (w < 30) w = 30; // if content of specific height if (options.tmp.contentHeight) { h = parseInt(options.tmp.contentHeight); div2.height(h); setTimeout(function () { var $div = div2.find('div.menu'); if (h > $div.height()) { div2.find('div.menu').css('overflow-y', 'hidden'); } }, 1); setTimeout(function () { var $div = div2.find('div.menu'); if ($div.css('overflow-y') != 'auto') $div.css('overflow-y', 'auto'); }, 10); } if (options.tmp.contentWidth) { w = parseInt(options.tmp.contentWidth); div2.width(w); setTimeout(function () { if (w > div2.find('div.menu > table').width()) { div2.find('div.menu > table').css('overflow-x', 'hidden'); } }, 1); setTimeout(function () { div2.find('div.menu > table').css('overflow-x', 'auto'); }, 10); } // adjust position var tmp = (w - 17) / 2; var boxLeft = options.left; var boxWidth = options.width; var tipLeft = options.tipLeft; // alignment switch (options.align) { case 'both': boxLeft = 17 + parseInt(options.left); if (options.width === 0) options.width = w2utils.getSize($(obj), 'width'); if (options.maxWidth && options.width > options.maxWidth) options.width = options.maxWidth; break; case 'left': boxLeft = 17 + parseInt(options.left); break; case 'right': boxLeft = w2utils.getSize($(obj), 'width') - w + 14 + parseInt(options.left); tipLeft = w - 40; break; } if (w === 30 && !boxWidth) boxWidth = 30; else boxWidth = (options.width ? options.width : 'auto'); if (tmp < 25) { boxLeft = 25 - tmp; tipLeft = Math.floor(tmp); } // Y coord var X, Y, offsetTop; if (options.contextMenu) { // context menu X = options.originalEvent.pageX + 8; Y = options.originalEvent.pageY - 0; offsetTop = options.originalEvent.pageY; } else { var offset = obj.offset() || {}; X = ((offset.left > 25 ? offset.left : 25) + boxLeft); Y = (offset.top + w2utils.getSize(obj, 'height') + options.top + 7); offsetTop = offset.top; } div1.css({ left : X + 'px', top : Y + 'px', 'min-width' : boxWidth, 'min-height': (options.height ? options.height : 'auto') }); // $(window).height() - has a problem in FF20 var offset = div2.offset() || {}; var maxHeight = window.innerHeight + $(document).scrollTop() - offset.top - 7; var maxWidth = window.innerWidth + $(document).scrollLeft() - offset.left - 7; if (options.contextMenu) { // context menu maxHeight = window.innerHeight - options.originalEvent.pageY - 15; maxWidth = window.innerWidth - options.originalEvent.pageX; } if ((maxHeight > -50 && maxHeight < 210) || options.openAbove === true) { var tipOffset; // show on top if (options.contextMenu) { // context menu maxHeight = options.originalEvent.pageY - 7; tipOffset = 5; } else { maxHeight = offset.top - $(document).scrollTop() - 7; tipOffset = 24; } if (options.maxHeight && maxHeight > options.maxHeight) maxHeight = options.maxHeight; if (h > maxHeight) { overflowY = true; div2.height(maxHeight).width(w).css({ 'overflow-y': 'auto' }); h = maxHeight; } div1.addClass('bottom-arrow'); div1.css('top', (offsetTop - h - tipOffset + options.top) + 'px'); div1.find('>style').html( '#w2ui-overlay'+ name +':before { margin-left: '+ parseInt(tipLeft) +'px; }'+ '#w2ui-overlay'+ name +':after { margin-left: '+ parseInt(tipLeft) +'px; }' ); } else { // show under if (options.maxHeight && maxHeight > options.maxHeight) maxHeight = options.maxHeight; if (h > maxHeight) { overflowY = true; div2.height(maxHeight).width(w).css({ 'overflow-y': 'auto' }); } div1.addClass('top-arrow'); div1.find('>style').html( '#w2ui-overlay'+ name +':before { margin-left: '+ parseInt(tipLeft) +'px; }'+ '#w2ui-overlay'+ name +':after { margin-left: '+ parseInt(tipLeft) +'px; }' ); } // check width w = div2.width(); maxWidth = window.innerWidth + $(document).scrollLeft() - offset.left - 7; if (options.maxWidth && maxWidth > options.maxWidth) maxWidth = options.maxWidth; if (w > maxWidth && options.align !== 'both') { options.align = 'right'; setTimeout(function () { resize(); }, 1); } // don't show tip if (options.contextMenu || options.noTip) { // context menu div1.find('>style').html( '#w2ui-overlay'+ name +':before { display: none; }'+ '#w2ui-overlay'+ name +':after { display: none; }' ); } // check scroll bar (needed to avoid horizontal scrollbar) if (overflowY && options.align != 'both') div2.width(w + w2utils.scrollBarSize() + 2); } } }; $.fn.w2menu = function (menu, options) { /* ITEM STRUCTURE item : { id : null, text : '', style : '', img : '', icon : '', count : '', hidden : false, checked : null, disabled : false ... } */ var defaults = { type : 'normal', // can be normal, radio, check index : null, // current selected items : [], render : null, msgNoItems : 'No items', onSelect : null, tmp : {} }; var obj = this; var name = ''; if (menu === 'refresh') { // if not show - call blur if ($('#w2ui-overlay'+ name).length > 0) { options = $.extend($.fn.w2menuOptions, options); var scrTop = $('#w2ui-overlay'+ name +' div.menu').scrollTop(); $('#w2ui-overlay'+ name +' div.menu').html(getMenuHTML()); $('#w2ui-overlay'+ name +' div.menu').scrollTop(scrTop); mresize(); } else { $(this).w2menu(options); } } else if (menu === 'refresh-index') { var $menu = $('#w2ui-overlay'+ name +' div.menu'); var cur = $menu.find('tr[index='+ options.index +']'); var scrTop = $menu.scrollTop(); $menu.find('tr.w2ui-selected').removeClass('w2ui-selected'); // clear all cur.addClass('w2ui-selected'); // select current // scroll into view if (cur.length > 0) { var top = cur[0].offsetTop - 5; // 5 is margin top var height = $menu.height(); $menu.scrollTop(scrTop); if (top < scrTop || top + cur.height() > scrTop + height) { $menu.animate({ 'scrollTop': top - (height - cur.height() * 2) / 2 }, 200, 'linear'); } } mresize(); } else { if (arguments.length === 1) options = menu; else options.items = menu; if (typeof options !== 'object') options = {}; options = $.extend({}, defaults, options); $.fn.w2menuOptions = options; if (options.name) name = '-' + options.name; if (typeof options.select === 'function' && typeof options.onSelect !== 'function') options.onSelect = options.select; if (typeof options.onRender === 'function' && typeof options.render !== 'function') options.render = options.onRender; // since only one overlay can exist at a time $.fn.w2menuClick = function (event, index) { if (['radio', 'check'].indexOf(options.type) != -1) { // move checkbox $(event.target).parents('tr').find('.w2ui-icon') .removeClass('w2ui-icon-empty') .addClass('w2ui-icon-check'); } if (typeof options.onSelect === 'function') { // need time so that menu first hides setTimeout(function () { options.onSelect({ index : index, item : options.items[index], originalEvent: event }); }, 10); } // do not uncomment (or enum search type is not working in grid) // setTimeout(function () { $(document).click(); }, 50); // -- hide var div = $('#w2ui-overlay'+ name); if (typeof div[0].hide === 'function') { div.removeData('keepOpen'); div[0].hide(); } }; $.fn.w2menuDown = function (event, index) { var $el = $(event.target).parents('tr'); var tmp = $el.find('.w2ui-icon'); if (tmp.hasClass('w2ui-icon-empty')) { if (options.type == 'radio') { tmp.parents('table').find('.w2ui-icon') .removeClass('w2ui-icon-check') .addClass('w2ui-icon-empty'); } tmp.removeClass('w2ui-icon-empty').addClass('w2ui-icon-check'); } else if (tmp.hasClass('w2ui-icon-check') && (options.type == 'check')) { tmp.removeClass('w2ui-icon-check').addClass('w2ui-icon-empty'); } $el.parent().find('tr').removeClass('w2ui-selected'); $el.addClass('w2ui-selected'); $.fn.w2menuTmp = $el; }; $.fn.w2menuOut = function (event, index) { var $tmp = $($.fn.w2menuTmp); if ($tmp.length > 0) { $tmp.removeClass('w2ui-selected'); $tmp.find('.w2ui-icon').removeClass('w2ui-icon-check'); delete $.fn.w2menuTmp; } }; var html = ''; if (options.search) { html += '<div style="position: absolute; top: 0px; height: 40px; left: 0px; right: 0px; border-bottom: 1px solid silver; background-color: #ECECEC; padding: 8px 5px;">'+ ' <div class="w2ui-icon icon-search" style="position: absolute; margin-top: 4px; margin-left: 6px; width: 11px; background-position: left !important;"></div>'+ ' <input id="menu-search" type="text" style="width: 100%; outline: none; padding-left: 20px;" onclick="event.stopPropagation();"/>'+ '</div>'; options.style += ';background-color: #ECECEC'; options.index = 0; for (var i = 0; i < options.items.length; i++) options.items[i].hidden = false; } html += '<div class="menu" style="position: absolute; top: '+ (options.search ? 40 : 0) + 'px; bottom: 0px; width: 100%;">' + getMenuHTML() + '</div>'; var ret = $(this).w2overlay(html, options); setTimeout(function () { $('#w2ui-overlay'+ name +' #menu-search') .on('keyup', change) .on('keydown', function (event) { // cancel tab key if (event.keyCode === 9) { event.stopPropagation(); event.preventDefault(); } }); if (options.search) { if (['text', 'password'].indexOf($(obj)[0].type) != -1 || $(obj)[0].tagName.toUpperCase() == 'TEXTAREA') return; $('#w2ui-overlay'+ name +' #menu-search').focus(); } mresize(); }, 200); mresize(); return ret; } return; function mresize() { setTimeout(function () { // show selected $('#w2ui-overlay'+ name +' tr.w2ui-selected').removeClass('w2ui-selected'); var cur = $('#w2ui-overlay'+ name +' tr[index='+ options.index +']'); var scrTop = $('#w2ui-overlay'+ name +' div.menu').scrollTop(); cur.addClass('w2ui-selected'); if (options.tmp) options.tmp.contentHeight = $('#w2ui-overlay'+ name +' table').height() + (options.search ? 50 : 10); if (options.tmp) options.tmp.contentWidth = $('#w2ui-overlay'+ name +' table').width(); if ($('#w2ui-overlay'+ name).length > 0) $('#w2ui-overlay'+ name)[0].resize(); // scroll into view if (cur.length > 0) { var top = cur[0].offsetTop - 5; // 5 is margin top var el = $('#w2ui-overlay'+ name +' div.menu'); var height = el.height(); $('#w2ui-overlay'+ name +' div.menu').scrollTop(scrTop); if (top < scrTop || top + cur.height() > scrTop + height) { $('#w2ui-overlay'+ name +' div.menu').animate({ 'scrollTop': top - (height - cur.height() * 2) / 2 }, 200, 'linear'); } } }, 1); } function change(event) { var search = this.value; var key = event.keyCode; var cancel = false; switch (key) { case 13: // enter $('#w2ui-overlay'+ name).remove(); $.fn.w2menuClick(event, options.index); break; case 9: // tab case 27: // escape $('#w2ui-overlay'+ name).remove(); $.fn.w2menuClick(event, -1); break; case 38: // up options.index = w2utils.isInt(options.index) ? parseInt(options.index) : 0; options.index--; while (options.index > 0 && options.items[options.index].hidden) options.index--; if (options.index === 0 && options.items[options.index].hidden) { while (options.items[options.index] && options.items[options.index].hidden) options.index++; } if (options.index < 0) options.index = 0; cancel = true; break; case 40: // down options.index = w2utils.isInt(options.index) ? parseInt(options.index) : 0; options.index++; while (options.index < options.items.length-1 && options.items[options.index].hidden) options.index++; if (options.index === options.items.length-1 && options.items[options.index].hidden) { while (options.items[options.index] && options.items[options.index].hidden) options.index--; } if (options.index >= options.items.length) options.index = options.items.length - 1; cancel = true; break; } // filter if (!cancel) { var shown = 0; for (var i = 0; i < options.items.length; i++) { var item = options.items[i]; var prefix = ''; var suffix = ''; if (['is', 'begins with'].indexOf(options.match) !== -1) prefix = '^'; if (['is', 'ends with'].indexOf(options.match) !== -1) suffix = '$'; try { var re = new RegExp(prefix + search + suffix, 'i'); if (re.test(item.text) || item.text === '...') item.hidden = false; else item.hidden = true; } catch (e) {} // do not show selected items if (obj.type === 'enum' && $.inArray(item.id, ids) !== -1) item.hidden = true; if (item.hidden !== true) shown++; } options.index = 0; while (options.index < options.items.length-1 && options.items[options.index].hidden) options.index++; if (shown <= 0) options.index = -1; } $(obj).w2menu('refresh', options); mresize(); } function getMenuHTML() { if (options.spinner) { return '<table class="w2ui-drop-menu"><tbody><tr><td style="padding: 5px 10px 10px 10px; text-align: center">'+ ' <div class="w2ui-spinner" style="width: 18px; height: 18px; position: relative; top: 5px;"></div> '+ ' <div style="display: inline-block; padding: 3px; color: #999;">'+ w2utils.lang('Loading...') +'</div>'+ '</td></tr></tbody></table>'; } var count = 0; var menu_html = '<table cellspacing="0" cellpadding="0" class="w2ui-drop-menu"><tbody>'; var img = null, icon = null; for (var f = 0; f < options.items.length; f++) { var mitem = options.items[f]; if (typeof mitem === 'string') { mitem = { id: mitem, text: mitem }; } else { if (mitem.text != null && mitem.id == null) mitem.id = mitem.text; if (mitem.text == null && mitem.id != null) mitem.text = mitem.id; if (mitem.caption != null) mitem.text = mitem.caption; img = mitem.img; icon = mitem.icon; if (img == null) img = null; if (icon == null) icon = null; } if (['radio', 'check'].indexOf(options.type) != -1) { if (mitem.checked === true) icon = 'w2ui-icon-check'; else icon = 'w2ui-icon-empty'; } if (mitem.hidden !== true) { var imgd = ''; var txt = mitem.text; if (typeof options.render === 'function') txt = options.render(mitem, options); if (img) imgd = '<td class="menu-icon"><div class="w2ui-tb-image w2ui-icon '+ img +'"></div></td>'; if (icon) imgd = '<td class="menu-icon" align="center"><span class="w2ui-icon '+ icon +'"></span></td>'; // render only if non-empty if (txt != null && txt !== '' && !(/^-+$/.test(txt))) { var bg = (count % 2 === 0 ? 'w2ui-item-even' : 'w2ui-item-odd'); if (options.altRows !== true) bg = ''; var colspan = 1; if (imgd == '') colspan++; if (mitem.count == null && mitem.hotkey == null) colspan++; if (mitem.tooltip == null && mitem.hint != null) mitem.tooltip = mitem.hint; // for backward compatibility menu_html += '<tr index="'+ f + '" style="'+ (mitem.style ? mitem.style : '') +'" '+ (mitem.tooltip ? 'title="'+ mitem.tooltip +'"' : '') + ' class="'+ bg +' '+ (options.index === f ? 'w2ui-selected' : '') + ' ' + (mitem.disabled === true ? 'w2ui-disabled' : '') +'"'+ ' onmousedown="if ('+ (mitem.disabled === true ? 'true' : 'false') + ') return;'+ ' $.fn.w2menuDown(event, \''+ f +'\');"'+ ' onmouseout="if ('+ (mitem.disabled === true ? 'true' : 'false') + ') return;'+ ' $.fn.w2menuOut(event, \''+ f +'\');"'+ ' onclick="event.stopPropagation(); '+ ' if ('+ (mitem.disabled === true ? 'true' : 'false') + ') return;'+ ' $.fn.w2menuClick(event, \''+ f +'\');">'+ imgd + ' <td class="menu-text" colspan="'+ colspan +'">'+ txt +'</td>'+ ' <td class="menu-count">'+ (mitem.count != null ? '<span>' + mitem.count + '</span>' : '') + (mitem.hotkey != null ? '<span class="hotkey">' + mitem.hotkey + '</span>' : '') + '</td>' + '</tr>'; count++; } else { // horizontal line menu_html += '<tr><td colspan="3" style="padding: 6px; pointer-events: none"><div style="border-top: 1px solid silver;"></div></td></tr>'; } } options.items[f] = mitem; } if (count === 0) { menu_html += '<tr><td style="padding: 13px; color: #999; text-align: center">'+ options.msgNoItems +'</div></td></tr>'; } menu_html += "</tbody></table>"; return menu_html; } }; $.fn.w2color = function (color, callBack) { var obj = this; var el = $(this)[0]; var index = [-1, -1]; if ($.fn.w2colorPalette == null) { $.fn.w2colorPalette = [ ['000000', '888888', 'BBBBBB', 'DDDDDD', 'EEEEEE', 'F7F7F7', 'FFFFFF', ''], ['FF011B', 'FF9838', 'FFFD59', '01FD55', '00FFFE', '006CE7', '9B24F4', 'FF21F5'], ['FFEAEA', 'FCEFE1', 'FCF5E1', 'EBF7E7', 'E9F3F5', 'ECF4FC', 'EAE6F4', 'F5E7ED'], ['F4CCCC', 'FCE5CD', 'FFF2CC', 'D9EAD3', 'D0E0E3', 'CFE2F3', 'D9D1E9', 'EAD1DC'], ['EA9899', 'F9CB9C', 'FEE599', 'B6D7A8', 'A2C4C9', '9FC5E8', 'B4A7D6', 'D5A6BD'], ['E06666', 'F6B26B', 'FED966', '93C47D', '76A5AF', '6FA8DC', '8E7CC3', 'C27BA0'], ['CC0814', 'E69138', 'F1C232', '6AA84F', '45818E', '3D85C6', '674EA7', 'A54D79'], ['99050C', 'B45F17', 'BF901F', '37761D', '124F5C', '0A5394', '351C75', '741B47'], // ['660205', '783F0B', '7F6011', '274E12', '0C343D', '063762', '20124D', '4C1030'], ['F2F2F2', 'F2F2F2', 'F2F2F2', 'F2F2F2', 'F2F2F2'] // custom colors (up to 4) ]; } var pal = $.fn.w2colorPalette; if (typeof color != 'string') color = ''; if (color) color = String(color).toUpperCase(); if ($('#w2ui-overlay').length == 0) { $(el).w2overlay(getColorHTML(color), { onHide: function () { if (typeof callBack == 'function') callBack($(el).data('_color')); $(el).removeData('_color'); } }); } else { // only refresh contents $('#w2ui-overlay .w2ui-color').parent().html(getColorHTML(color)); } // bind events $('#w2ui-overlay .color') .on('mousedown', function (event) { var color = $(event.originalEvent.target).attr('name'); index = $(event.originalEvent.target).attr('index').split(':'); $(el).data('_color', color); }) .on('mouseup', function () { setTimeout(function () { if ($("#w2ui-overlay").length > 0) $('#w2ui-overlay').removeData('keepOpen')[0].hide(); }, 10); }); $('#w2ui-overlay input') .on('mousedown', function (event) { $('#w2ui-overlay').data('keepOpen', true); setTimeout(function () { $('#w2ui-overlay').data('keepOpen', true); }, 10); event.stopPropagation(); }) .on('keyup', function (event) { if (this.value != '' && this.value[0] != '#') this.value = '#' + this.value; }) .on('change', function (event) { var tmp = this.value; if (tmp.substr(0, 1) == '#') tmp = tmp.substr(1); if (tmp.length != 6) { $(this).w2tag('Invalid color.'); return; } $.fn.w2colorPalette[pal.length - 1].unshift(tmp.toUpperCase()); $(el).w2color(color, callBack); setTimeout(function() { $('#w2ui-overlay input')[0].focus(); }, 100); }) .w2field('hex'); el.nav = function (direction) { switch (direction) { case 'up': index[0]--; break; case 'down': index[0]++; break; case 'right': index[1]++; break; case 'left': index[1]--; break; } if (index[0] < 0) index[0] = 0; if (index[0] > pal.length - 2) index[0] = pal.length - 2; if (index[1] < 0) index[1] = 0; if (index[1] > pal[0].length - 1) index[1] = pal[0].length - 1; color = pal[index[0]][index[1]]; $(el).data('_color', color); return color; }; function getColorHTML(color) { var html = '<div class="w2ui-color">'+ '<table cellspacing="5"><tbody>'; for (var i = 0; i < pal.length - 1; i++) { html += '<tr>'; for (var j = 0; j < pal[i].length; j++) { html += '<td>'+ ' <div class="color '+ (pal[i][j] == '' ? 'no-color' : '') +'" style="background-color: #'+ pal[i][j] +';" ' + ' name="'+ pal[i][j] +'" index="'+ i + ':' + j +'">'+ (color == pal[i][j] ? '&#149;' : '&#160;') + ' </div>'+ '</td>'; if (color == pal[i][j]) index = [i, j]; } html += '</tr>'; if (i < 2) html += '<tr><td style="height: 8px" colspan="8"></td></tr>'; } var tmp = pal[pal.length - 1]; html += '<tr><td style="height: 8px" colspan="8"></td></tr>'+ '<tr>'+ ' <td colspan="4" style="text-align: left"><input placeholder="#FFF000" style="margin-left: 1px; width: 74px" maxlength="7"/></td>'+ ' <td><div class="color" style="background-color: #'+ tmp[0] +';" name="'+ tmp[0] +'" index="8:0">'+ (color == tmp[0] ? '&#149;' : '&#160;') +'</div></td>'+ ' <td><div class="color" style="background-color: #'+ tmp[1] +';" name="'+ tmp[1] +'" index="8:0">'+ (color == tmp[1] ? '&#149;' : '&#160;') +'</div></td>'+ ' <td><div class="color" style="background-color: #'+ tmp[2] +';" name="'+ tmp[2] +'" index="8:0">'+ (color == tmp[2] ? '&#149;' : '&#160;') +'</div></td>'+ ' <td><div class="color" style="background-color: #'+ tmp[3] +';" name="'+ tmp[3] +'" index="8:0">'+ (color == tmp[3] ? '&#149;' : '&#160;') +'</div></td>'+ '</tr>'+ '<tr><td style="height: 4px" colspan="8"></td></tr>'; html += '</tbody></table></div>'; return html; } }; })(jQuery);
src/w2utils.js
var w2ui = w2ui || {}; var w2obj = w2obj || {}; // expose object to be able to overwrite default functions /************************************************ * Library: Web 2.0 UI for jQuery * - Following objects are defines * - w2ui - object that will contain all widgets * - w2obj - object with widget prototypes * - w2utils - basic utilities * - $().w2render - common render * - $().w2destroy - common destroy * - $().w2marker - marker plugin * - $().w2tag - tag plugin * - $().w2overlay - overlay plugin * - $().w2menu - menu plugin * - w2utils.event - generic event object * - Dependencies: jQuery * * == NICE TO HAVE == * - overlay should be displayed where more space (on top or on bottom) * - write and article how to replace certain framework functions * - add maxHeight for the w2menu * - add time zone * - TEST On IOS * - $().w2marker() -- only unmarks first instance * - subitems for w2menus() * - add w2utils.lang wrap for all captions in all buttons. * - $().w2date(), $().w2dateTime() * * == 1.5 changes * - date has problems in FF new Date('yyyy-mm-dd') breaks * - bug: w2utils.formatDate('2011-31-01', 'yyyy-dd-mm'); - wrong foratter * - format date and time is buggy * - added decimalSymbol * - renamed size() -> formatSize() * - added cssPrefix() * - added w2utils.settings.weekStarts * - onComplete should pass widget as context (this) * - hidden and disabled in menus * - added menu.item.tooltip for overlay menus * - added w2tag options.id, options.left, options.top * - added w2tag options.position = top|bottom|left|right - default is right * - added $().w2color(color, callBack) * - added custom colors * - added w2menu.options.type = radio|check * - added w2menu items.hotkey * - added options.contextMenu for w2overlay() * - added options.noTip for w2overlay() * - added options.overlayStyle for w2overlay() * - added options.selectable * - Refactored w2tag * - added options.style for w2tag * - added options.hideOnKeyPress for w2tag * - added options.hideOnBlur for w2tag * - events 'eventName:after' syntax * - deprecated onComplete, introduced event.done(func) - can have multiple handlers * - added getCursorPosition, setCursorPosition * - w2tag hideOnClick - hides on document click * - add isDateTime() * - data_format -> dateFormat, time_format -> timeFormat * - implemented w2utils.formatters (used in grid) * ************************************************/ var w2utils = (function ($) { var tmp = {}; // for some temp variables var obj = { version : '1.5.x', settings : { "locale" : "en-us", "dateFormat" : "m/d/yyyy", "timeFormat" : "hh:mi pm", "currencyPrefix" : "$", "currencySuffix" : "", "currencyPrecision" : 2, "groupSymbol" : ",", "decimalSymbol" : ".", "shortmonths" : ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], "fullmonths" : ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], "shortdays" : ["M", "T", "W", "T", "F", "S", "S"], "fulldays" : ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], "weekStarts" : "M", // can be "M" for Monday or "S" for Sunday "dataType" : 'HTTP', // can be HTTP, HTTPJSON, RESTFULL, RESTFULLJSON, JSON (case sensitive) "phrases" : {}, // empty object for english phrases "dateStartYear" : 1950, // start year for date-picker "dateEndYear" : 2020 // end year for date picker }, isBin : isBin, isInt : isInt, isFloat : isFloat, isMoney : isMoney, isHex : isHex, isAlphaNumeric : isAlphaNumeric, isEmail : isEmail, isDate : isDate, isTime : isTime, isDateTime : isDateTime, age : age, interval : interval, date : date, formatSize : formatSize, formatNumber : formatNumber, formatDate : formatDate, formatTime : formatTime, formatDateTime : formatDateTime, stripTags : stripTags, encodeTags : encodeTags, escapeId : escapeId, base64encode : base64encode, base64decode : base64decode, md5 : md5, transition : transition, lock : lock, unlock : unlock, lang : lang, locale : locale, getSize : getSize, getStrWidth : getStrWidth, scrollBarSize : scrollBarSize, checkName : checkName, checkUniqueId : checkUniqueId, parseRoute : parseRoute, cssPrefix : cssPrefix, getCursorPosition : getCursorPosition, setCursorPosition : setCursorPosition, // some internal variables isIOS : ((navigator.userAgent.toLowerCase().indexOf('iphone') != -1 || navigator.userAgent.toLowerCase().indexOf('ipod') != -1 || navigator.userAgent.toLowerCase().indexOf('ipad') != -1) ? true : false), isIE : ((navigator.userAgent.toLowerCase().indexOf('msie') != -1 || navigator.userAgent.toLowerCase().indexOf('trident') != -1 ) ? true : false) }; return obj; function isBin (val) { var re = /^[0-1]+$/; return re.test(val); } function isInt (val) { var re = /^[-+]?[0-9]+$/; return re.test(val); } function isFloat (val) { if (typeof val == 'string') val = val.replace(/\s+/g, '').replace(w2utils.settings.groupSymbol, '').replace(w2utils.settings.decimalSymbol, '.'); return (typeof val === 'number' || (typeof val === 'string' && val !== '')) && !isNaN(Number(val)); } function isMoney (val) { var se = w2utils.settings; var re = new RegExp('^'+ (se.currencyPrefix ? '\\' + se.currencyPrefix + '?' : '') + '[-+]?'+ (se.currencyPrefix ? '\\' + se.currencyPrefix + '?' : '') + '[0-9]*[\\'+ se.decimalSymbol +']?[0-9]+'+ (se.currencySuffix ? '\\' + se.currencySuffix + '?' : '') +'$', 'i'); if (typeof val === 'string') { val = val.replace(new RegExp(se.groupSymbol, 'g'), ''); } if (typeof val === 'object' || val === '') return false; return re.test(val); } function isHex (val) { var re = /^[a-fA-F0-9]+$/; return re.test(val); } function isAlphaNumeric (val) { var re = /^[a-zA-Z0-9_-]+$/; return re.test(val); } function isEmail (val) { var email = /^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; return email.test(val); } function isDate (val, format, retDate) { if (!val) return false; var dt = 'Invalid Date'; var month, day, year; if (format == null) format = w2utils.settings.dateFormat; if (typeof val.getUTCFullYear === 'function') { // date object year = val.getUTCFullYear(); month = val.getUTCMonth(); day = val.getUTCDate(); } else if (parseInt(val) == val && parseInt(val) > 0) { val = new Date(val); year = val.getUTCFullYear(); month = val.getUTCMonth(); day = val.getUTCDate(); } else { val = String(val); // convert month formats if (new RegExp('mon', 'ig').test(format)) { format = format.replace(/month/ig, 'm').replace(/mon/ig, 'm').replace(/dd/ig, 'd').replace(/[, ]/ig, '/').replace(/\/\//g, '/').toLowerCase(); val = val.replace(/[, ]/ig, '/').replace(/\/\//g, '/').toLowerCase(); for (var m = 0, len = w2utils.settings.fullmonths.length; m < len; m++) { var t = w2utils.settings.fullmonths[m]; val = val.replace(new RegExp(t, 'ig'), (parseInt(m) + 1)).replace(new RegExp(t.substr(0, 3), 'ig'), (parseInt(m) + 1)); } } // format date var tmp = val.replace(/-/g, '/').replace(/\./g, '/').toLowerCase().split('/'); var tmp2 = format.replace(/-/g, '/').replace(/\./g, '/').toLowerCase(); if (tmp2 === 'mm/dd/yyyy') { month = tmp[0]; day = tmp[1]; year = tmp[2]; } if (tmp2 === 'm/d/yyyy') { month = tmp[0]; day = tmp[1]; year = tmp[2]; } if (tmp2 === 'dd/mm/yyyy') { month = tmp[1]; day = tmp[0]; year = tmp[2]; } if (tmp2 === 'd/m/yyyy') { month = tmp[1]; day = tmp[0]; year = tmp[2]; } if (tmp2 === 'yyyy/dd/mm') { month = tmp[2]; day = tmp[1]; year = tmp[0]; } if (tmp2 === 'yyyy/d/m') { month = tmp[2]; day = tmp[1]; year = tmp[0]; } if (tmp2 === 'yyyy/mm/dd') { month = tmp[1]; day = tmp[2]; year = tmp[0]; } if (tmp2 === 'yyyy/m/d') { month = tmp[1]; day = tmp[2]; year = tmp[0]; } if (tmp2 === 'mm/dd/yy') { month = tmp[0]; day = tmp[1]; year = tmp[2]; } if (tmp2 === 'm/d/yy') { month = tmp[0]; day = tmp[1]; year = parseInt(tmp[2]) + 1900; } if (tmp2 === 'dd/mm/yy') { month = tmp[1]; day = tmp[0]; year = parseInt(tmp[2]) + 1900; } if (tmp2 === 'd/m/yy') { month = tmp[1]; day = tmp[0]; year = parseInt(tmp[2]) + 1900; } if (tmp2 === 'yy/dd/mm') { month = tmp[2]; day = tmp[1]; year = parseInt(tmp[0]) + 1900; } if (tmp2 === 'yy/d/m') { month = tmp[2]; day = tmp[1]; year = parseInt(tmp[0]) + 1900; } if (tmp2 === 'yy/mm/dd') { month = tmp[1]; day = tmp[2]; year = parseInt(tmp[0]) + 1900; } if (tmp2 === 'yy/m/d') { month = tmp[1]; day = tmp[2]; year = parseInt(tmp[0]) + 1900; } } if (!isInt(year)) return false; if (!isInt(month)) return false; if (!isInt(day)) return false; year = +year; month = +month; day = +day; dt = new Date(year, month - 1, day); // do checks if (month == null) return false; if (String(dt) == 'Invalid Date') return false; if ((dt.getMonth() + 1 !== month) || (dt.getDate() !== day) || (dt.getFullYear() !== year)) return false; if (retDate === true) return dt; else return true; } function isTime (val, retTime) { // Both formats 10:20pm and 22:20 if (val == null) return false; var max, pm; // -- process american format val = String(val); val = val.toUpperCase(); pm = val.indexOf('PM') >= 0; var ampm = (pm || val.indexOf('AM') >= 0); if (ampm) max = 12; else max = 24; val = val.replace('AM', '').replace('PM', ''); val = $.trim(val); // --- var tmp = val.split(':'); var h = parseInt(tmp[0] || 0), m = parseInt(tmp[1] || 0), s = parseInt(tmp[2] || 0); // accept edge case: 3PM is a good timestamp, but 3 (without AM or PM) is NOT: if ((!ampm || tmp.length !== 1) && tmp.length !== 2 && tmp.length !== 3) { return false; } if (tmp[0] === '' || h < 0 || h > max || !this.isInt(tmp[0]) || tmp[0].length > 2) { return false; } if (tmp.length > 1 && (tmp[1] === '' || m < 0 || m > 59 || !this.isInt(tmp[1]) || tmp[1].length !== 2)) { return false; } if (tmp.length > 2 && (tmp[2] === '' || s < 0 || s > 59 || !this.isInt(tmp[2]) || tmp[2].length !== 2)) { return false; } // check the edge cases: 12:01AM is ok, as is 12:01PM, but 24:01 is NOT ok while 24:00 is (midnight; equivalent to 00:00). // meanwhile, there is 00:00 which is ok, but 0AM nor 0PM are okay, while 0:01AM and 0:00AM are. if (!ampm && max === h && (m !== 0 || s !== 0)) { return false; } if (ampm && tmp.length === 1 && h === 0) { return false; } if (retTime === true) { if (pm) h += 12; return { hours: h, minutes: m, seconds: s }; } return true; } function isDateTime (val, format, retDate) { var formats = format.split('|'); if (typeof val.getUTCFullYear === 'function') { // date object if (retDate !== true) return true; return val; } else if (parseInt(val) == val && parseInt(val) > 0) { val = new Date(val); if (retDate !== true) return true; return val; } else { var tmp = String(val).indexOf(' '); var values = [val.substr(0, tmp), val.substr(tmp).trim()]; formats[0] = formats[0].trim(); if (formats[1]) formats[1] = formats[1].trim(); // check var tmp1 = w2utils.isDate(values[0], formats[0], true); var tmp2 = w2utils.isTime(values[1], true); if (tmp1 !== false && tmp2 !== false) { if (retDate !== true) return true; tmp1.setHours(tmp2[0]); tmp1.setMinutes(tmp2[1]); tmp1.setSeconds(tmp2[2]); return tmp1; } else { return false; } } } function age (dateStr) { if (dateStr === '' || dateStr == null || (typeof dateStr == 'object' && !dateStr.getMonth)) return ''; var d1 = new Date(dateStr); if (w2utils.isInt(dateStr)) d1 = new Date(Number(dateStr)); // for unix timestamps if (String(d1) == 'Invalid Date') return ''; var d2 = new Date(); var sec = (d2.getTime() - d1.getTime()) / 1000; var amount = ''; var type = ''; if (sec < 0) { amount = '<span style="color: #aaa">0 sec</span>'; type = ''; } else if (sec < 60) { amount = Math.floor(sec); type = 'sec'; if (sec < 0) { amount = 0; type = 'sec'; } } else if (sec < 60*60) { amount = Math.floor(sec/60); type = 'min'; } else if (sec < 24*60*60) { amount = Math.floor(sec/60/60); type = 'hour'; } else if (sec < 30*24*60*60) { amount = Math.floor(sec/24/60/60); type = 'day'; } else if (sec < 365*24*60*60) { amount = Math.floor(sec/30/24/60/60*10)/10; type = 'month'; } else if (sec < 365*4*24*60*60) { amount = Math.floor(sec/365/24/60/60*10)/10; type = 'year'; } else if (sec >= 365*4*24*60*60) { // factor in leap year shift (only older then 4 years) amount = Math.floor(sec/365.25/24/60/60*10)/10; type = 'year'; } return amount + ' ' + type + (amount > 1 ? 's' : ''); } function interval (value) { var ret = ''; if (value < 1000) { ret = "< 1 sec"; } else if (value < 60000) { ret = Math.floor(value / 1000) + " secs"; } else if (value < 3600000) { ret = Math.floor(value / 60000) + " mins"; } else if (value < 86400000) { ret = Math.floor(value / 3600000 * 10) / 10 + " hours"; } else if (value < 2628000000) { ret = Math.floor(value / 86400000 * 10) / 10 + " days"; } else if (value < 3.1536e+10) { ret = Math.floor(value / 2628000000 * 10) / 10 + " months"; } else { ret = Math.floor(value / 3.1536e+9) / 10 + " years"; } return ret; } function date (dateStr) { if (dateStr === '' || dateStr == null || (typeof dateStr == 'object' && !dateStr.getMonth)) return ''; var d1 = new Date(dateStr); if (w2utils.isInt(dateStr)) d1 = new Date(Number(dateStr)); // for unix timestamps if (String(d1) == 'Invalid Date') return ''; var months = w2utils.settings.shortmonths; var d2 = new Date(); // today var d3 = new Date(); d3.setTime(d3.getTime() - 86400000); // yesterday var dd1 = months[d1.getMonth()] + ' ' + d1.getDate() + ', ' + d1.getFullYear(); var dd2 = months[d2.getMonth()] + ' ' + d2.getDate() + ', ' + d2.getFullYear(); var dd3 = months[d3.getMonth()] + ' ' + d3.getDate() + ', ' + d3.getFullYear(); var time = (d1.getHours() - (d1.getHours() > 12 ? 12 :0)) + ':' + (d1.getMinutes() < 10 ? '0' : '') + d1.getMinutes() + ' ' + (d1.getHours() >= 12 ? 'pm' : 'am'); var time2= (d1.getHours() - (d1.getHours() > 12 ? 12 :0)) + ':' + (d1.getMinutes() < 10 ? '0' : '') + d1.getMinutes() + ':' + (d1.getSeconds() < 10 ? '0' : '') + d1.getSeconds() + ' ' + (d1.getHours() >= 12 ? 'pm' : 'am'); var dsp = dd1; if (dd1 === dd2) dsp = time; if (dd1 === dd3) dsp = w2utils.lang('Yesterday'); return '<span title="'+ dd1 +' ' + time2 +'">'+ dsp +'</span>'; } function formatSize (sizeStr) { if (!w2utils.isFloat(sizeStr) || sizeStr === '') return ''; sizeStr = parseFloat(sizeStr); if (sizeStr === 0) return 0; var sizes = ['Bt', 'KB', 'MB', 'GB', 'TB']; var i = parseInt( Math.floor( Math.log(sizeStr) / Math.log(1024) ) ); return (Math.floor(sizeStr / Math.pow(1024, i) * 10) / 10).toFixed(i === 0 ? 0 : 1) + ' ' + sizes[i]; } function formatNumber (val, fraction, useGrouping) { return parseFloat(val).toLocaleString(w2utils.settings.locale, { minimumFractionDigits : fraction, maximumFractionDigits : 20, useGrouping : useGrouping }); } function formatDate (dateStr, format) { // IMPORTANT dateStr HAS TO BE valid JavaScript Date String if (!format) format = this.settings.dateFormat; if (dateStr === '' || dateStr == null || (typeof dateStr == 'object' && !dateStr.getMonth)) return ''; var dt = new Date(dateStr); if (w2utils.isInt(dateStr)) dt = new Date(Number(dateStr)); // for unix timestamps if (String(dt) == 'Invalid Date') return ''; var year = dt.getFullYear(); var month = dt.getMonth(); var date = dt.getDate(); return format.toLowerCase() .replace('month', w2utils.settings.fullmonths[month]) .replace('mon', w2utils.settings.shortmonths[month]) .replace(/yyyy/g, year) .replace(/yyy/g, year) .replace(/yy/g, year > 2000 ? 100 + parseInt(String(year).substr(2)) : String(year).substr(2)) .replace(/(^|[^a-z$])y/g, '$1' + year) // only y's that are not preceded by a letter .replace(/mm/g, (month + 1 < 10 ? '0' : '') + (month + 1)) .replace(/dd/g, (date < 10 ? '0' : '') + date) .replace(/th/g, (date == 1 ? 'st' : 'th')) .replace(/th/g, (date == 2 ? 'nd' : 'th')) .replace(/th/g, (date == 3 ? 'rd' : 'th')) .replace(/(^|[^a-z$])m/g, '$1' + (month + 1)) // only y's that are not preceded by a letter .replace(/(^|[^a-z$])d/g, '$1' + date); // only y's that are not preceded by a letter } function formatTime (dateStr, format) { // IMPORTANT dateStr HAS TO BE valid JavaScript Date String var months = w2utils.settings.shortmonths; var fullMonths = w2utils.settings.fullmonths; if (!format) format = this.settings.timeFormat; if (dateStr === '' || dateStr == null || (typeof dateStr == 'object' && !dateStr.getMonth)) return ''; var dt = new Date(dateStr); if (w2utils.isInt(dateStr)) dt = new Date(Number(dateStr)); // for unix timestamps if (w2utils.isTime(dateStr)) { var tmp = w2utils.isTime(dateStr, true); dt = new Date(); dt.setHours(tmp.hours); dt.setMinutes(tmp.minutes); } if (String(dt) == 'Invalid Date') return ''; var type = 'am'; var hour = dt.getHours(); var h24 = dt.getHours(); var min = dt.getMinutes(); var sec = dt.getSeconds(); if (min < 10) min = '0' + min; if (sec < 10) sec = '0' + sec; if (format.indexOf('am') !== -1 || format.indexOf('pm') !== -1) { if (hour >= 12) type = 'pm'; if (hour > 12) hour = hour - 12; } return format.toLowerCase() .replace('am', type) .replace('pm', type) .replace('hhh', (hour < 10 ? '0' + hour : hour)) .replace('hh24', (h24 < 10 ? '0' + h24 : h24)) .replace('h24', h24) .replace('hh', hour) .replace('mm', min) .replace('mi', min) .replace('ss', sec) .replace(/(^|[^a-z$])h/g, '$1' + hour) // only y's that are not preceded by a letter .replace(/(^|[^a-z$])m/g, '$1' + min) // only y's that are not preceded by a letter .replace(/(^|[^a-z$])s/g, '$1' + sec); // only y's that are not preceded by a letter } function formatDateTime(dateStr, format) { var fmt; if (dateStr === '' || dateStr == null || (typeof dateStr == 'object' && !dateStr.getMonth)) return ''; if (typeof format !== 'string') { fmt = [this.settings.dateFormat, this.settings.timeFormat]; } else { fmt = format.split('|'); fmt[0] = fmt[0].trim(); fmt[1] = fmt[1].trim(); } // older formats support if (fmt[1] == 'h12') fmt[1] = 'h:m pm'; if (fmt[1] == 'h24') fmt[1] = 'h24:m'; return this.formatDate(dateStr, fmt[0]) + ' ' + this.formatTime(dateStr, fmt[1]); } function stripTags (html) { if (html == null) return html; switch (typeof html) { case 'number': break; case 'string': html = $.trim(String(html).replace(/(<([^>]+)>)/ig, "")); break; case 'object': // does not modify original object, but creates a copy if (Array.isArray(html)) { html = $.extend(true, [], html); for (var i = 0; i < html.length; i++) html[i] = this.stripTags(html[i]); } else { html = $.extend(true, {}, html); for (var i in html) html[i] = this.stripTags(html[i]); } break; } return html; } function encodeTags (html) { if (html == null) return html; switch (typeof html) { case 'number': break; case 'string': html = String(html).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;"); break; case 'object': // does not modify original object, but creates a copy if (Array.isArray(html)) { html = $.extend(true, [], html); for (var i = 0; i < html.length; i++) html[i] = this.encodeTags(html[i]); } else { html = $.extend(true, {}, html); for (var i in html) html[i] = this.encodeTags(html[i]); } break; } return html; } function escapeId (id) { if (id === '' || id == null) return ''; return String(id).replace(/([;&,\.\+\*\~'`:"\!\^#$%@\[\]\(\)=<>\|\/? {}\\])/g, '\\$1'); } function base64encode (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; input = utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); } function utf8_encode (string) { string = String(string).replace(/\r\n/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; } return output; } function base64decode (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = keyStr.indexOf(input.charAt(i++)); enc2 = keyStr.indexOf(input.charAt(i++)); enc3 = keyStr.indexOf(input.charAt(i++)); enc4 = keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 !== 64) { output = output + String.fromCharCode(chr2); } if (enc4 !== 64) { output = output + String.fromCharCode(chr3); } } output = utf8_decode(output); function utf8_decode (utftext) { var string = ""; var i = 0; var c = 0, c2, c3; while ( i < utftext.length ) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i+1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; } return output; } function md5(input) { /* * Based on http://pajhome.org.uk/crypt/md5 */ var hexcase = 0; var b64pad = ""; function __pj_crypt_hex_md5(s) { return __pj_crypt_rstr2hex(__pj_crypt_rstr_md5(__pj_crypt_str2rstr_utf8(s))); } function __pj_crypt_b64_md5(s) { return __pj_crypt_rstr2b64(__pj_crypt_rstr_md5(__pj_crypt_str2rstr_utf8(s))); } function __pj_crypt_any_md5(s, e) { return __pj_crypt_rstr2any(__pj_crypt_rstr_md5(__pj_crypt_str2rstr_utf8(s)), e); } function __pj_crypt_hex_hmac_md5(k, d) { return __pj_crypt_rstr2hex(__pj_crypt_rstr_hmac_md5(__pj_crypt_str2rstr_utf8(k), __pj_crypt_str2rstr_utf8(d))); } function __pj_crypt_b64_hmac_md5(k, d) { return __pj_crypt_rstr2b64(__pj_crypt_rstr_hmac_md5(__pj_crypt_str2rstr_utf8(k), __pj_crypt_str2rstr_utf8(d))); } function __pj_crypt_any_hmac_md5(k, d, e) { return __pj_crypt_rstr2any(__pj_crypt_rstr_hmac_md5(__pj_crypt_str2rstr_utf8(k), __pj_crypt_str2rstr_utf8(d)), e); } /* * Calculate the MD5 of a raw string */ function __pj_crypt_rstr_md5(s) { return __pj_crypt_binl2rstr(__pj_crypt_binl_md5(__pj_crypt_rstr2binl(s), s.length * 8)); } /* * Calculate the HMAC-MD5, of a key and some data (raw strings) */ function __pj_crypt_rstr_hmac_md5(key, data) { var bkey = __pj_crypt_rstr2binl(key); if (bkey.length > 16) bkey = __pj_crypt_binl_md5(bkey, key.length * 8); var ipad = Array(16), opad = Array(16); for (var i = 0; i < 16; i++) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } var hash = __pj_crypt_binl_md5(ipad.concat(__pj_crypt_rstr2binl(data)), 512 + data.length * 8); return __pj_crypt_binl2rstr(__pj_crypt_binl_md5(opad.concat(hash), 512 + 128)); } /* * Convert a raw string to a hex string */ function __pj_crypt_rstr2hex(input) { try { hexcase } catch (e) { hexcase = 0; } var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; var output = ""; var x; for (var i = 0; i < input.length; i++) { x = input.charCodeAt(i); output += hex_tab.charAt((x >>> 4) & 0x0F) + hex_tab.charAt(x & 0x0F); } return output; } /* * Convert a raw string to a base-64 string */ function __pj_crypt_rstr2b64(input) { try { b64pad } catch (e) { b64pad = ''; } var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var output = ""; var len = input.length; for (var i = 0; i < len; i += 3) { var triplet = (input.charCodeAt(i) << 16) | (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0) | (i + 2 < len ? input.charCodeAt(i + 2) : 0); for (var j = 0; j < 4; j++) { if (i * 8 + j * 6 > input.length * 8) output += b64pad; else output += tab.charAt((triplet >>> 6 * (3 - j)) & 0x3F); } } return output; } /* * Convert a raw string to an arbitrary string encoding */ function __pj_crypt_rstr2any(input, encoding) { var divisor = encoding.length; var i, j, q, x, quotient; /* Convert to an array of 16-bit big-endian values, forming the dividend */ var dividend = Array(Math.ceil(input.length / 2)); for (i = 0; i < dividend.length; i++) { dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1); } /* * Repeatedly perform a long division. The binary array forms the dividend, * the length of the encoding is the divisor. Once computed, the quotient * forms the dividend for the next step. All remainders are stored for later * use. */ var full_length = Math.ceil(input.length * 8 / (Math.log(encoding.length) / Math.log(2))); var remainders = Array(full_length); for (j = 0; j < full_length; j++) { quotient = Array(); x = 0; for (i = 0; i < dividend.length; i++) { x = (x << 16) + dividend[i]; q = Math.floor(x / divisor); x -= q * divisor; if (quotient.length > 0 || q > 0) quotient[quotient.length] = q; } remainders[j] = x; dividend = quotient; } /* Convert the remainders to the output string */ var output = ""; for (i = remainders.length - 1; i >= 0; i--) output += encoding.charAt(remainders[i]); return output; } /* * Encode a string as utf-8. * For efficiency, this assumes the input is valid utf-16. */ function __pj_crypt_str2rstr_utf8(input) { var output = ""; var i = -1; var x, y; while (++i < input.length) { /* Decode utf-16 surrogate pairs */ x = input.charCodeAt(i); y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0; if (0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF) { x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF); i++; } /* Encode output as utf-8 */ if (x <= 0x7F) output += String.fromCharCode(x); else if (x <= 0x7FF) output += String.fromCharCode(0xC0 | ((x >>> 6) & 0x1F), 0x80 | (x & 0x3F)); else if (x <= 0xFFFF) output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F), 0x80 | ((x >>> 6) & 0x3F), 0x80 | (x & 0x3F)); else if (x <= 0x1FFFFF) output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07), 0x80 | ((x >>> 12) & 0x3F), 0x80 | ((x >>> 6) & 0x3F), 0x80 | (x & 0x3F)); } return output; } /* * Encode a string as utf-16 */ function __pj_crypt_str2rstr_utf16le(input) { var output = ""; for (var i = 0; i < input.length; i++) output += String.fromCharCode(input.charCodeAt(i) & 0xFF, (input.charCodeAt(i) >>> 8) & 0xFF); return output; } function __pj_crypt_str2rstr_utf16be(input) { var output = ""; for (var i = 0; i < input.length; i++) output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF, input.charCodeAt(i) & 0xFF); return output; } /* * Convert a raw string to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ function __pj_crypt_rstr2binl(input) { var output = Array(input.length >> 2); for (var i = 0; i < output.length; i++) output[i] = 0; for (var i = 0; i < input.length * 8; i += 8) output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32); return output; } /* * Convert an array of little-endian words to a string */ function __pj_crypt_binl2rstr(input) { var output = ""; for (var i = 0; i < input.length * 32; i += 8) output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); return output; } /* * Calculate the MD5 of an array of little-endian words, and a bit length. */ function __pj_crypt_binl_md5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << ((len) % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; for (var i = 0; i < x.length; i += 16) { var olda = a; var oldb = b; var oldc = c; var oldd = d; a = __pj_crypt_md5_ff(a, b, c, d, x[i + 0], 7, -680876936); d = __pj_crypt_md5_ff(d, a, b, c, x[i + 1], 12, -389564586); c = __pj_crypt_md5_ff(c, d, a, b, x[i + 2], 17, 606105819); b = __pj_crypt_md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); a = __pj_crypt_md5_ff(a, b, c, d, x[i + 4], 7, -176418897); d = __pj_crypt_md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); c = __pj_crypt_md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); b = __pj_crypt_md5_ff(b, c, d, a, x[i + 7], 22, -45705983); a = __pj_crypt_md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); d = __pj_crypt_md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); c = __pj_crypt_md5_ff(c, d, a, b, x[i + 10], 17, -42063); b = __pj_crypt_md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); a = __pj_crypt_md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); d = __pj_crypt_md5_ff(d, a, b, c, x[i + 13], 12, -40341101); c = __pj_crypt_md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); b = __pj_crypt_md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); a = __pj_crypt_md5_gg(a, b, c, d, x[i + 1], 5, -165796510); d = __pj_crypt_md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); c = __pj_crypt_md5_gg(c, d, a, b, x[i + 11], 14, 643717713); b = __pj_crypt_md5_gg(b, c, d, a, x[i + 0], 20, -373897302); a = __pj_crypt_md5_gg(a, b, c, d, x[i + 5], 5, -701558691); d = __pj_crypt_md5_gg(d, a, b, c, x[i + 10], 9, 38016083); c = __pj_crypt_md5_gg(c, d, a, b, x[i + 15], 14, -660478335); b = __pj_crypt_md5_gg(b, c, d, a, x[i + 4], 20, -405537848); a = __pj_crypt_md5_gg(a, b, c, d, x[i + 9], 5, 568446438); d = __pj_crypt_md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); c = __pj_crypt_md5_gg(c, d, a, b, x[i + 3], 14, -187363961); b = __pj_crypt_md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); a = __pj_crypt_md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); d = __pj_crypt_md5_gg(d, a, b, c, x[i + 2], 9, -51403784); c = __pj_crypt_md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); b = __pj_crypt_md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); a = __pj_crypt_md5_hh(a, b, c, d, x[i + 5], 4, -378558); d = __pj_crypt_md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); c = __pj_crypt_md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); b = __pj_crypt_md5_hh(b, c, d, a, x[i + 14], 23, -35309556); a = __pj_crypt_md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); d = __pj_crypt_md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); c = __pj_crypt_md5_hh(c, d, a, b, x[i + 7], 16, -155497632); b = __pj_crypt_md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); a = __pj_crypt_md5_hh(a, b, c, d, x[i + 13], 4, 681279174); d = __pj_crypt_md5_hh(d, a, b, c, x[i + 0], 11, -358537222); c = __pj_crypt_md5_hh(c, d, a, b, x[i + 3], 16, -722521979); b = __pj_crypt_md5_hh(b, c, d, a, x[i + 6], 23, 76029189); a = __pj_crypt_md5_hh(a, b, c, d, x[i + 9], 4, -640364487); d = __pj_crypt_md5_hh(d, a, b, c, x[i + 12], 11, -421815835); c = __pj_crypt_md5_hh(c, d, a, b, x[i + 15], 16, 530742520); b = __pj_crypt_md5_hh(b, c, d, a, x[i + 2], 23, -995338651); a = __pj_crypt_md5_ii(a, b, c, d, x[i + 0], 6, -198630844); d = __pj_crypt_md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); c = __pj_crypt_md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); b = __pj_crypt_md5_ii(b, c, d, a, x[i + 5], 21, -57434055); a = __pj_crypt_md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); d = __pj_crypt_md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); c = __pj_crypt_md5_ii(c, d, a, b, x[i + 10], 15, -1051523); b = __pj_crypt_md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); a = __pj_crypt_md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); d = __pj_crypt_md5_ii(d, a, b, c, x[i + 15], 10, -30611744); c = __pj_crypt_md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); b = __pj_crypt_md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); a = __pj_crypt_md5_ii(a, b, c, d, x[i + 4], 6, -145523070); d = __pj_crypt_md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); c = __pj_crypt_md5_ii(c, d, a, b, x[i + 2], 15, 718787259); b = __pj_crypt_md5_ii(b, c, d, a, x[i + 9], 21, -343485551); a = __pj_crypt_safe_add(a, olda); b = __pj_crypt_safe_add(b, oldb); c = __pj_crypt_safe_add(c, oldc); d = __pj_crypt_safe_add(d, oldd); } return Array(a, b, c, d); } /* * These functions implement the four basic operations the algorithm uses. */ function __pj_crypt_md5_cmn(q, a, b, x, s, t) { return __pj_crypt_safe_add(__pj_crypt_bit_rol(__pj_crypt_safe_add(__pj_crypt_safe_add(a, q), __pj_crypt_safe_add(x, t)), s), b); } function __pj_crypt_md5_ff(a, b, c, d, x, s, t) { return __pj_crypt_md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function __pj_crypt_md5_gg(a, b, c, d, x, s, t) { return __pj_crypt_md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function __pj_crypt_md5_hh(a, b, c, d, x, s, t) { return __pj_crypt_md5_cmn(b ^ c ^ d, a, b, x, s, t); } function __pj_crypt_md5_ii(a, b, c, d, x, s, t) { return __pj_crypt_md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function __pj_crypt_safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function __pj_crypt_bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } return __pj_crypt_hex_md5(input); } function transition (div_old, div_new, type, callBack) { var width = $(div_old).width(); var height = $(div_old).height(); var time = 0.5; if (!div_old || !div_new) { console.log('ERROR: Cannot do transition when one of the divs is null'); return; } div_old.parentNode.style.cssText += 'perspective: 700; overflow: hidden;'; div_old.style.cssText += '; position: absolute; z-index: 1019; backface-visibility: hidden'; div_new.style.cssText += '; position: absolute; z-index: 1020; backface-visibility: hidden'; switch (type) { case 'slide-left': // init divs div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0)'; div_new.style.cssText += 'overflow: hidden; transform: translate3d('+ width + 'px, 0, 0)'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; transform: translate3d(0, 0, 0)'; div_old.style.cssText += 'transition: '+ time +'s; transform: translate3d(-'+ width +'px, 0, 0)'; }, 1); break; case 'slide-right': // init divs div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0)'; div_new.style.cssText += 'overflow: hidden; transform: translate3d(-'+ width +'px, 0, 0)'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; transform: translate3d(0px, 0, 0)'; div_old.style.cssText += 'transition: '+ time +'s; transform: translate3d('+ width +'px, 0, 0)'; }, 1); break; case 'slide-down': // init divs div_old.style.cssText += 'overflow: hidden; z-index: 1; transform: translate3d(0, 0, 0)'; div_new.style.cssText += 'overflow: hidden; z-index: 0; transform: translate3d(0, 0, 0)'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; transform: translate3d(0, 0, 0)'; div_old.style.cssText += 'transition: '+ time +'s; transform: translate3d(0, '+ height +'px, 0)'; }, 1); break; case 'slide-up': // init divs div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0)'; div_new.style.cssText += 'overflow: hidden; transform: translate3d(0, '+ height +'px, 0)'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; transform: translate3d(0, 0, 0)'; div_old.style.cssText += 'transition: '+ time +'s; transform: translate3d(0, 0, 0)'; }, 1); break; case 'flip-left': // init divs div_old.style.cssText += 'overflow: hidden; transform: rotateY(0deg)'; div_new.style.cssText += 'overflow: hidden; transform: rotateY(-180deg)'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; transform: rotateY(0deg)'; div_old.style.cssText += 'transition: '+ time +'s; transform: rotateY(180deg)'; }, 1); break; case 'flip-right': // init divs div_old.style.cssText += 'overflow: hidden; transform: rotateY(0deg)'; div_new.style.cssText += 'overflow: hidden; transform: rotateY(180deg)'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; transform: rotateY(0deg)'; div_old.style.cssText += 'transition: '+ time +'s; transform: rotateY(-180deg)'; }, 1); break; case 'flip-down': // init divs div_old.style.cssText += 'overflow: hidden; transform: rotateX(0deg)'; div_new.style.cssText += 'overflow: hidden; transform: rotateX(180deg)'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; transform: rotateX(0deg)'; div_old.style.cssText += 'transition: '+ time +'s; transform: rotateX(-180deg)'; }, 1); break; case 'flip-up': // init divs div_old.style.cssText += 'overflow: hidden; transform: rotateX(0deg)'; div_new.style.cssText += 'overflow: hidden; transform: rotateX(-180deg)'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; transform: rotateX(0deg)'; div_old.style.cssText += 'transition: '+ time +'s; transform: rotateX(180deg)'; }, 1); break; case 'pop-in': // init divs div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0)'; div_new.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0); transform: scale(.8); opacity: 0;'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; transform: scale(1); opacity: 1;'; div_old.style.cssText += 'transition: '+ time +'s;'; }, 1); break; case 'pop-out': // init divs div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0); transform: scale(1); opacity: 1;'; div_new.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0); opacity: 0;'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; opacity: 1;'; div_old.style.cssText += 'transition: '+ time +'s; transform: scale(1.7); opacity: 0;'; }, 1); break; default: // init divs div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0)'; div_new.style.cssText += 'overflow: hidden; translate3d(0, 0, 0); opacity: 0;'; $(div_new).show(); // -- need a timing function because otherwise not working window.setTimeout(function() { div_new.style.cssText += 'transition: '+ time +'s; opacity: 1;'; div_old.style.cssText += 'transition: '+ time +'s'; }, 1); break; } setTimeout(function () { if (type === 'slide-down') { $(div_old).css('z-index', '1019'); $(div_new).css('z-index', '1020'); } if (div_new) { $(div_new).css({ 'opacity': '1' }).css(w2utils.cssPrefix({ 'transition': '', 'transform' : '' })); } if (div_old) { $(div_old).css({ 'opacity': '1' }).css(w2utils.cssPrefix({ 'transition': '', 'transform' : '' })); } if (typeof callBack === 'function') callBack(); }, time * 1000); } function lock (box, msg, spinner) { var options = {}; if (typeof msg === 'object') { options = msg; } else { options.msg = msg; options.spinner = spinner; } if (!options.msg && options.msg !== 0) options.msg = ''; w2utils.unlock(box); $(box).prepend( '<div class="w2ui-lock"></div>'+ '<div class="w2ui-lock-msg"></div>' ); var $lock = $(box).find('.w2ui-lock'); var mess = $(box).find('.w2ui-lock-msg'); if (!options.msg) mess.css({ 'background-color': 'transparent', 'border': '0px' }); if (options.spinner === true) options.msg = '<div class="w2ui-spinner" '+ (!options.msg ? 'style="width: 35px; height: 35px"' : '') +'></div>' + options.msg; if (options.opacity != null) $lock.css('opacity', options.opacity); if (typeof $lock.fadeIn == 'function') { $lock.fadeIn(200); mess.html(options.msg).fadeIn(200); } else { $lock.show(); mess.html(options.msg).show(0); } // hide all tags (do not hide overlays as the form can be in overlay) $().w2tag(); } function unlock (box, speed) { if (isInt(speed)) { $(box).find('.w2ui-lock').fadeOut(speed); setTimeout(function () { $(box).find('.w2ui-lock').remove(); $(box).find('.w2ui-lock-msg').remove(); }, speed); } else { $(box).find('.w2ui-lock').remove(); $(box).find('.w2ui-lock-msg').remove(); } } function getSize (el, type) { var $el = $(el); var bwidth = { left : parseInt($el.css('border-left-width')) || 0, right : parseInt($el.css('border-right-width')) || 0, top : parseInt($el.css('border-top-width')) || 0, bottom : parseInt($el.css('border-bottom-width')) || 0 }; var mwidth = { left : parseInt($el.css('margin-left')) || 0, right : parseInt($el.css('margin-right')) || 0, top : parseInt($el.css('margin-top')) || 0, bottom : parseInt($el.css('margin-bottom')) || 0 }; var pwidth = { left : parseInt($el.css('padding-left')) || 0, right : parseInt($el.css('padding-right')) || 0, top : parseInt($el.css('padding-top')) || 0, bottom : parseInt($el.css('padding-bottom')) || 0 }; switch (type) { case 'top' : return bwidth.top + mwidth.top + pwidth.top; case 'bottom' : return bwidth.bottom + mwidth.bottom + pwidth.bottom; case 'left' : return bwidth.left + mwidth.left + pwidth.left; case 'right' : return bwidth.right + mwidth.right + pwidth.right; case 'width' : return bwidth.left + bwidth.right + mwidth.left + mwidth.right + pwidth.left + pwidth.right + parseInt($el.width()); case 'height' : return bwidth.top + bwidth.bottom + mwidth.top + mwidth.bottom + pwidth.top + pwidth.bottom + parseInt($el.height()); case '+width' : return bwidth.left + bwidth.right + mwidth.left + mwidth.right + pwidth.left + pwidth.right; case '+height' : return bwidth.top + bwidth.bottom + mwidth.top + mwidth.bottom + pwidth.top + pwidth.bottom; } return 0; } function getStrWidth (str, styles) { var w, html = '<div id="_tmp_width" style="position: absolute; top: -900px;'+ styles +'">'+ str +'</div>'; $('body').append(html); w = $('#_tmp_width').width(); $('#_tmp_width').remove(); return w; } function lang (phrase) { var translation = this.settings.phrases[phrase]; if (translation == null) return phrase; else return translation; } function locale (locale) { if (!locale) locale = 'en-us'; // if the locale is an object, not a string, than we assume it's a if(typeof locale !== "string" ) { w2utils.settings = $.extend(true, w2utils.settings, locale); return } if (locale.length === 5) locale = 'locale/'+ locale +'.json'; // clear phrases from language before w2utils.settings.phrases = {}; // load from the file $.ajax({ url : locale, type : "GET", dataType : "JSON", async : false, cache : false, success : function (data, status, xhr) { w2utils.settings = $.extend(true, w2utils.settings, data); }, error : function (xhr, status, msg) { console.log('ERROR: Cannot load locale '+ locale); } }); } function scrollBarSize () { if (tmp.scrollBarSize) return tmp.scrollBarSize; var html = '<div id="_scrollbar_width" style="position: absolute; top: -300px; width: 100px; height: 100px; overflow-y: scroll;">'+ ' <div style="height: 120px">1</div>'+ '</div>'; $('body').append(html); tmp.scrollBarSize = 100 - $('#_scrollbar_width > div').width(); $('#_scrollbar_width').remove(); if (String(navigator.userAgent).indexOf('MSIE') >= 0) tmp.scrollBarSize = tmp.scrollBarSize / 2; // need this for IE9+ return tmp.scrollBarSize; } function checkName (params, component) { // was w2checkNameParam if (!params || params.name == null) { console.log('ERROR: The parameter "name" is required but not supplied in $().'+ component +'().'); return false; } if (w2ui[params.name] != null) { console.log('ERROR: The parameter "name" is not unique. There are other objects already created with the same name (obj: '+ params.name +').'); return false; } if (!w2utils.isAlphaNumeric(params.name)) { console.log('ERROR: The parameter "name" has to be alpha-numeric (a-z, 0-9, dash and underscore). '); return false; } return true; } function checkUniqueId (id, items, itemsDecription, objName) { // was w2checkUniqueId if (!$.isArray(items)) items = [items]; for (var i = 0; i < items.length; i++) { if (items[i].id === id) { console.log('ERROR: The parameter "id='+ id +'" is not unique within the current '+ itemsDecription +'. (obj: '+ objName +')'); return false; } } return true; } function parseRoute(route) { var keys = []; var path = route .replace(/\/\(/g, '(?:/') .replace(/\+/g, '__plus__') .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, function(_, slash, format, key, capture, optional) { keys.push({ name: key, optional: !! optional }); slash = slash || ''; return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')' + (optional || ''); }) .replace(/([\/.])/g, '\\$1') .replace(/__plus__/g, '(.+)') .replace(/\*/g, '(.*)'); return { path : new RegExp('^' + path + '$', 'i'), keys : keys }; } function cssPrefix(field, value, returnString) { var css = {}; var newCSS = {}; var ret = ''; if (!$.isPlainObject(field)) { css[field] = value; } else { css = field; if (value === true) returnString = true; } for (var c in css) { newCSS[c] = css[c]; newCSS['-webkit-'+c] = css[c]; newCSS['-moz-'+c] = css[c].replace('-webkit-', '-moz-'); newCSS['-ms-'+c] = css[c].replace('-webkit-', '-ms-'); newCSS['-o-'+c] = css[c].replace('-webkit-', '-o-'); } if (returnString === true) { for (var c in newCSS) { ret += c + ': ' + newCSS[c] + '; '; } } else { ret = newCSS; } return ret; } function getCursorPosition(input) { if (input == null) return null; var caretOffset = 0; var doc = input.ownerDocument || input.document; var win = doc.defaultView || doc.parentWindow; var sel; if (win.getSelection) { sel = win.getSelection(); if (sel.rangeCount > 0) { var range = sel.getRangeAt(0); var preCaretRange = range.cloneRange(); preCaretRange.selectNodeContents(input); preCaretRange.setEnd(range.endContainer, range.endOffset); caretOffset = preCaretRange.toString().length; } } else if ( (sel = doc.selection) && sel.type != "Control") { var textRange = sel.createRange(); var preCaretTextRange = doc.body.createTextRange(); preCaretTextRange.moveToElementText(input); preCaretTextRange.setEndPoint("EndToEnd", textRange); caretOffset = preCaretTextRange.text.length; } return caretOffset; } function setCursorPosition(input, pos, posEnd) { var range = document.createRange(); var el, sel = window.getSelection(); if (input == null) return; for (var i = 0; i < input.childNodes.length; i++) { var tmp = $(input.childNodes[i]).text(); if (input.childNodes[i].tagName) tmp = $(input.childNodes[i]).html(); if (pos <= tmp.length) { el = input.childNodes[i]; if (el.childNodes && el.childNodes.length > 0) el = el.childNodes[0]; if (el.childNodes && el.childNodes.length > 0) el = el.childNodes[0]; break; } else { pos -= tmp.length; } } if (el == null) return; if (pos > el.length) pos = el.length; range.setStart(el, pos); if (posEnd) { range.setEnd(el, posEnd); } else { range.collapse(true); } sel.removeAllRanges(); sel.addRange(range); } })(jQuery); /*********************************************************** * Formatters object * --- Primariy used in grid * *********************************************************/ w2utils.formatters = { 'number': function (value, params) { if (parseInt(params) > 20) params = 20; if (parseInt(params) < 0) params = 0; if (value == null || value == '') return ''; return w2utils.formatNumber(parseFloat(value), params, true); }, 'float': function (value, params) { return w2utils.formatters['number'](value, params); }, 'int': function (value, params) { return w2utils.formatters['number'](value, 0); }, 'money': function (value, params) { if (value == null || value == '') return ''; var data = w2utils.formatNumber(Number(value), w2utils.settings.currencyPrecision || 2); return (w2utils.settings.currencyPrefix || '') + data + (w2utils.settings.currencySuffix || ''); }, 'currency': function (value, params) { return w2utils.formatters['money'](value, params); }, 'percent': function (value, params) { if (value == null || value == '') return ''; return w2utils.formatNumber(value, params || 1) + '%'; }, 'size': function (value, params) { if (value == null || value == '') return ''; return w2utils.formatSize(parseInt(value)); }, 'date': function (value, params) { if (params == null || params == '') params = w2utils.settings.dateFormat; if (value == null || value == 0) return ''; var dt = w2utils.isDateTime(value, params, true); if (dt == '') dt = w2utils.isDate(value, params, true); return '<span title="'+ dt +'">' + w2utils.formatDate(dt, params) + '</span>'; }, 'datetime': function (value, params) { if (params == null || params == '') params = w2utils.settings.dateFormat + '|' + w2utils.settings.timeFormat; if (value == null || value == 0) return ''; var dt = w2utils.isDateTime(value, params, true); if (dt == '') dt = w2utils.isDate(value, params, true); return '<span title="'+ dt +'">' + w2utils.formatDateTime(dt, params) + '</span>'; }, 'time': function (value, params) { if (params == null || params == '') params = w2utils.settings.timeFormat; if (params == 'h12') params = 'hh:mi pm'; if (params == 'h24') params = 'h24:mi'; if (value == null || value == 0) return ''; var dt = w2utils.isDateTime(value, params, true); if (dt == '') dt = w2utils.isDate(value, params, true); return '<span title="'+ dt +'">' + w2utils.formatTime(value, params) + '</span>'; }, 'timestamp': function (value, params) { if (params == null || params == '') params = w2utils.settings.dateFormat + '|' + w2utils.settings.timeFormat; if (value == null || value == 0) return ''; var dt = w2utils.isDateTime(value, params, true); if (dt == '') dt = w2utils.isDate(value, params, true); return dt.toString ? dt.toString() : ''; }, 'gmt': function (value, params) { if (params == null || params == '') params = w2utils.settings.dateFormat + '|' + w2utils.settings.timeFormat; if (value == null || value == 0) return ''; var dt = w2utils.isDateTime(value, params, true); if (dt == '') dt = w2utils.isDate(value, params, true); return dt.toUTCString ? dt.toUTCString() : ''; }, 'age': function (value, params) { if (value == null || value == 0) return ''; var dt = w2utils.isDateTime(value, params, true); if (dt == '') dt = w2utils.isDate(value, params, true); return '<span title="'+ dt +'">' + w2utils.age(value) + ((' ' + params) || '') + '</span>'; }, 'toggle': function (value, params) { return (value ? 'Yes' : ''); } }; /*********************************************************** * Generic Event Object * --- This object is reused across all other * --- widgets in w2ui. * *********************************************************/ w2utils.event = { on: function (edata, handler) { // allow 'eventName:after' syntax if (typeof edata == 'string' && edata.indexOf(':') != -1) { var tmp = edata.split(':'); if (['complete', 'done'].indexOf(edata[1]) != -1) edata[1] = 'after'; edata = { type : tmp[0], execute : tmp[1] }; } if (!$.isPlainObject(edata)) edata = { type: edata }; edata = $.extend({ type: null, execute: 'before', target: null, onComplete: null }, edata); // errors if (!edata.type) { console.log('ERROR: You must specify event type when calling .on() method of '+ this.name); return; } if (!handler) { console.log('ERROR: You must specify event handler function when calling .on() method of '+ this.name); return; } if (!$.isArray(this.handlers)) this.handlers = []; this.handlers.push({ edata: edata, handler: handler }); }, off: function (edata, handler) { // allow 'eventName:after' syntax if (typeof edata == 'string' && edata.indexOf(':') != -1) { var tmp = edata.split(':'); if (['complete', 'done'].indexOf(edata[1]) != -1) edata[1] = 'after'; edata = { type : tmp[0], execute : tmp[1] } } if (!$.isPlainObject(edata)) edata = { type: edata }; edata = $.extend({}, { type: null, execute: 'before', target: null, onComplete: null }, edata); // errors if (!edata.type) { console.log('ERROR: You must specify event type when calling .off() method of '+ this.name); return; } if (!handler) { handler = null; } // remove handlers var newHandlers = []; for (var h = 0, len = this.handlers.length; h < len; h++) { var t = this.handlers[h]; if ((t.edata.type === edata.type || edata.type === '*') && (t.edata.target === edata.target || edata.target == null) && (t.edata.execute === edata.execute || edata.execute == null) && (t.handler === handler || handler == null)) { // match } else { newHandlers.push(t); } } this.handlers = newHandlers; }, trigger: function (edata) { var edata = $.extend({ type: null, phase: 'before', target: null, doneHandlers: [] }, edata, { isStopped : false, isCancelled : false, done : function (handler) { this.doneHandlers.push(handler); }, preventDefault : function () { this.isCancelled = true; }, stopPropagation : function () { this.isStopped = true; } }); if (edata.phase === 'before') edata.onComplete = null; var args, fun, tmp; if (edata.target == null) edata.target = null; if (!$.isArray(this.handlers)) this.handlers = []; // process events in REVERSE order for (var h = this.handlers.length-1; h >= 0; h--) { var item = this.handlers[h]; if ((item.edata.type === edata.type || item.edata.type === '*') && (item.edata.target === edata.target || item.edata.target == null) && (item.edata.execute === edata.phase || item.edata.execute === '*' || item.edata.phase === '*')) { edata = $.extend({}, item.edata, edata); // check handler arguments args = []; tmp = new RegExp(/\((.*?)\)/).exec(item.handler); if (tmp) args = tmp[1].split(/\s*,\s*/); if (args.length === 2) { item.handler.call(this, edata.target, edata); // old way for back compatibility } else { item.handler.call(this, edata); // new way } if (edata.isStopped === true || edata.stop === true) return edata; // back compatibility edata.stop === true } } // main object events var funName = 'on' + edata.type.substr(0,1).toUpperCase() + edata.type.substr(1); if (edata.phase === 'before' && typeof this[funName] === 'function') { fun = this[funName]; // check handler arguments args = []; tmp = new RegExp(/\((.*?)\)/).exec(fun); if (tmp) args = tmp[1].split(/\s*,\s*/); if (args.length === 2) { fun.call(this, edata.target, edata); // old way for back compatibility } else { fun.call(this, edata); // new way } if (edata.isStopped === true || edata.stop === true) return edata; // back compatibility edata.stop === true } // item object events if (edata.object != null && edata.phase === 'before' && typeof edata.object[funName] === 'function') { fun = edata.object[funName]; // check handler arguments args = []; tmp = new RegExp(/\((.*?)\)/).exec(fun); if (tmp) args = tmp[1].split(/\s*,\s*/); if (args.length === 2) { fun.call(this, edata.target, edata); // old way for back compatibility } else { fun.call(this, edata); // new way } if (edata.isStopped === true || edata.stop === true) return edata; } // execute onComplete if (edata.phase === 'after') { if (typeof edata.onComplete === 'function') edata.onComplete.call(this, edata); for (var i = 0; i < edata.doneHandlers.length; i++) { if (typeof edata.doneHandlers[i] == 'function') { edata.doneHandlers[i].call(this, edata); } } } return edata; } }; /*********************************************************** * Commonly used plugins * --- used primarily in grid and form * *********************************************************/ (function ($) { $.fn.w2render = function (name) { if ($(this).length > 0) { if (typeof name === 'string' && w2ui[name]) w2ui[name].render($(this)[0]); if (typeof name === 'object') name.render($(this)[0]); } }; $.fn.w2destroy = function (name) { if (!name && this.length > 0) name = this.attr('name'); if (typeof name === 'string' && w2ui[name]) w2ui[name].destroy(); if (typeof name === 'object') name.destroy(); }; $.fn.w2marker = function () { var str = Array.prototype.slice.call(arguments, 0); if (Array.isArray(str[0])) str = str[0]; if (str.length == 0 || !str[0]) { // remove marker return $(this).each(clearMarkedText); } else { // add marker return $(this).each(function (index, el) { clearMarkedText(index, el); for (var s = 0; s < str.length; s++) { var tmp = str[s]; if (typeof tmp !== 'string') tmp = String(tmp); // escape regex special chars tmp = tmp.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&").replace(/&/g, '&amp;').replace(/</g, '&gt;').replace(/>/g, '&lt;'); var regex = new RegExp(tmp + '(?!([^<]+)?>)', "gi"); // only outside tags el.innerHTML = el.innerHTML.replace(regex, replaceValue); } function replaceValue(matched) { // mark new return '<span class="w2ui-marker">' + matched + '</span>'; } }); } function clearMarkedText(index, el) { while (el.innerHTML.indexOf('<span class="w2ui-marker">') != -1) { el.innerHTML = el.innerHTML.replace(/\<span class=\"w2ui\-marker\"\>(.*)\<\/span\>/ig, '$1'); // unmark } } }; // -- w2tag - there can be multiple on screen at a time $.fn.w2tag = function (text, options) { // only one argument if (arguments.length == 1 && typeof text == 'object') { options = text; if (options.html != null) text = options.html; } // default options options = $.extend({ id : null, // id for the tag, otherwise input id is used html : text, // or html position : 'right', // can be left, right, top, bottom left : 0, // delta for left coordinate top : 0, // delta for top coordinate style : '', // adition style for the tag css : {}, // add css for input when tag is shown className : '', // add class bubble inputClass : '', // add class for input when tag is shown onShow : null, // callBack when shown onHide : null, // callBack when hidden hideOnKeyPress : true, // hide tag if key pressed hideOnBlur : false, // hide tag on blur hideOnClick : false // hide tag on document click }, options); if (options.name != null && options.id == null) options.id = options.name; // for backward compatibility if (options['class'] != '' && options.inputClass == '') options.inputClass = options['class']; // remove all tags if ($(this).length === 0) { $('.w2ui-tag').each(function (index, el) { var opt = $(el).data('options'); if (opt == null) opt = {}; $($(el).data('taged-el')).removeClass(opt.inputClass); clearInterval($(el).data('timer')); $(el).remove(); }); return; } return $(this).each(function (index, el) { // show or hide tag var origID = (options.id ? options.id : el.id); var tagID = w2utils.escapeId(origID); var $tags = $('#w2ui-tag-'+tagID); if (text === '' || text == null) { // remmove element $tags.css('opacity', 0); clearInterval($tags.data('timer')); $tags.remove(); return; } else if ($tags.length != 0) { // if already present options = $.extend($tags.data('options'), options); $tags.data('options', options); $tags.find('.w2ui-tag-body') .attr('style', options.style) .addClass(options.className) .html(options.html); } else { var originalCSS = ''; if ($(el).length > 0) originalCSS = $(el)[0].style.cssText; // insert $('body').append( '<div onclick="event.stopPropagation()" id="w2ui-tag-'+ origID +'" class="w2ui-tag '+ ($(el).parents('.w2ui-popup').length > 0 ? 'w2ui-tag-popup' : '') + '">'+ ' <div style="margin: -2px 0px 0px -2px; white-space: nowrap;">'+ ' <div class="w2ui-tag-body '+ options.className +'" style="'+ (options.style || '') +'">'+ text +'</div>'+ ' </div>' + '</div>'); $tags = $('#w2ui-tag-'+tagID); $(el).data('w2tag', $tags.get(0)); } // need time out to allow tag to be rendered setTimeout(function () { if (!$(el).offset()) return; var pos = checkIfMoved(true); if (pos == null) return; $tags.css({ opacity : '1', left : pos.left + 'px', top : pos.top + 'px' }) .data('options', options) .data('taged-el', el) .data('position', pos.left + 'x' + pos.top) .data('timer', setInterval(checkIfMoved, 100)) .find('.w2ui-tag-body').addClass(pos['posClass']); $(el).css(options.css) .off('.w2tag') .addClass(options.inputClass); if (options.hideOnKeyPress) { $(el).on('keypress.w2tag', hideTag); } if (options.hideOnBlur) { $(el).on('blur.w2tag', hideTag); } if (options.hideOnClick) { $(document).on('click.w2tag', hideTag) } if (typeof options.onShow === 'function') options.onShow(); }, 1); // bind event to hide it function hideTag() { $tags = $('#w2ui-tag-'+tagID); if ($tags.length <= 0) return; clearInterval($tags.data('timer')); $tags.remove(); $(document).off('.w2tag'); $(el).off('.w2tag', hideTag) .removeClass(options.inputClass) .removeData('w2tag'); if ($(el).length > 0) $(el)[0].style.cssText = originalCSS; if (typeof options.onHide === 'function') options.onHide(); } function checkIfMoved(skipTransition) { // monitor if destroyed var offset = $(el).offset(); if ($(el).length === 0 || (offset.left === 0 && offset.top === 0) || $tags.find('.w2ui-tag-body').length == 0) { clearInterval($tags.data('timer')); hideTag(); return; } // monitor if moved var posClass = 'w2ui-tag-right'; var posLeft = parseInt($(el).offset().left + el.offsetWidth + (options.left ? options.left : 0)); var posTop = parseInt($(el).offset().top + (options.top ? options.top : 0)); var tagBody = $tags.find('.w2ui-tag-body'); var width = tagBody[0].offsetWidth; var height = tagBody[0].offsetHeight; if (options.position == 'top') { posClass = 'w2ui-tag-top'; posLeft = parseInt($(el).offset().left + (options.left ? options.left : 0)) - 14; posTop = parseInt($(el).offset().top + (options.top ? options.top : 0)) - height - 10; } if (options.position == 'bottom') { posClass = 'w2ui-tag-bottom'; posLeft = parseInt($(el).offset().left + (options.left ? options.left : 0)) - 14; posTop = parseInt($(el).offset().top + el.offsetHeight + (options.top ? options.top : 0)) + 10; } if (options.position == 'left') { posClass = 'w2ui-tag-left'; posLeft = parseInt($(el).offset().left + (options.left ? options.left : 0)) - width - 20; posTop = parseInt($(el).offset().top + (options.top ? options.top : 0)); } if ($tags.data('position') !== posLeft + 'x' + posTop && skipTransition !== true) { $tags.css(w2utils.cssPrefix({ 'transition': '.2s' })).css({ left: posLeft + 'px', top : posTop + 'px' }).data('position', posLeft + 'x' + posTop); } return { left: posLeft, top: posTop, posClass: posClass }; } }); }; // w2overlay - appears under the element, there can be only one at a time $.fn.w2overlay = function (html, options) { var obj = this; var name = ''; var defaults = { name : null, // it not null, then allows multiple concurrent overlays html : '', // html text to display align : 'none', // can be none, left, right, both left : 0, // offset left top : 0, // offset top tipLeft : 30, // tip offset left noTip : false, // if true - no tip will be displayed selectable : false, width : 0, // fixed width height : 0, // fixed height maxWidth : null, // max width if any maxHeight : null, // max height if any contextMenu : false, // if true, it will be opened at mouse position style : '', // additional style for main div 'class' : '', // additional class name for main div overlayStyle: '', onShow : null, // event on show onHide : null, // event on hide openAbove : false, // show above control tmp : {} }; if (arguments.length == 1) { if (typeof html == 'object') { options = html; } else { options = { html: html }; } } if (arguments.length == 2) options.html = html; if (!$.isPlainObject(options)) options = {}; options = $.extend({}, defaults, options); if (options.name) name = '-' + options.name; // hide var tmp_hide; if (this.length == 0 || options.html === '' || options.html == null) { if ($('#w2ui-overlay'+ name).length > 0) { tmp_hide = $('#w2ui-overlay'+ name)[0].hide; if (typeof tmp_hide === 'function') tmp_hide(); } else { $('#w2ui-overlay'+ name).remove(); } return $(this); } // hide previous if any if ($('#w2ui-overlay'+ name).length > 0) { tmp_hide = $('#w2ui-overlay'+ name)[0].hide; $(document).off('click', tmp_hide); if (typeof tmp_hide === 'function') tmp_hide(); } if (obj.length > 0 && (obj[0].tagName == null || obj[0].tagName.toUpperCase() == 'BODY')) options.contextMenu = true; if (options.contextMenu && options.originalEvent == null) { console.log('ERROR: for context menu you need to pass options.originalEvent.'); } // append $('body').append( '<div id="w2ui-overlay'+ name +'" style="display: none; left: 0px; top: 0px; '+ options.overlayStyle +'"'+ ' class="w2ui-reset w2ui-overlay '+ ($(this).parents('.w2ui-popup, .w2ui-overlay-popup').length > 0 ? 'w2ui-overlay-popup' : '') +'">'+ ' <style></style>'+ ' <div style="min-width: 100%; '+ options.style +'" class="'+ options['class'] +'"></div>'+ '</div>' ); // init var div1 = $('#w2ui-overlay'+ name); var div2 = div1.find(' > div'); div2.html(options.html); // pick bg color of first div var bc = div2.css('background-color'); if (bc != null && bc !== 'rgba(0, 0, 0, 0)' && bc !== 'transparent') div1.css({ 'background-color': bc, 'border-color': bc }); var offset = $(obj).offset() || {}; div1.data('element', obj.length > 0 ? obj[0] : null) .data('options', options) .data('position', offset.left + 'x' + offset.top) .fadeIn('fast') .on('click', function (event) { // if there is label for input, it will produce 2 click events if (event.target.tagName.toUpperCase() == 'LABEL') event.stopPropagation(); }) .on('mousedown', function (event) { $('#w2ui-overlay'+ name).data('keepOpen', true); if (['INPUT', 'TEXTAREA', 'SELECT'].indexOf(event.target.tagName.toUpperCase()) == -1 && !options.selectable) { event.preventDefault(); } }); div1[0].hide = hide; div1[0].resize = resize; // need time to display setTimeout(function () { resize(); $(document).off('click', hide).on('click', hide); if (typeof options.onShow === 'function') options.onShow(); }, 10); monitor(); return $(this); // monitor position function monitor() { var tmp = $('#w2ui-overlay'+ name); if (tmp.data('element') !== obj[0]) return; // it if it different overlay if (tmp.length === 0) return; var offset = $(obj).offset() || {}; var pos = offset.left + 'x' + offset.top; if (tmp.data('position') !== pos) { hide(); } else { setTimeout(monitor, 250); } } // click anywhere else hides the drop down function hide(event) { if (event && event.button != 0) return; // only for left click button var div1 = $('#w2ui-overlay'+ name); if (div1.data('keepOpen') === true) { div1.removeData('keepOpen'); return; } var result; if (typeof options.onHide === 'function') result = options.onHide(); if (result === false) return; div1.remove(); $(document).off('click', hide); clearInterval(div1.data('timer')); } function resize () { var div1 = $('#w2ui-overlay'+ name); var div2 = div1.find(' > div'); // if goes over the screen, limit height and width if (div1.length > 0) { div2.height('auto').width('auto'); // width/height var overflowX = false; var overflowY = false; var h = div2.height(); var w = div2.width(); if (options.width && options.width < w) w = options.width; if (w < 30) w = 30; // if content of specific height if (options.tmp.contentHeight) { h = parseInt(options.tmp.contentHeight); div2.height(h); setTimeout(function () { var $div = div2.find('div.menu'); if (h > $div.height()) { div2.find('div.menu').css('overflow-y', 'hidden'); } }, 1); setTimeout(function () { var $div = div2.find('div.menu'); if ($div.css('overflow-y') != 'auto') $div.css('overflow-y', 'auto'); }, 10); } if (options.tmp.contentWidth) { w = parseInt(options.tmp.contentWidth); div2.width(w); setTimeout(function () { if (w > div2.find('div.menu > table').width()) { div2.find('div.menu > table').css('overflow-x', 'hidden'); } }, 1); setTimeout(function () { div2.find('div.menu > table').css('overflow-x', 'auto'); }, 10); } // adjust position var tmp = (w - 17) / 2; var boxLeft = options.left; var boxWidth = options.width; var tipLeft = options.tipLeft; // alignment switch (options.align) { case 'both': boxLeft = 17 + parseInt(options.left); if (options.width === 0) options.width = w2utils.getSize($(obj), 'width'); if (options.maxWidth && options.width > options.maxWidth) options.width = options.maxWidth; break; case 'left': boxLeft = 17 + parseInt(options.left); break; case 'right': boxLeft = w2utils.getSize($(obj), 'width') - w + 14 + parseInt(options.left); tipLeft = w - 40; break; } if (w === 30 && !boxWidth) boxWidth = 30; else boxWidth = (options.width ? options.width : 'auto'); if (tmp < 25) { boxLeft = 25 - tmp; tipLeft = Math.floor(tmp); } // Y coord var X, Y, offsetTop; if (options.contextMenu) { // context menu X = options.originalEvent.pageX + 8; Y = options.originalEvent.pageY - 0; offsetTop = options.originalEvent.pageY; } else { var offset = obj.offset() || {}; X = ((offset.left > 25 ? offset.left : 25) + boxLeft); Y = (offset.top + w2utils.getSize(obj, 'height') + options.top + 7); offsetTop = offset.top; } div1.css({ left : X + 'px', top : Y + 'px', 'min-width' : boxWidth, 'min-height': (options.height ? options.height : 'auto') }); // $(window).height() - has a problem in FF20 var offset = div2.offset() || {}; var maxHeight = window.innerHeight + $(document).scrollTop() - offset.top - 7; var maxWidth = window.innerWidth + $(document).scrollLeft() - offset.left - 7; if (options.contextMenu) { // context menu maxHeight = window.innerHeight - options.originalEvent.pageY - 15; maxWidth = window.innerWidth - options.originalEvent.pageX; } if ((maxHeight > -50 && maxHeight < 210) || options.openAbove === true) { var tipOffset; // show on top if (options.contextMenu) { // context menu maxHeight = options.originalEvent.pageY - 7; tipOffset = 5; } else { maxHeight = offset.top - $(document).scrollTop() - 7; tipOffset = 24; } if (options.maxHeight && maxHeight > options.maxHeight) maxHeight = options.maxHeight; if (h > maxHeight) { overflowY = true; div2.height(maxHeight).width(w).css({ 'overflow-y': 'auto' }); h = maxHeight; } div1.addClass('bottom-arrow'); div1.css('top', (offsetTop - h - tipOffset + options.top) + 'px'); div1.find('>style').html( '#w2ui-overlay'+ name +':before { margin-left: '+ parseInt(tipLeft) +'px; }'+ '#w2ui-overlay'+ name +':after { margin-left: '+ parseInt(tipLeft) +'px; }' ); } else { // show under if (options.maxHeight && maxHeight > options.maxHeight) maxHeight = options.maxHeight; if (h > maxHeight) { overflowY = true; div2.height(maxHeight).width(w).css({ 'overflow-y': 'auto' }); } div1.addClass('top-arrow'); div1.find('>style').html( '#w2ui-overlay'+ name +':before { margin-left: '+ parseInt(tipLeft) +'px; }'+ '#w2ui-overlay'+ name +':after { margin-left: '+ parseInt(tipLeft) +'px; }' ); } // check width w = div2.width(); maxWidth = window.innerWidth + $(document).scrollLeft() - offset.left - 7; if (options.maxWidth && maxWidth > options.maxWidth) maxWidth = options.maxWidth; if (w > maxWidth && options.align !== 'both') { options.align = 'right'; setTimeout(function () { resize(); }, 1); } // don't show tip if (options.contextMenu || options.noTip) { // context menu div1.find('>style').html( '#w2ui-overlay'+ name +':before { display: none; }'+ '#w2ui-overlay'+ name +':after { display: none; }' ); } // check scroll bar (needed to avoid horizontal scrollbar) if (overflowY && options.align != 'both') div2.width(w + w2utils.scrollBarSize() + 2); } } }; $.fn.w2menu = function (menu, options) { /* ITEM STRUCTURE item : { id : null, text : '', style : '', img : '', icon : '', count : '', hidden : false, checked : null, disabled : false ... } */ var defaults = { type : 'normal', // can be normal, radio, check index : null, // current selected items : [], render : null, msgNoItems : 'No items', onSelect : null, tmp : {} }; var obj = this; var name = ''; if (menu === 'refresh') { // if not show - call blur if ($('#w2ui-overlay'+ name).length > 0) { options = $.extend($.fn.w2menuOptions, options); var scrTop = $('#w2ui-overlay'+ name +' div.menu').scrollTop(); $('#w2ui-overlay'+ name +' div.menu').html(getMenuHTML()); $('#w2ui-overlay'+ name +' div.menu').scrollTop(scrTop); mresize(); } else { $(this).w2menu(options); } } else if (menu === 'refresh-index') { var $menu = $('#w2ui-overlay'+ name +' div.menu'); var cur = $menu.find('tr[index='+ options.index +']'); var scrTop = $menu.scrollTop(); $menu.find('tr.w2ui-selected').removeClass('w2ui-selected'); // clear all cur.addClass('w2ui-selected'); // select current // scroll into view if (cur.length > 0) { var top = cur[0].offsetTop - 5; // 5 is margin top var height = $menu.height(); $menu.scrollTop(scrTop); if (top < scrTop || top + cur.height() > scrTop + height) { $menu.animate({ 'scrollTop': top - (height - cur.height() * 2) / 2 }, 200, 'linear'); } } mresize(); } else { if (arguments.length === 1) options = menu; else options.items = menu; if (typeof options !== 'object') options = {}; options = $.extend({}, defaults, options); $.fn.w2menuOptions = options; if (options.name) name = '-' + options.name; if (typeof options.select === 'function' && typeof options.onSelect !== 'function') options.onSelect = options.select; if (typeof options.onRender === 'function' && typeof options.render !== 'function') options.render = options.onRender; // since only one overlay can exist at a time $.fn.w2menuClick = function (event, index) { if (['radio', 'check'].indexOf(options.type) != -1) { // move checkbox $(event.target).parents('tr').find('.w2ui-icon') .removeClass('w2ui-icon-empty') .addClass('w2ui-icon-check'); } if (typeof options.onSelect === 'function') { // need time so that menu first hides setTimeout(function () { options.onSelect({ index : index, item : options.items[index], originalEvent: event }); }, 10); } // do not uncomment (or enum search type is not working in grid) // setTimeout(function () { $(document).click(); }, 50); // -- hide var div = $('#w2ui-overlay'+ name); if (typeof div[0].hide === 'function') { div.removeData('keepOpen'); div[0].hide(); } }; $.fn.w2menuDown = function (event, index) { var $el = $(event.target).parents('tr'); var tmp = $el.find('.w2ui-icon'); if (tmp.hasClass('w2ui-icon-empty')) { if (options.type == 'radio') { tmp.parents('table').find('.w2ui-icon') .removeClass('w2ui-icon-check') .addClass('w2ui-icon-empty'); } tmp.removeClass('w2ui-icon-empty').addClass('w2ui-icon-check'); } else if (tmp.hasClass('w2ui-icon-check') && (options.type == 'check')) { tmp.removeClass('w2ui-icon-check').addClass('w2ui-icon-empty'); } $el.parent().find('tr').removeClass('w2ui-selected'); $el.addClass('w2ui-selected'); $.fn.w2menuTmp = $el; }; $.fn.w2menuOut = function (event, index) { var $tmp = $($.fn.w2menuTmp); if ($tmp.length > 0) { $tmp.removeClass('w2ui-selected'); $tmp.find('.w2ui-icon').removeClass('w2ui-icon-check'); delete $.fn.w2menuTmp; } }; var html = ''; if (options.search) { html += '<div style="position: absolute; top: 0px; height: 40px; left: 0px; right: 0px; border-bottom: 1px solid silver; background-color: #ECECEC; padding: 8px 5px;">'+ ' <div class="w2ui-icon icon-search" style="position: absolute; margin-top: 4px; margin-left: 6px; width: 11px; background-position: left !important;"></div>'+ ' <input id="menu-search" type="text" style="width: 100%; outline: none; padding-left: 20px;" onclick="event.stopPropagation();"/>'+ '</div>'; options.style += ';background-color: #ECECEC'; options.index = 0; for (var i = 0; i < options.items.length; i++) options.items[i].hidden = false; } html += '<div class="menu" style="position: absolute; top: '+ (options.search ? 40 : 0) + 'px; bottom: 0px; width: 100%;">' + getMenuHTML() + '</div>'; var ret = $(this).w2overlay(html, options); setTimeout(function () { $('#w2ui-overlay'+ name +' #menu-search') .on('keyup', change) .on('keydown', function (event) { // cancel tab key if (event.keyCode === 9) { event.stopPropagation(); event.preventDefault(); } }); if (options.search) { if (['text', 'password'].indexOf($(obj)[0].type) != -1 || $(obj)[0].tagName.toUpperCase() == 'TEXTAREA') return; $('#w2ui-overlay'+ name +' #menu-search').focus(); } mresize(); }, 200); mresize(); return ret; } return; function mresize() { setTimeout(function () { // show selected $('#w2ui-overlay'+ name +' tr.w2ui-selected').removeClass('w2ui-selected'); var cur = $('#w2ui-overlay'+ name +' tr[index='+ options.index +']'); var scrTop = $('#w2ui-overlay'+ name +' div.menu').scrollTop(); cur.addClass('w2ui-selected'); if (options.tmp) options.tmp.contentHeight = $('#w2ui-overlay'+ name +' table').height() + (options.search ? 50 : 10); if (options.tmp) options.tmp.contentWidth = $('#w2ui-overlay'+ name +' table').width(); if ($('#w2ui-overlay'+ name).length > 0) $('#w2ui-overlay'+ name)[0].resize(); // scroll into view if (cur.length > 0) { var top = cur[0].offsetTop - 5; // 5 is margin top var el = $('#w2ui-overlay'+ name +' div.menu'); var height = el.height(); $('#w2ui-overlay'+ name +' div.menu').scrollTop(scrTop); if (top < scrTop || top + cur.height() > scrTop + height) { $('#w2ui-overlay'+ name +' div.menu').animate({ 'scrollTop': top - (height - cur.height() * 2) / 2 }, 200, 'linear'); } } }, 1); } function change(event) { var search = this.value; var key = event.keyCode; var cancel = false; switch (key) { case 13: // enter $('#w2ui-overlay'+ name).remove(); $.fn.w2menuClick(event, options.index); break; case 9: // tab case 27: // escape $('#w2ui-overlay'+ name).remove(); $.fn.w2menuClick(event, -1); break; case 38: // up options.index = w2utils.isInt(options.index) ? parseInt(options.index) : 0; options.index--; while (options.index > 0 && options.items[options.index].hidden) options.index--; if (options.index === 0 && options.items[options.index].hidden) { while (options.items[options.index] && options.items[options.index].hidden) options.index++; } if (options.index < 0) options.index = 0; cancel = true; break; case 40: // down options.index = w2utils.isInt(options.index) ? parseInt(options.index) : 0; options.index++; while (options.index < options.items.length-1 && options.items[options.index].hidden) options.index++; if (options.index === options.items.length-1 && options.items[options.index].hidden) { while (options.items[options.index] && options.items[options.index].hidden) options.index--; } if (options.index >= options.items.length) options.index = options.items.length - 1; cancel = true; break; } // filter if (!cancel) { var shown = 0; for (var i = 0; i < options.items.length; i++) { var item = options.items[i]; var prefix = ''; var suffix = ''; if (['is', 'begins with'].indexOf(options.match) !== -1) prefix = '^'; if (['is', 'ends with'].indexOf(options.match) !== -1) suffix = '$'; try { var re = new RegExp(prefix + search + suffix, 'i'); if (re.test(item.text) || item.text === '...') item.hidden = false; else item.hidden = true; } catch (e) {} // do not show selected items if (obj.type === 'enum' && $.inArray(item.id, ids) !== -1) item.hidden = true; if (item.hidden !== true) shown++; } options.index = 0; while (options.index < options.items.length-1 && options.items[options.index].hidden) options.index++; if (shown <= 0) options.index = -1; } $(obj).w2menu('refresh', options); mresize(); } function getMenuHTML() { if (options.spinner) { return '<table class="w2ui-drop-menu"><tbody><tr><td style="padding: 5px 10px 10px 10px; text-align: center">'+ ' <div class="w2ui-spinner" style="width: 18px; height: 18px; position: relative; top: 5px;"></div> '+ ' <div style="display: inline-block; padding: 3px; color: #999;">'+ w2utils.lang('Loading...') +'</div>'+ '</td></tr></tbody></table>'; } var count = 0; var menu_html = '<table cellspacing="0" cellpadding="0" class="w2ui-drop-menu"><tbody>'; var img = null, icon = null; for (var f = 0; f < options.items.length; f++) { var mitem = options.items[f]; if (typeof mitem === 'string') { mitem = { id: mitem, text: mitem }; } else { if (mitem.text != null && mitem.id == null) mitem.id = mitem.text; if (mitem.text == null && mitem.id != null) mitem.text = mitem.id; if (mitem.caption != null) mitem.text = mitem.caption; img = mitem.img; icon = mitem.icon; if (img == null) img = null; if (icon == null) icon = null; } if (['radio', 'check'].indexOf(options.type) != -1) { if (mitem.checked === true) icon = 'w2ui-icon-check'; else icon = 'w2ui-icon-empty'; } if (mitem.hidden !== true) { var imgd = ''; var txt = mitem.text; if (typeof options.render === 'function') txt = options.render(mitem, options); if (img) imgd = '<td class="menu-icon"><div class="w2ui-tb-image w2ui-icon '+ img +'"></div></td>'; if (icon) imgd = '<td class="menu-icon" align="center"><span class="w2ui-icon '+ icon +'"></span></td>'; // render only if non-empty if (txt != null && txt !== '' && !(/^-+$/.test(txt))) { var bg = (count % 2 === 0 ? 'w2ui-item-even' : 'w2ui-item-odd'); if (options.altRows !== true) bg = ''; var colspan = 1; if (imgd == '') colspan++; if (mitem.count == null && mitem.hotkey == null) colspan++; if (mitem.tooltip == null && mitem.hint != null) mitem.tooltip = mitem.hint; // for backward compatibility menu_html += '<tr index="'+ f + '" style="'+ (mitem.style ? mitem.style : '') +'" '+ (mitem.tooltip ? 'title="'+ mitem.tooltip +'"' : '') + ' class="'+ bg +' '+ (options.index === f ? 'w2ui-selected' : '') + ' ' + (mitem.disabled === true ? 'w2ui-disabled' : '') +'"'+ ' onmousedown="if ('+ (mitem.disabled === true ? 'true' : 'false') + ') return;'+ ' $.fn.w2menuDown(event, \''+ f +'\');"'+ ' onmouseout="if ('+ (mitem.disabled === true ? 'true' : 'false') + ') return;'+ ' $.fn.w2menuOut(event, \''+ f +'\');"'+ ' onclick="event.stopPropagation(); '+ ' if ('+ (mitem.disabled === true ? 'true' : 'false') + ') return;'+ ' $.fn.w2menuClick(event, \''+ f +'\');">'+ imgd + ' <td class="menu-text" colspan="'+ colspan +'">'+ txt +'</td>'+ ' <td class="menu-count">'+ (mitem.count != null ? '<span>' + mitem.count + '</span>' : '') + (mitem.hotkey != null ? '<span class="hotkey">' + mitem.hotkey + '</span>' : '') + '</td>' + '</tr>'; count++; } else { // horizontal line menu_html += '<tr><td colspan="3" style="padding: 6px; pointer-events: none"><div style="border-top: 1px solid silver;"></div></td></tr>'; } } options.items[f] = mitem; } if (count === 0) { menu_html += '<tr><td style="padding: 13px; color: #999; text-align: center">'+ options.msgNoItems +'</div></td></tr>'; } menu_html += "</tbody></table>"; return menu_html; } }; $.fn.w2color = function (color, callBack) { var obj = this; var el = $(this)[0]; var index = [-1, -1]; if ($.fn.w2colorPalette == null) { $.fn.w2colorPalette = [ ['000000', '888888', 'BBBBBB', 'DDDDDD', 'EEEEEE', 'F7F7F7', 'FFFFFF', ''], ['FF011B', 'FF9838', 'FFFD59', '01FD55', '00FFFE', '006CE7', '9B24F4', 'FF21F5'], ['FFEAEA', 'FCEFE1', 'FCF5E1', 'EBF7E7', 'E9F3F5', 'ECF4FC', 'EAE6F4', 'F5E7ED'], ['F4CCCC', 'FCE5CD', 'FFF2CC', 'D9EAD3', 'D0E0E3', 'CFE2F3', 'D9D1E9', 'EAD1DC'], ['EA9899', 'F9CB9C', 'FEE599', 'B6D7A8', 'A2C4C9', '9FC5E8', 'B4A7D6', 'D5A6BD'], ['E06666', 'F6B26B', 'FED966', '93C47D', '76A5AF', '6FA8DC', '8E7CC3', 'C27BA0'], ['CC0814', 'E69138', 'F1C232', '6AA84F', '45818E', '3D85C6', '674EA7', 'A54D79'], ['99050C', 'B45F17', 'BF901F', '37761D', '124F5C', '0A5394', '351C75', '741B47'], // ['660205', '783F0B', '7F6011', '274E12', '0C343D', '063762', '20124D', '4C1030'], ['F2F2F2', 'F2F2F2', 'F2F2F2', 'F2F2F2', 'F2F2F2'] // custom colors (up to 4) ]; } var pal = $.fn.w2colorPalette; if (typeof color != 'string') color = ''; if (color) color = String(color).toUpperCase(); if ($('#w2ui-overlay').length == 0) { $(el).w2overlay(getColorHTML(color), { onHide: function () { if (typeof callBack == 'function') callBack($(el).data('_color')); $(el).removeData('_color'); } }); } else { // only refresh contents $('#w2ui-overlay .w2ui-color').parent().html(getColorHTML(color)); } // bind events $('#w2ui-overlay .color') .on('mousedown', function (event) { var color = $(event.originalEvent.target).attr('name'); index = $(event.originalEvent.target).attr('index').split(':'); $(el).data('_color', color); }) .on('mouseup', function () { setTimeout(function () { if ($("#w2ui-overlay").length > 0) $('#w2ui-overlay').removeData('keepOpen')[0].hide(); }, 10); }); $('#w2ui-overlay input') .on('mousedown', function (event) { $('#w2ui-overlay').data('keepOpen', true); setTimeout(function () { $('#w2ui-overlay').data('keepOpen', true); }, 10); event.stopPropagation(); }) .on('keyup', function (event) { if (this.value != '' && this.value[0] != '#') this.value = '#' + this.value; }) .on('change', function (event) { var tmp = this.value; if (tmp.substr(0, 1) == '#') tmp = tmp.substr(1); if (tmp.length != 6) { $(this).w2tag('Invalid color.'); return; } $.fn.w2colorPalette[pal.length - 1].unshift(tmp.toUpperCase()); $(el).w2color(color, callBack); setTimeout(function() { $('#w2ui-overlay input')[0].focus(); }, 100); }) .w2field('hex'); el.nav = function (direction) { switch (direction) { case 'up': index[0]--; break; case 'down': index[0]++; break; case 'right': index[1]++; break; case 'left': index[1]--; break; } if (index[0] < 0) index[0] = 0; if (index[0] > pal.length - 2) index[0] = pal.length - 2; if (index[1] < 0) index[1] = 0; if (index[1] > pal[0].length - 1) index[1] = pal[0].length - 1; color = pal[index[0]][index[1]]; $(el).data('_color', color); return color; }; function getColorHTML(color) { var html = '<div class="w2ui-color">'+ '<table cellspacing="5"><tbody>'; for (var i = 0; i < pal.length - 1; i++) { html += '<tr>'; for (var j = 0; j < pal[i].length; j++) { html += '<td>'+ ' <div class="color '+ (pal[i][j] == '' ? 'no-color' : '') +'" style="background-color: #'+ pal[i][j] +';" ' + ' name="'+ pal[i][j] +'" index="'+ i + ':' + j +'">'+ (color == pal[i][j] ? '&#149;' : '&#160;') + ' </div>'+ '</td>'; if (color == pal[i][j]) index = [i, j]; } html += '</tr>'; if (i < 2) html += '<tr><td style="height: 8px" colspan="8"></td></tr>'; } var tmp = pal[pal.length - 1]; html += '<tr><td style="height: 8px" colspan="8"></td></tr>'+ '<tr>'+ ' <td colspan="4" style="text-align: left"><input placeholder="#FFF000" style="margin-left: 1px; width: 74px" maxlength="7"/></td>'+ ' <td><div class="color" style="background-color: #'+ tmp[0] +';" name="'+ tmp[0] +'" index="8:0">'+ (color == tmp[0] ? '&#149;' : '&#160;') +'</div></td>'+ ' <td><div class="color" style="background-color: #'+ tmp[1] +';" name="'+ tmp[1] +'" index="8:0">'+ (color == tmp[1] ? '&#149;' : '&#160;') +'</div></td>'+ ' <td><div class="color" style="background-color: #'+ tmp[2] +';" name="'+ tmp[2] +'" index="8:0">'+ (color == tmp[2] ? '&#149;' : '&#160;') +'</div></td>'+ ' <td><div class="color" style="background-color: #'+ tmp[3] +';" name="'+ tmp[3] +'" index="8:0">'+ (color == tmp[3] ? '&#149;' : '&#160;') +'</div></td>'+ '</tr>'+ '<tr><td style="height: 4px" colspan="8"></td></tr>'; html += '</tbody></table></div>'; return html; } }; })(jQuery);
Fixed formatNumber
src/w2utils.js
Fixed formatNumber
<ide><path>rc/w2utils.js <ide> } <ide> <ide> function formatNumber (val, fraction, useGrouping) { <del> return parseFloat(val).toLocaleString(w2utils.settings.locale, { <add> var options = { <ide> minimumFractionDigits : fraction, <del> maximumFractionDigits : 20, <add> maximumFractionDigits : fraction, <ide> useGrouping : useGrouping <del> }); <add> }; <add> if (fraction == null || fraction < 0) { <add> options.minimumFractionDigits = 0; <add> options.maximumFractionDigits = 20; <add> } <add> return parseFloat(val).toLocaleString(w2utils.settings.locale, options); <ide> } <ide> <ide> function formatDate (dateStr, format) { // IMPORTANT dateStr HAS TO BE valid JavaScript Date String <ide> $lock.show(); <ide> mess.html(options.msg).show(0); <ide> } <del> // hide all tags (do not hide overlays as the form can be in overlay) <del> $().w2tag(); <ide> } <ide> <ide> function unlock (box, speed) { <ide> .data('options', options) <ide> .data('taged-el', el) <ide> .data('position', pos.left + 'x' + pos.top) <del> .data('timer', setInterval(checkIfMoved, 100)) <add> .data('timer', setTimeout(checkIfMoved, 100)) <ide> .find('.w2ui-tag-body').addClass(pos['posClass']); <ide> <ide> $(el).css(options.css) <ide> hideTag(); <ide> return; <ide> } <add> setTimeout(checkIfMoved, 100); <ide> // monitor if moved <ide> var posClass = 'w2ui-tag-right'; <ide> var posLeft = parseInt($(el).offset().left + el.offsetWidth + (options.left ? options.left : 0));
Java
mit
2ed28b3e29a5c9431e1ec72d1a664d096536dc77
0
sake/bouncycastle-java
package org.bouncycastle.cms; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Null; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.DEREncodable; import org.bouncycastle.asn1.DERNull; import org.bouncycastle.asn1.DERObject; import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.DERSet; import org.bouncycastle.asn1.DERTags; import org.bouncycastle.asn1.cms.Attribute; import org.bouncycastle.asn1.cms.AttributeTable; import org.bouncycastle.asn1.cms.CMSAttributes; import org.bouncycastle.asn1.cms.IssuerAndSerialNumber; import org.bouncycastle.asn1.cms.SignerIdentifier; import org.bouncycastle.asn1.cms.SignerInfo; import org.bouncycastle.asn1.cms.Time; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.DigestInfo; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.security.Provider; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import javax.crypto.Cipher; /** * an expanded SignerInfo block from a CMS Signed message */ public class SignerInformation { private SignerId sid; private SignerInfo info; private AlgorithmIdentifier digestAlgorithm; private AlgorithmIdentifier encryptionAlgorithm; private ASN1Set signedAttributes; private ASN1Set unsignedAttributes; private CMSProcessable content; private byte[] signature; private DERObjectIdentifier contentType; private DigestCalculator digestCalculator; private byte[] resultDigest; SignerInformation( SignerInfo info, DERObjectIdentifier contentType, CMSProcessable content, DigestCalculator digestCalculator) { this.info = info; this.sid = new SignerId(); this.contentType = contentType; try { SignerIdentifier s = info.getSID(); if (s.isTagged()) { ASN1OctetString octs = ASN1OctetString.getInstance(s.getId()); sid.setSubjectKeyIdentifier(octs.getEncoded()); } else { IssuerAndSerialNumber iAnds = IssuerAndSerialNumber.getInstance(s.getId()); sid.setIssuer(iAnds.getName().getEncoded()); sid.setSerialNumber(iAnds.getSerialNumber().getValue()); } } catch (IOException e) { throw new IllegalArgumentException("invalid sid in SignerInfo"); } this.digestAlgorithm = info.getDigestAlgorithm(); this.signedAttributes = info.getAuthenticatedAttributes(); this.unsignedAttributes = info.getUnauthenticatedAttributes(); this.encryptionAlgorithm = info.getDigestEncryptionAlgorithm(); this.signature = info.getEncryptedDigest().getOctets(); this.content = content; this.digestCalculator = digestCalculator; } private byte[] encodeObj( DEREncodable obj) throws IOException { if (obj != null) { return obj.getDERObject().getEncoded(); } return null; } public SignerId getSID() { return sid; } /** * return the version number for this objects underlying SignerInfo structure. */ public int getVersion() { return info.getVersion().getValue().intValue(); } public AlgorithmIdentifier getDigestAlgorithmID() { return digestAlgorithm; } /** * return the object identifier for the signature. */ public String getDigestAlgOID() { return digestAlgorithm.getObjectId().getId(); } /** * return the signature parameters, or null if there aren't any. */ public byte[] getDigestAlgParams() { try { return encodeObj(digestAlgorithm.getParameters()); } catch (Exception e) { throw new RuntimeException("exception getting digest parameters " + e); } } /** * return the content digest that was calculated during verification. */ public byte[] getContentDigest() { if (resultDigest == null) { throw new IllegalStateException("method can only be called after verify."); } return (byte[])resultDigest.clone(); } /** * return the object identifier for the signature. */ public String getEncryptionAlgOID() { return encryptionAlgorithm.getObjectId().getId(); } /** * return the signature/encryption algorithm parameters, or null if * there aren't any. */ public byte[] getEncryptionAlgParams() { try { return encodeObj(encryptionAlgorithm.getParameters()); } catch (Exception e) { throw new RuntimeException("exception getting encryption parameters " + e); } } /** * return a table of the signed attributes - indexed by * the OID of the attribute. */ public AttributeTable getSignedAttributes() { if (signedAttributes == null) { return null; } return new AttributeTable(signedAttributes); } /** * return a table of the unsigned attributes indexed by * the OID of the attribute. */ public AttributeTable getUnsignedAttributes() { if (unsignedAttributes == null) { return null; } return new AttributeTable(unsignedAttributes); } /** * return the encoded signature */ public byte[] getSignature() { return (byte[])signature.clone(); } /** * Return a SignerInformationStore containing the counter signatures attached to this * signer. If no counter signatures are present an empty store is returned. */ public SignerInformationStore getCounterSignatures() { // TODO There are several checks implied by the RFC3852 comments that are missing /* The countersignature attribute MUST be an unsigned attribute; it MUST NOT be a signed attribute, an authenticated attribute, an unauthenticated attribute, or an unprotected attribute. */ AttributeTable unsignedAttributeTable = getUnsignedAttributes(); if (unsignedAttributeTable == null) { return new SignerInformationStore(new ArrayList(0)); } List counterSignatures = new ArrayList(); /* The UnsignedAttributes syntax is defined as a SET OF Attributes. The UnsignedAttributes in a signerInfo may include multiple instances of the countersignature attribute. */ ASN1EncodableVector allCSAttrs = unsignedAttributeTable.getAll(CMSAttributes.counterSignature); for (int i = 0; i < allCSAttrs.size(); ++i) { Attribute counterSignatureAttribute = (Attribute)allCSAttrs.get(i); /* A countersignature attribute can have multiple attribute values. The syntax is defined as a SET OF AttributeValue, and there MUST be one or more instances of AttributeValue present. */ ASN1Set values = counterSignatureAttribute.getAttrValues(); if (values.size() < 1) { // TODO Throw an appropriate exception? } for (Enumeration en = values.getObjects(); en.hasMoreElements();) { /* Countersignature values have the same meaning as SignerInfo values for ordinary signatures, except that: 1. The signedAttributes field MUST NOT contain a content-type attribute; there is no content type for countersignatures. 2. The signedAttributes field MUST contain a message-digest attribute if it contains any other attributes. 3. The input to the message-digesting process is the contents octets of the DER encoding of the signatureValue field of the SignerInfo value with which the attribute is associated. */ SignerInfo si = SignerInfo.getInstance(en.nextElement()); String digestName = CMSSignedHelper.INSTANCE.getDigestAlgName(si.getDigestAlgorithm().getObjectId().getId()); counterSignatures.add(new SignerInformation(si, CMSAttributes.counterSignature, null, new CounterSignatureDigestCalculator(digestName, null, getSignature()))); } } return new SignerInformationStore(counterSignatures); } /** * return the DER encoding of the signed attributes. * @throws IOException if an encoding error occurs. */ public byte[] getEncodedSignedAttributes() throws IOException { if (signedAttributes != null) { return signedAttributes.getEncoded(ASN1Encodable.DER); } return null; } private boolean doVerify( PublicKey key, Provider sigProvider) throws CMSException, NoSuchAlgorithmException { String digestName = CMSSignedHelper.INSTANCE.getDigestAlgName(this.getDigestAlgOID()); String signatureName = digestName + "with" + CMSSignedHelper.INSTANCE.getEncryptionAlgName(this.getEncryptionAlgOID()); Signature sig = CMSSignedHelper.INSTANCE.getSignatureInstance(signatureName, sigProvider); MessageDigest digest = CMSSignedHelper.INSTANCE.getDigestInstance(digestName, sigProvider); // TODO [BJA-109] Note: PSSParameterSpec requires JDK1.4+ /* try { DERObjectIdentifier sigAlgOID = encryptionAlgorithm.getObjectId(); DEREncodable sigParams = this.encryptionAlgorithm.getParameters(); if (sigAlgOID.equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) { // RFC 4056 // When the id-RSASSA-PSS algorithm identifier is used for a signature, // the AlgorithmIdentifier parameters field MUST contain RSASSA-PSS-params. if (sigParams == null) { throw new CMSException( "RSASSA-PSS signature must specify algorithm parameters"); } AlgorithmParameters params = AlgorithmParameters.getInstance( sigAlgOID.getId(), sig.getProvider().getName()); params.init(sigParams.getDERObject().getEncoded(), "ASN.1"); PSSParameterSpec spec = (PSSParameterSpec)params.getParameterSpec(PSSParameterSpec.class); sig.setParameter(spec); } else { // TODO Are there other signature algorithms that provide parameters? if (sigParams != null) { throw new CMSException("unrecognised signature parameters provided"); } } } catch (IOException e) { throw new CMSException("error encoding signature parameters.", e); } catch (InvalidAlgorithmParameterException e) { throw new CMSException("error setting signature parameters.", e); } catch (InvalidParameterSpecException e) { throw new CMSException("error processing signature parameters.", e); } */ try { sig.initVerify(key); if (signedAttributes == null) { if (content != null) { content.write( new CMSSignedDataGenerator.SigOutputStream(sig)); content.write( new CMSSignedDataGenerator.DigOutputStream(digest)); resultDigest = digest.digest(); } else { if (digestCalculator == null) { throw new CMSException("data not encapsulated in signature - use detached constructor."); } resultDigest = digestCalculator.getDigest(); // need to decrypt signature and check message bytes return verifyDigest(resultDigest, key, this.getSignature(), sigProvider); } } else { byte[] hash; if (content != null) { content.write( new CMSSignedDataGenerator.DigOutputStream(digest)); hash = digest.digest(); } else if (digestCalculator != null) { hash = digestCalculator.getDigest(); } else { hash = null; } resultDigest = hash; // TODO RFC 3852 11.4 Validate countersignature attribute // TODO Shouldn't be using attribute OID as contentType (should be null) boolean isCounterSignature = contentType.equals( CMSAttributes.counterSignature); AttributeTable signedAttrTable = this.getSignedAttributes(); // Check the content-type attribute is correct DERObject validContentType = getSingleValuedSignedAttribute( CMSAttributes.contentType, "content-type"); if (validContentType == null) { if (!isCounterSignature && signedAttrTable != null) { throw new CMSException("The content-type attribute type MUST be present whenever signed attributes are present in signed-data"); } } else { if (isCounterSignature) { throw new CMSException("[For counter signatures,] the signedAttributes field MUST NOT contain a content-type attribute"); } DERObjectIdentifier typeOID = (DERObjectIdentifier)validContentType; if (!typeOID.equals(contentType)) { throw new SignatureException("contentType in signed attributes different"); } } // Check the message-digest attribute is correct Attribute dig = signedAttrTable.get(CMSAttributes.messageDigest); if (dig == null) { throw new SignatureException("no hash for content found in signed attributes"); } DERObject hashObj = dig.getAttrValues().getObjectAt(0).getDERObject(); if (hashObj instanceof ASN1OctetString) { byte[] signedHash = ((ASN1OctetString)hashObj).getOctets(); if (!MessageDigest.isEqual(hash, signedHash)) { throw new SignatureException("content hash found in signed attributes different"); } } else if (hashObj instanceof DERNull) { if (hash != null) { throw new SignatureException("NULL hash found in signed attributes when one expected"); } } sig.update(this.getEncodedSignedAttributes()); } return sig.verify(this.getSignature()); } catch (InvalidKeyException e) { throw new CMSException( "key not appropriate to signature in message.", e); } catch (IOException e) { throw new CMSException( "can't process mime object to create signature.", e); } catch (SignatureException e) { throw new CMSException( "invalid signature format in message: " + e.getMessage(), e); } } private boolean isNull( DEREncodable o) { return (o instanceof ASN1Null) || (o == null); } private DigestInfo derDecode( byte[] encoding) throws IOException, CMSException { if (encoding[0] != (DERTags.CONSTRUCTED | DERTags.SEQUENCE)) { throw new IOException("not a digest info object"); } ASN1InputStream aIn = new ASN1InputStream(encoding); DigestInfo digInfo = new DigestInfo((ASN1Sequence)aIn.readObject()); // length check to avoid Bleichenbacher vulnerability if (digInfo.getEncoded().length != encoding.length) { throw new CMSException("malformed RSA signature"); } return digInfo; } private boolean verifyDigest( byte[] digest, PublicKey key, byte[] signature, Provider sigProvider) throws NoSuchAlgorithmException, CMSException { String algorithm = CMSSignedHelper.INSTANCE.getEncryptionAlgName(this.getEncryptionAlgOID()); try { if (algorithm.equals("RSA")) { Cipher c; if (sigProvider != null) { c = Cipher.getInstance("RSA/ECB/PKCS1Padding", sigProvider); } else { c = Cipher.getInstance("RSA/ECB/PKCS1Padding"); } c.init(Cipher.DECRYPT_MODE, key); DigestInfo digInfo = derDecode(c.doFinal(signature)); if (!digInfo.getAlgorithmId().getObjectId().equals(digestAlgorithm.getObjectId())) { return false; } if (!isNull(digInfo.getAlgorithmId().getParameters())) { return false; } byte[] sigHash = digInfo.getDigest(); return MessageDigest.isEqual(digest, sigHash); } else if (algorithm.equals("DSA")) { Signature sig; if (sigProvider != null) { sig = Signature.getInstance("NONEwithDSA", sigProvider); } else { sig = Signature.getInstance("NONEwithDSA"); } sig.initVerify(key); sig.update(digest); return sig.verify(signature); } else { throw new CMSException("algorithm: " + algorithm + " not supported in base signatures."); } } catch (GeneralSecurityException e) { throw new CMSException("Exception processing signature: " + e, e); } catch (IOException e) { throw new CMSException("Exception decoding signature: " + e, e); } } /** * verify that the given public key succesfully handles and confirms the * signature associated with this signer. */ public boolean verify( PublicKey key, String sigProvider) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException { return doVerify(key, CMSUtils.getProvider(sigProvider)); } /** * verify that the given public key succesfully handles and confirms the * signature associated with this signer. */ public boolean verify( PublicKey key, Provider sigProvider) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException { return doVerify(key, sigProvider); } /** * verify that the given certificate successfully handles and confirms * the signature associated with this signer and, if a signingTime * attribute is available, that the certificate was valid at the time the * signature was generated. */ public boolean verify( X509Certificate cert, String sigProvider) throws NoSuchAlgorithmException, NoSuchProviderException, CertificateExpiredException, CertificateNotYetValidException, CMSException { return verify(cert, CMSUtils.getProvider(sigProvider)); } /** * verify that the given certificate successfully handles and confirms * the signature associated with this signer and, if a signingTime * attribute is available, that the certificate was valid at the time the * signature was generated. */ public boolean verify( X509Certificate cert, Provider sigProvider) throws NoSuchAlgorithmException, CertificateExpiredException, CertificateNotYetValidException, CMSException { DERObject validSigningTime = getSingleValuedSignedAttribute( CMSAttributes.signingTime, "signing-time"); if (validSigningTime != null) { Time time = Time.getInstance(validSigningTime); cert.checkValidity(time.getDate()); } return doVerify(cert.getPublicKey(), sigProvider); } /** * Return the base ASN.1 CMS structure that this object contains. * * @return an object containing a CMS SignerInfo structure. */ public SignerInfo toSignerInfo() { return info; } private DERObject getSingleValuedSignedAttribute( DERObjectIdentifier attrOID, String printableName) throws CMSException { AttributeTable unsignedAttrTable = this.getUnsignedAttributes(); if (unsignedAttrTable != null && unsignedAttrTable.getAll(attrOID).size() > 0) { throw new CMSException("The " + printableName + " attribute MUST NOT be an unsigned attribute"); } AttributeTable signedAttrTable = this.getSignedAttributes(); if (signedAttrTable == null) { return null; } ASN1EncodableVector v = signedAttrTable.getAll(attrOID); switch (v.size()) { case 0: return null; case 1: { Attribute t = (Attribute)v.get(0); // assert t != null; ASN1Set attrValues = t.getAttrValues(); if (attrValues.size() != 1) { throw new CMSException("A " + printableName + " attribute MUST have a single attribute value"); } return attrValues.getObjectAt(0).getDERObject(); } default: throw new CMSException("The SignedAttributes in a signerInfo MUST NOT include multiple instances of the " + printableName + " attribute"); } } /** * Return a signer information object with the passed in unsigned * attributes replacing the ones that are current associated with * the object passed in. * * @param signerInformation the signerInfo to be used as the basis. * @param unsignedAttributes the unsigned attributes to add. * @return a copy of the original SignerInformationObject with the changed attributes. */ public static SignerInformation replaceUnsignedAttributes( SignerInformation signerInformation, AttributeTable unsignedAttributes) { SignerInfo sInfo = signerInformation.info; ASN1Set unsignedAttr = null; if (unsignedAttributes != null) { unsignedAttr = new DERSet(unsignedAttributes.toASN1EncodableVector()); } return new SignerInformation( new SignerInfo(sInfo.getSID(), sInfo.getDigestAlgorithm(), sInfo.getAuthenticatedAttributes(), sInfo.getDigestEncryptionAlgorithm(), sInfo.getEncryptedDigest(), unsignedAttr), signerInformation.contentType, signerInformation.content, null); } /** * Return a signer information object with passed in SignerInformationStore representing counter * signatures attached as an unsigned attribute. * * @param signerInformation the signerInfo to be used as the basis. * @param counterSigners signer info objects carrying counter signature. * @return a copy of the original SignerInformationObject with the changed attributes. */ public static SignerInformation addCounterSigners( SignerInformation signerInformation, SignerInformationStore counterSigners) { // TODO Perform checks from RFC 3852 11.4 SignerInfo sInfo = signerInformation.info; AttributeTable unsignedAttr = signerInformation.getUnsignedAttributes(); ASN1EncodableVector v; if (unsignedAttr != null) { v = unsignedAttr.toASN1EncodableVector(); } else { v = new ASN1EncodableVector(); } ASN1EncodableVector sigs = new ASN1EncodableVector(); for (Iterator it = counterSigners.getSigners().iterator(); it.hasNext();) { sigs.add(((SignerInformation)it.next()).toSignerInfo()); } v.add(new Attribute(CMSAttributes.counterSignature, new DERSet(sigs))); return new SignerInformation( new SignerInfo(sInfo.getSID(), sInfo.getDigestAlgorithm(), sInfo.getAuthenticatedAttributes(), sInfo.getDigestEncryptionAlgorithm(), sInfo.getEncryptedDigest(), new DERSet(v)), signerInformation.contentType, signerInformation.content, null); } }
src/org/bouncycastle/cms/SignerInformation.java
package org.bouncycastle.cms; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Null; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.DEREncodable; import org.bouncycastle.asn1.DERNull; import org.bouncycastle.asn1.DERObject; import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.DERSet; import org.bouncycastle.asn1.DERTags; import org.bouncycastle.asn1.cms.Attribute; import org.bouncycastle.asn1.cms.AttributeTable; import org.bouncycastle.asn1.cms.CMSAttributes; import org.bouncycastle.asn1.cms.IssuerAndSerialNumber; import org.bouncycastle.asn1.cms.SignerIdentifier; import org.bouncycastle.asn1.cms.SignerInfo; import org.bouncycastle.asn1.cms.Time; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.DigestInfo; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.security.Provider; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import javax.crypto.Cipher; /** * an expanded SignerInfo block from a CMS Signed message */ public class SignerInformation { private SignerId sid; private SignerInfo info; private AlgorithmIdentifier digestAlgorithm; private AlgorithmIdentifier encryptionAlgorithm; private ASN1Set signedAttributes; private ASN1Set unsignedAttributes; private CMSProcessable content; private byte[] signature; private DERObjectIdentifier contentType; private DigestCalculator digestCalculator; private byte[] resultDigest; SignerInformation( SignerInfo info, DERObjectIdentifier contentType, CMSProcessable content, DigestCalculator digestCalculator) { this.info = info; this.sid = new SignerId(); this.contentType = contentType; try { SignerIdentifier s = info.getSID(); if (s.isTagged()) { ASN1OctetString octs = ASN1OctetString.getInstance(s.getId()); sid.setSubjectKeyIdentifier(octs.getEncoded()); } else { IssuerAndSerialNumber iAnds = IssuerAndSerialNumber.getInstance(s.getId()); sid.setIssuer(iAnds.getName().getEncoded()); sid.setSerialNumber(iAnds.getSerialNumber().getValue()); } } catch (IOException e) { throw new IllegalArgumentException("invalid sid in SignerInfo"); } this.digestAlgorithm = info.getDigestAlgorithm(); this.signedAttributes = info.getAuthenticatedAttributes(); this.unsignedAttributes = info.getUnauthenticatedAttributes(); this.encryptionAlgorithm = info.getDigestEncryptionAlgorithm(); this.signature = info.getEncryptedDigest().getOctets(); this.content = content; this.digestCalculator = digestCalculator; } private byte[] encodeObj( DEREncodable obj) throws IOException { if (obj != null) { return obj.getDERObject().getEncoded(); } return null; } public SignerId getSID() { return sid; } /** * return the version number for this objects underlying SignerInfo structure. */ public int getVersion() { return info.getVersion().getValue().intValue(); } public AlgorithmIdentifier getDigestAlgorithmID() { return digestAlgorithm; } /** * return the object identifier for the signature. */ public String getDigestAlgOID() { return digestAlgorithm.getObjectId().getId(); } /** * return the signature parameters, or null if there aren't any. */ public byte[] getDigestAlgParams() { try { return encodeObj(digestAlgorithm.getParameters()); } catch (Exception e) { throw new RuntimeException("exception getting digest parameters " + e); } } /** * return the content digest that was calculated during verification. */ public byte[] getContentDigest() { if (resultDigest == null) { throw new IllegalStateException("method can only be called after verify."); } return (byte[])resultDigest.clone(); } /** * return the object identifier for the signature. */ public String getEncryptionAlgOID() { return encryptionAlgorithm.getObjectId().getId(); } /** * return the signature/encryption algorithm parameters, or null if * there aren't any. */ public byte[] getEncryptionAlgParams() { try { return encodeObj(encryptionAlgorithm.getParameters()); } catch (Exception e) { throw new RuntimeException("exception getting encryption parameters " + e); } } /** * return a table of the signed attributes - indexed by * the OID of the attribute. */ public AttributeTable getSignedAttributes() { if (signedAttributes == null) { return null; } return new AttributeTable(signedAttributes); } /** * return a table of the unsigned attributes indexed by * the OID of the attribute. */ public AttributeTable getUnsignedAttributes() { if (unsignedAttributes == null) { return null; } return new AttributeTable(unsignedAttributes); } /** * return the encoded signature */ public byte[] getSignature() { return (byte[])signature.clone(); } /** * Return a SignerInformationStore containing the counter signatures attached to this * signer. If no counter signatures are present an empty store is returned. */ public SignerInformationStore getCounterSignatures() { // TODO There are several checks implied by the RFC3852 comments that are missing /* The countersignature attribute MUST be an unsigned attribute; it MUST NOT be a signed attribute, an authenticated attribute, an unauthenticated attribute, or an unprotected attribute. */ AttributeTable unsignedAttributeTable = getUnsignedAttributes(); if (unsignedAttributeTable == null) { return new SignerInformationStore(new ArrayList(0)); } List counterSignatures = new ArrayList(); /* The UnsignedAttributes syntax is defined as a SET OF Attributes. The UnsignedAttributes in a signerInfo may include multiple instances of the countersignature attribute. */ ASN1EncodableVector allCSAttrs = unsignedAttributeTable.getAll(CMSAttributes.counterSignature); for (int i = 0; i < allCSAttrs.size(); ++i) { Attribute counterSignatureAttribute = (Attribute)allCSAttrs.get(i); /* A countersignature attribute can have multiple attribute values. The syntax is defined as a SET OF AttributeValue, and there MUST be one or more instances of AttributeValue present. */ ASN1Set values = counterSignatureAttribute.getAttrValues(); if (values.size() < 1) { // TODO Throw an appropriate exception? } for (Enumeration en = values.getObjects(); en.hasMoreElements();) { /* Countersignature values have the same meaning as SignerInfo values for ordinary signatures, except that: 1. The signedAttributes field MUST NOT contain a content-type attribute; there is no content type for countersignatures. 2. The signedAttributes field MUST contain a message-digest attribute if it contains any other attributes. 3. The input to the message-digesting process is the contents octets of the DER encoding of the signatureValue field of the SignerInfo value with which the attribute is associated. */ SignerInfo si = SignerInfo.getInstance(en.nextElement()); String digestName = CMSSignedHelper.INSTANCE.getDigestAlgName(si.getDigestAlgorithm().getObjectId().getId()); counterSignatures.add(new SignerInformation(si, CMSAttributes.counterSignature, null, new CounterSignatureDigestCalculator(digestName, null, getSignature()))); } } return new SignerInformationStore(counterSignatures); } /** * return the DER encoding of the signed attributes. * @throws IOException if an encoding error occurs. */ public byte[] getEncodedSignedAttributes() throws IOException { if (signedAttributes != null) { return signedAttributes.getEncoded(ASN1Encodable.DER); } return null; } private boolean doVerify( PublicKey key, AttributeTable signedAttrTable, Provider sigProvider) throws CMSException, NoSuchAlgorithmException { String digestName = CMSSignedHelper.INSTANCE.getDigestAlgName(this.getDigestAlgOID()); String signatureName = digestName + "with" + CMSSignedHelper.INSTANCE.getEncryptionAlgName(this.getEncryptionAlgOID()); Signature sig = CMSSignedHelper.INSTANCE.getSignatureInstance(signatureName, sigProvider); MessageDigest digest = CMSSignedHelper.INSTANCE.getDigestInstance(digestName, sigProvider); // TODO [BJA-109] Note: PSSParameterSpec requires JDK1.4+ /* try { DERObjectIdentifier sigAlgOID = encryptionAlgorithm.getObjectId(); DEREncodable sigParams = this.encryptionAlgorithm.getParameters(); if (sigAlgOID.equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) { // RFC 4056 // When the id-RSASSA-PSS algorithm identifier is used for a signature, // the AlgorithmIdentifier parameters field MUST contain RSASSA-PSS-params. if (sigParams == null) { throw new CMSException( "RSASSA-PSS signature must specify algorithm parameters"); } AlgorithmParameters params = AlgorithmParameters.getInstance( sigAlgOID.getId(), sig.getProvider().getName()); params.init(sigParams.getDERObject().getEncoded(), "ASN.1"); PSSParameterSpec spec = (PSSParameterSpec)params.getParameterSpec(PSSParameterSpec.class); sig.setParameter(spec); } else { // TODO Are there other signature algorithms that provide parameters? if (sigParams != null) { throw new CMSException("unrecognised signature parameters provided"); } } } catch (IOException e) { throw new CMSException("error encoding signature parameters.", e); } catch (InvalidAlgorithmParameterException e) { throw new CMSException("error setting signature parameters.", e); } catch (InvalidParameterSpecException e) { throw new CMSException("error processing signature parameters.", e); } */ try { sig.initVerify(key); if (signedAttributes == null) { if (content != null) { content.write( new CMSSignedDataGenerator.SigOutputStream(sig)); content.write( new CMSSignedDataGenerator.DigOutputStream(digest)); resultDigest = digest.digest(); } else { if (digestCalculator == null) { throw new CMSException("data not encapsulated in signature - use detached constructor."); } resultDigest = digestCalculator.getDigest(); // need to decrypt signature and check message bytes return verifyDigest(resultDigest, key, this.getSignature(), sigProvider); } } else { byte[] hash; if (content != null) { content.write( new CMSSignedDataGenerator.DigOutputStream(digest)); hash = digest.digest(); } else if (digestCalculator != null) { hash = digestCalculator.getDigest(); } else { hash = null; } resultDigest = hash; Attribute dig = signedAttrTable.get( CMSAttributes.messageDigest); Attribute type = signedAttrTable.get( CMSAttributes.contentType); if (dig == null) { throw new SignatureException("no hash for content found in signed attributes"); } if (type == null && !contentType.equals(CMSAttributes.counterSignature)) { throw new SignatureException("no content type id found in signed attributes"); } DERObject hashObj = dig.getAttrValues().getObjectAt(0).getDERObject(); if (hashObj instanceof ASN1OctetString) { byte[] signedHash = ((ASN1OctetString)hashObj).getOctets(); if (!MessageDigest.isEqual(hash, signedHash)) { throw new SignatureException("content hash found in signed attributes different"); } } else if (hashObj instanceof DERNull) { if (hash != null) { throw new SignatureException("NULL hash found in signed attributes when one expected"); } } if (type != null) { DERObjectIdentifier typeOID = (DERObjectIdentifier)type.getAttrValues().getObjectAt(0); if (!typeOID.equals(contentType)) { throw new SignatureException("contentType in signed attributes different"); } } sig.update(this.getEncodedSignedAttributes()); } return sig.verify(this.getSignature()); } catch (InvalidKeyException e) { throw new CMSException( "key not appropriate to signature in message.", e); } catch (IOException e) { throw new CMSException( "can't process mime object to create signature.", e); } catch (SignatureException e) { throw new CMSException( "invalid signature format in message: " + e.getMessage(), e); } } private boolean isNull( DEREncodable o) { return (o instanceof ASN1Null) || (o == null); } private DigestInfo derDecode( byte[] encoding) throws IOException, CMSException { if (encoding[0] != (DERTags.CONSTRUCTED | DERTags.SEQUENCE)) { throw new IOException("not a digest info object"); } ASN1InputStream aIn = new ASN1InputStream(encoding); DigestInfo digInfo = new DigestInfo((ASN1Sequence)aIn.readObject()); // length check to avoid Bleichenbacher vulnerability if (digInfo.getEncoded().length != encoding.length) { throw new CMSException("malformed RSA signature"); } return digInfo; } private boolean verifyDigest( byte[] digest, PublicKey key, byte[] signature, Provider sigProvider) throws NoSuchAlgorithmException, CMSException { String algorithm = CMSSignedHelper.INSTANCE.getEncryptionAlgName(this.getEncryptionAlgOID()); try { if (algorithm.equals("RSA")) { Cipher c; if (sigProvider != null) { c = Cipher.getInstance("RSA/ECB/PKCS1Padding", sigProvider); } else { c = Cipher.getInstance("RSA/ECB/PKCS1Padding"); } c.init(Cipher.DECRYPT_MODE, key); DigestInfo digInfo = derDecode(c.doFinal(signature)); if (!digInfo.getAlgorithmId().getObjectId().equals(digestAlgorithm.getObjectId())) { return false; } if (!isNull(digInfo.getAlgorithmId().getParameters())) { return false; } byte[] sigHash = digInfo.getDigest(); return MessageDigest.isEqual(digest, sigHash); } else if (algorithm.equals("DSA")) { Signature sig; if (sigProvider != null) { sig = Signature.getInstance("NONEwithDSA", sigProvider); } else { sig = Signature.getInstance("NONEwithDSA"); } sig.initVerify(key); sig.update(digest); return sig.verify(signature); } else { throw new CMSException("algorithm: " + algorithm + " not supported in base signatures."); } } catch (GeneralSecurityException e) { throw new CMSException("Exception processing signature: " + e, e); } catch (IOException e) { throw new CMSException("Exception decoding signature: " + e, e); } } /** * verify that the given public key succesfully handles and confirms the * signature associated with this signer. */ public boolean verify( PublicKey key, String sigProvider) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException { return doVerify(key, this.getSignedAttributes(), CMSUtils.getProvider(sigProvider)); } /** * verify that the given public key succesfully handles and confirms the * signature associated with this signer. */ public boolean verify( PublicKey key, Provider sigProvider) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException { return doVerify(key, this.getSignedAttributes(), sigProvider); } /** * verify that the given certificate successfully handles and confirms * the signature associated with this signer and, if a signingTime * attribute is available, that the certificate was valid at the time the * signature was generated. */ public boolean verify( X509Certificate cert, String sigProvider) throws NoSuchAlgorithmException, NoSuchProviderException, CertificateExpiredException, CertificateNotYetValidException, CMSException { return verify(cert, CMSUtils.getProvider(sigProvider)); } /** * verify that the given certificate successfully handles and confirms * the signature associated with this signer and, if a signingTime * attribute is available, that the certificate was valid at the time the * signature was generated. */ public boolean verify( X509Certificate cert, Provider sigProvider) throws NoSuchAlgorithmException, CertificateExpiredException, CertificateNotYetValidException, CMSException { AttributeTable attr = this.getSignedAttributes(); if (attr != null) { ASN1EncodableVector v = attr.getAll(CMSAttributes.signingTime); switch (v.size()) { case 0: break; case 1: { Attribute t = (Attribute)v.get(0); // assert t != null; ASN1Set attrValues = t.getAttrValues(); if (attrValues.size() != 1) { throw new CMSException("A signing-time attribute MUST have a single attribute value"); } Time time = Time.getInstance(attrValues.getObjectAt(0).getDERObject()); cert.checkValidity(time.getDate()); break; } default: throw new CMSException("The SignedAttributes in a signerInfo MUST NOT include multiple instances of the signing-time attribute"); } } return doVerify(cert.getPublicKey(), attr, sigProvider); } /** * Return the base ASN.1 CMS structure that this object contains. * * @return an object containing a CMS SignerInfo structure. */ public SignerInfo toSignerInfo() { return info; } /** * Return a signer information object with the passed in unsigned * attributes replacing the ones that are current associated with * the object passed in. * * @param signerInformation the signerInfo to be used as the basis. * @param unsignedAttributes the unsigned attributes to add. * @return a copy of the original SignerInformationObject with the changed attributes. */ public static SignerInformation replaceUnsignedAttributes( SignerInformation signerInformation, AttributeTable unsignedAttributes) { SignerInfo sInfo = signerInformation.info; ASN1Set unsignedAttr = null; if (unsignedAttributes != null) { unsignedAttr = new DERSet(unsignedAttributes.toASN1EncodableVector()); } return new SignerInformation( new SignerInfo(sInfo.getSID(), sInfo.getDigestAlgorithm(), sInfo.getAuthenticatedAttributes(), sInfo.getDigestEncryptionAlgorithm(), sInfo.getEncryptedDigest(), unsignedAttr), signerInformation.contentType, signerInformation.content, null); } /** * Return a signer information object with passed in SignerInformationStore representing counter * signatures attached as an unsigned attribute. * * @param signerInformation the signerInfo to be used as the basis. * @param counterSigners signer info objects carrying counter signature. * @return a copy of the original SignerInformationObject with the changed attributes. */ public static SignerInformation addCounterSigners( SignerInformation signerInformation, SignerInformationStore counterSigners) { SignerInfo sInfo = signerInformation.info; AttributeTable unsignedAttr = signerInformation.getUnsignedAttributes(); ASN1EncodableVector v; if (unsignedAttr != null) { v = unsignedAttr.toASN1EncodableVector(); } else { v = new ASN1EncodableVector(); } ASN1EncodableVector sigs = new ASN1EncodableVector(); for (Iterator it = counterSigners.getSigners().iterator(); it.hasNext();) { sigs.add(((SignerInformation)it.next()).toSignerInfo()); } v.add(new Attribute(CMSAttributes.counterSignature, new DERSet(sigs))); return new SignerInformation( new SignerInfo(sInfo.getSID(), sInfo.getDigestAlgorithm(), sInfo.getAuthenticatedAttributes(), sInfo.getDigestEncryptionAlgorithm(), sInfo.getEncryptedDigest(), new DERSet(v)), signerInformation.contentType, signerInformation.content, null); } }
More work on attribute validation
src/org/bouncycastle/cms/SignerInformation.java
More work on attribute validation
<ide><path>rc/org/bouncycastle/cms/SignerInformation.java <ide> <ide> private boolean doVerify( <ide> PublicKey key, <del> AttributeTable signedAttrTable, <ide> Provider sigProvider) <ide> throws CMSException, NoSuchAlgorithmException <ide> { <ide> } <ide> <ide> resultDigest = hash; <del> <del> Attribute dig = signedAttrTable.get( <del> CMSAttributes.messageDigest); <del> Attribute type = signedAttrTable.get( <del> CMSAttributes.contentType); <add> <add> // TODO RFC 3852 11.4 Validate countersignature attribute <add> // TODO Shouldn't be using attribute OID as contentType (should be null) <add> boolean isCounterSignature = contentType.equals( <add> CMSAttributes.counterSignature); <add> <add> AttributeTable signedAttrTable = this.getSignedAttributes(); <add> <add> // Check the content-type attribute is correct <add> DERObject validContentType = getSingleValuedSignedAttribute( <add> CMSAttributes.contentType, "content-type"); <add> if (validContentType == null) <add> { <add> if (!isCounterSignature && signedAttrTable != null) <add> { <add> throw new CMSException("The content-type attribute type MUST be present whenever signed attributes are present in signed-data"); <add> } <add> } <add> else <add> { <add> if (isCounterSignature) <add> { <add> throw new CMSException("[For counter signatures,] the signedAttributes field MUST NOT contain a content-type attribute"); <add> } <add> <add> DERObjectIdentifier typeOID = (DERObjectIdentifier)validContentType; <add> <add> if (!typeOID.equals(contentType)) <add> { <add> throw new SignatureException("contentType in signed attributes different"); <add> } <add> } <add> <add> // Check the message-digest attribute is correct <add> Attribute dig = signedAttrTable.get(CMSAttributes.messageDigest); <ide> <ide> if (dig == null) <ide> { <ide> throw new SignatureException("no hash for content found in signed attributes"); <del> } <del> <del> if (type == null && !contentType.equals(CMSAttributes.counterSignature)) <del> { <del> throw new SignatureException("no content type id found in signed attributes"); <ide> } <ide> <ide> DERObject hashObj = dig.getAttrValues().getObjectAt(0).getDERObject(); <ide> if (hash != null) <ide> { <ide> throw new SignatureException("NULL hash found in signed attributes when one expected"); <del> } <del> } <del> <del> if (type != null) <del> { <del> DERObjectIdentifier typeOID = (DERObjectIdentifier)type.getAttrValues().getObjectAt(0); <del> <del> if (!typeOID.equals(contentType)) <del> { <del> throw new SignatureException("contentType in signed attributes different"); <ide> } <ide> } <ide> <ide> String sigProvider) <ide> throws NoSuchAlgorithmException, NoSuchProviderException, CMSException <ide> { <del> return doVerify(key, this.getSignedAttributes(), CMSUtils.getProvider(sigProvider)); <add> return doVerify(key, CMSUtils.getProvider(sigProvider)); <ide> } <ide> <ide> /** <ide> Provider sigProvider) <ide> throws NoSuchAlgorithmException, NoSuchProviderException, CMSException <ide> { <del> return doVerify(key, this.getSignedAttributes(), sigProvider); <add> return doVerify(key, sigProvider); <ide> } <ide> <ide> /** <ide> CertificateExpiredException, CertificateNotYetValidException, <ide> CMSException <ide> { <del> AttributeTable attr = this.getSignedAttributes(); <del> <del> if (attr != null) <del> { <del> ASN1EncodableVector v = attr.getAll(CMSAttributes.signingTime); <del> switch (v.size()) <del> { <del> case 0: <del> break; <del> case 1: <del> { <del> Attribute t = (Attribute)v.get(0); <del>// assert t != null; <del> <del> ASN1Set attrValues = t.getAttrValues(); <del> if (attrValues.size() != 1) <del> { <del> throw new CMSException("A signing-time attribute MUST have a single attribute value"); <del> } <del> <del> Time time = Time.getInstance(attrValues.getObjectAt(0).getDERObject()); <del> <del> cert.checkValidity(time.getDate()); <del> break; <del> } <del> default: <del> throw new CMSException("The SignedAttributes in a signerInfo MUST NOT include multiple instances of the signing-time attribute"); <del> } <del> } <del> <del> return doVerify(cert.getPublicKey(), attr, sigProvider); <add> DERObject validSigningTime = getSingleValuedSignedAttribute( <add> CMSAttributes.signingTime, "signing-time"); <add> <add> if (validSigningTime != null) <add> { <add> Time time = Time.getInstance(validSigningTime); <add> <add> cert.checkValidity(time.getDate()); <add> } <add> <add> return doVerify(cert.getPublicKey(), sigProvider); <ide> } <ide> <ide> /** <ide> public SignerInfo toSignerInfo() <ide> { <ide> return info; <add> } <add> <add> private DERObject getSingleValuedSignedAttribute( <add> DERObjectIdentifier attrOID, String printableName) <add> throws CMSException <add> { <add> AttributeTable unsignedAttrTable = this.getUnsignedAttributes(); <add> if (unsignedAttrTable != null <add> && unsignedAttrTable.getAll(attrOID).size() > 0) <add> { <add> throw new CMSException("The " + printableName <add> + " attribute MUST NOT be an unsigned attribute"); <add> } <add> <add> AttributeTable signedAttrTable = this.getSignedAttributes(); <add> if (signedAttrTable == null) <add> { <add> return null; <add> } <add> <add> ASN1EncodableVector v = signedAttrTable.getAll(attrOID); <add> switch (v.size()) <add> { <add> case 0: <add> return null; <add> case 1: <add> { <add> Attribute t = (Attribute)v.get(0); <add>// assert t != null; <add> <add> ASN1Set attrValues = t.getAttrValues(); <add> if (attrValues.size() != 1) <add> { <add> throw new CMSException("A " + printableName <add> + " attribute MUST have a single attribute value"); <add> } <add> <add> return attrValues.getObjectAt(0).getDERObject(); <add> } <add> default: <add> throw new CMSException("The SignedAttributes in a signerInfo MUST NOT include multiple instances of the " <add> + printableName + " attribute"); <add> } <ide> } <ide> <ide> /** <ide> SignerInformation signerInformation, <ide> SignerInformationStore counterSigners) <ide> { <add> // TODO Perform checks from RFC 3852 11.4 <add> <ide> SignerInfo sInfo = signerInformation.info; <ide> AttributeTable unsignedAttr = signerInformation.getUnsignedAttributes(); <ide> ASN1EncodableVector v;
Java
apache-2.0
2ba994af8aae58a652d9e4f9fc6cfaf503667037
0
opencb/opencga,j-coll/opencga,opencb/opencga,j-coll/opencga,opencb/opencga,j-coll/opencga,j-coll/opencga,j-coll/opencga,opencb/opencga,opencb/opencga,j-coll/opencga,opencb/opencga
package org.opencb.opencga.analysis.clinical; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.opencb.biodata.models.alignment.RegionCoverage; import org.opencb.biodata.models.clinical.interpretation.ClinicalProperty.RoleInCancer; import org.opencb.biodata.models.clinical.interpretation.DiseasePanel; import org.opencb.biodata.models.clinical.interpretation.Interpretation; import org.opencb.biodata.models.clinical.interpretation.ReportedLowCoverage; import org.opencb.biodata.models.commons.Analyst; import org.opencb.biodata.models.core.Exon; import org.opencb.biodata.models.core.Gene; import org.opencb.biodata.models.core.Region; import org.opencb.biodata.models.core.Transcript; import org.opencb.cellbase.client.rest.CellBaseClient; import org.opencb.commons.datastore.core.*; import org.opencb.commons.utils.ListUtils; import org.opencb.opencga.analysis.AnalysisResult; import org.opencb.opencga.analysis.OpenCgaAnalysis; import org.opencb.opencga.analysis.exceptions.AnalysisException; import org.opencb.opencga.catalog.db.api.FileDBAdaptor; import org.opencb.opencga.catalog.db.api.UserDBAdaptor; import org.opencb.opencga.catalog.exceptions.CatalogException; import org.opencb.opencga.core.models.*; import org.opencb.opencga.storage.core.StorageEngineFactory; import org.opencb.opencga.storage.core.manager.AlignmentStorageManager; import java.util.*; public abstract class FamilyAnalysis extends OpenCgaAnalysis<Interpretation> { protected String clinicalAnalysisId; protected List<String> diseasePanelIds; protected Map<String, RoleInCancer> roleInCancer; protected Map<String, List<String>> actionableVariants; protected ObjectMap config; @Deprecated protected int maxCoverage; protected final static String SEPARATOR = "__"; public final static int LOW_COVERAGE_DEFAULT = 20; public final static String INCLUDE_LOW_COVERAGE_PARAM = "includeLowCoverage"; public final static String MAX_LOW_COVERAGE_PARAM = "maxLowCoverage"; public final static String SKIP_DIAGNOSTIC_VARIANTS_PARAM = "skipDiagnosticVariants"; public final static String SKIP_UNTIERED_VARIANTS_PARAM = "skipUntieredVariants"; protected CellBaseClient cellBaseClient; protected AlignmentStorageManager alignmentStorageManager; public FamilyAnalysis(String clinicalAnalysisId, List<String> diseasePanelIds, Map<String, RoleInCancer> roleInCancer, Map<String, List<String>> actionableVariants, ObjectMap config, String studyStr, String opencgaHome, String token) { super(opencgaHome, studyStr, token); this.clinicalAnalysisId = clinicalAnalysisId; this.diseasePanelIds = diseasePanelIds; this.actionableVariants = actionableVariants; this.roleInCancer = roleInCancer; this.config = config != null ? config : new ObjectMap(); this.maxCoverage = 20; this.cellBaseClient = new CellBaseClient(storageConfiguration.getCellbase().toClientConfiguration()); this.alignmentStorageManager = new AlignmentStorageManager(catalogManager, StorageEngineFactory.get(storageConfiguration)); } @Override public abstract AnalysisResult<Interpretation> execute() throws Exception; protected ClinicalAnalysis getClinicalAnalysis() throws AnalysisException { QueryResult<ClinicalAnalysis> clinicalAnalysisQueryResult; try { clinicalAnalysisQueryResult = catalogManager.getClinicalAnalysisManager() .get(studyStr, clinicalAnalysisId, QueryOptions.empty(), token); } catch (CatalogException e) { throw new AnalysisException(e.getMessage(), e); } if (clinicalAnalysisQueryResult.getNumResults() == 0) { throw new AnalysisException("Clinical analysis " + clinicalAnalysisId + " not found in study " + studyStr); } ClinicalAnalysis clinicalAnalysis = clinicalAnalysisQueryResult.first(); // Sanity checks if (clinicalAnalysis.getFamily() == null || StringUtils.isEmpty(clinicalAnalysis.getFamily().getId())) { throw new AnalysisException("Missing family in clinical analysis " + clinicalAnalysisId); } if (clinicalAnalysis.getProband() == null || StringUtils.isEmpty(clinicalAnalysis.getProband().getId())) { throw new AnalysisException("Missing proband in clinical analysis " + clinicalAnalysisId); } return clinicalAnalysis; } protected Individual getProband(ClinicalAnalysis clinicalAnalysis) throws AnalysisException { Individual proband = clinicalAnalysis.getProband(); String clinicalAnalysisId = clinicalAnalysis.getId(); // Sanity checks if (proband == null) { throw new AnalysisException("Missing proband in clinical analysis " + clinicalAnalysisId); } if (ListUtils.isEmpty(proband.getSamples())) { throw new AnalysisException("Missing samples in proband " + proband.getId() + " in clinical analysis " + clinicalAnalysisId); } if (proband.getSamples().size() > 1) { throw new AnalysisException("Found more than one sample for proband " + proband.getId() + " in clinical analysis " + clinicalAnalysisId); } return proband; } protected List<String> getSampleNames(ClinicalAnalysis clinicalAnalysis) throws AnalysisException { return getSampleNames(clinicalAnalysis, null); } protected List<String> getSampleNames(ClinicalAnalysis clinicalAnalysis, Individual proband) throws AnalysisException { List<String> sampleList = new ArrayList<>(); // Sanity check if (clinicalAnalysis != null && clinicalAnalysis.getFamily() != null && CollectionUtils.isNotEmpty(clinicalAnalysis.getFamily().getMembers())) { Map<String, Individual> individualMap = new HashMap<>(); for (Individual member : clinicalAnalysis.getFamily().getMembers()) { if (ListUtils.isEmpty(member.getSamples())) { // throw new AnalysisException("No samples found for member " + member.getId()); continue; } if (member.getSamples().size() > 1) { throw new AnalysisException("More than one sample found for member " + member.getId()); } sampleList.add(member.getSamples().get(0).getId()); individualMap.put(member.getId(), member); } if (proband != null) { // Fill proband information to be able to navigate to the parents and their samples easily // Sanity check if (proband.getFather() != null && StringUtils.isNotEmpty(proband.getFather().getId()) && individualMap.containsKey(proband.getFather().getId())) { proband.setFather(individualMap.get(proband.getFather().getId())); } if (proband.getMother() != null && StringUtils.isNotEmpty(proband.getMother().getId()) && individualMap.containsKey(proband.getMother().getId())) { proband.setMother(individualMap.get(proband.getMother().getId())); } } } return sampleList; } protected List<ReportedLowCoverage> getReportedLowCoverage(ClinicalAnalysis clinicalAnalysis, List<Panel> diseasePanels) throws AnalysisException { String clinicalAnalysisId = clinicalAnalysis.getId(); // Sanity check if (clinicalAnalysis.getProband() == null || CollectionUtils.isEmpty(clinicalAnalysis.getProband().getSamples())) { throw new AnalysisException("Missing proband when computing reported low coverage"); } String probandId; try { probandId = clinicalAnalysis.getProband().getSamples().get(0).getId(); } catch (Exception e) { throw new AnalysisException("Missing proband when computing reported low coverage", e); } // Reported low coverage map List<ReportedLowCoverage> reportedLowCoverages = new ArrayList<>(); Set<String> lowCoverageByGeneDone = new HashSet<>(); // Look for the bam file of the proband QueryResult<File> fileQueryResult; try { fileQueryResult = catalogManager.getFileManager().get(studyStr, new Query() .append(FileDBAdaptor.QueryParams.SAMPLES.key(), probandId) .append(FileDBAdaptor.QueryParams.FORMAT.key(), File.Format.BAM), new QueryOptions(QueryOptions.INCLUDE, FileDBAdaptor.QueryParams.UUID.key()), token); } catch (CatalogException e) { throw new AnalysisException(e.getMessage(), e); } if (fileQueryResult.getNumResults() > 1) { throw new AnalysisException("More than one BAM file found for proband " + probandId + " in clinical analysis " + clinicalAnalysisId); } String bamFileId = fileQueryResult.getNumResults() == 1 ? fileQueryResult.first().getUuid() : null; if (bamFileId != null) { for (Panel diseasePanel : diseasePanels) { for (DiseasePanel.GenePanel genePanel : diseasePanel.getDiseasePanel().getGenes()) { String geneName = genePanel.getId(); if (!lowCoverageByGeneDone.contains(geneName)) { reportedLowCoverages.addAll(getReportedLowCoverages(geneName, bamFileId, maxCoverage)); lowCoverageByGeneDone.add(geneName); } } } } return reportedLowCoverages; } private List<ReportedLowCoverage> getReportedLowCoverages(String geneName, String bamFileId, int maxCoverage) { List<ReportedLowCoverage> reportedLowCoverages = new ArrayList<>(); try { // Get gene exons from CellBase QueryResponse<Gene> geneQueryResponse = cellBaseClient.getGeneClient().get(Collections.singletonList(geneName), QueryOptions.empty()); List<RegionCoverage> regionCoverages; for (Transcript transcript: geneQueryResponse.getResponse().get(0).first().getTranscripts()) { for (Exon exon: transcript.getExons()) { regionCoverages = alignmentStorageManager.getLowCoverageRegions(studyStr, bamFileId, new Region(exon.getChromosome(), exon.getStart(), exon.getEnd()), maxCoverage, token).getResult(); for (RegionCoverage regionCoverage: regionCoverages) { ReportedLowCoverage reportedLowCoverage = new ReportedLowCoverage(regionCoverage) .setGeneName(geneName) .setId(exon.getId()); reportedLowCoverages.add(reportedLowCoverage); } } } } catch (Exception e) { logger.error("Error getting low coverage regions for panel genes.", e.getMessage()); } // And for that exon regions, get low coverage regions return reportedLowCoverages; } protected List<Panel> getDiseasePanelsFromIds(List<String> diseasePanelIds) throws AnalysisException { List<Panel> diseasePanels = new ArrayList<>(); if (diseasePanelIds != null && !diseasePanelIds.isEmpty()) { List<QueryResult<Panel>> queryResults; try { queryResults = catalogManager.getPanelManager() .get(studyStr, diseasePanelIds, new Query(), QueryOptions.empty(), token); } catch (CatalogException e) { throw new AnalysisException(e.getMessage(), e); } if (queryResults.size() != diseasePanelIds.size()) { throw new AnalysisException("The number of disease panels retrieved doesn't match the number of disease panels queried"); } for (QueryResult<Panel> queryResult : queryResults) { if (queryResult.getNumResults() != 1) { throw new AnalysisException("The number of disease panels retrieved doesn't match the number of disease panels " + "queried"); } diseasePanels.add(queryResult.first()); } } else { throw new AnalysisException("Missing disease panels"); } return diseasePanels; } protected Analyst getAnalyst(String token) throws AnalysisException { try { String userId = catalogManager.getUserManager().getUserId(token); QueryResult<User> userQueryResult = catalogManager.getUserManager().get(userId, new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(UserDBAdaptor.QueryParams.EMAIL.key(), UserDBAdaptor.QueryParams.ORGANIZATION.key())), token); return new Analyst(userId, userQueryResult.first().getEmail(), userQueryResult.first().getOrganization()); } catch (CatalogException e) { throw new AnalysisException(e.getMessage(), e); } } }
opencga-analysis/src/main/java/org/opencb/opencga/analysis/clinical/FamilyAnalysis.java
package org.opencb.opencga.analysis.clinical; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.opencb.biodata.models.alignment.RegionCoverage; import org.opencb.biodata.models.clinical.interpretation.ClinicalProperty.RoleInCancer; import org.opencb.biodata.models.clinical.interpretation.DiseasePanel; import org.opencb.biodata.models.clinical.interpretation.Interpretation; import org.opencb.biodata.models.clinical.interpretation.ReportedLowCoverage; import org.opencb.biodata.models.commons.Analyst; import org.opencb.biodata.models.core.Exon; import org.opencb.biodata.models.core.Gene; import org.opencb.biodata.models.core.Region; import org.opencb.biodata.models.core.Transcript; import org.opencb.cellbase.client.rest.CellBaseClient; import org.opencb.commons.datastore.core.*; import org.opencb.commons.utils.ListUtils; import org.opencb.opencga.analysis.AnalysisResult; import org.opencb.opencga.analysis.OpenCgaAnalysis; import org.opencb.opencga.analysis.exceptions.AnalysisException; import org.opencb.opencga.catalog.db.api.FileDBAdaptor; import org.opencb.opencga.catalog.db.api.UserDBAdaptor; import org.opencb.opencga.catalog.exceptions.CatalogException; import org.opencb.opencga.core.models.*; import org.opencb.opencga.storage.core.StorageEngineFactory; import org.opencb.opencga.storage.core.manager.AlignmentStorageManager; import java.util.*; public abstract class FamilyAnalysis extends OpenCgaAnalysis<Interpretation> { protected String clinicalAnalysisId; protected List<String> diseasePanelIds; protected Map<String, RoleInCancer> roleInCancer; protected Map<String, List<String>> actionableVariants; protected ObjectMap config; @Deprecated protected int maxCoverage; protected final static String SEPARATOR = "__"; public final static int LOW_COVERAGE_DEFAULT = 20; public final static String INCLUDE_LOW_COVERAGE_PARAM = "includeLowCoverage"; public final static String MAX_LOW_COVERAGE_PARAM = "maxLowCoverage"; public final static String SKIP_DIAGNOSTIC_VARIANTS_PARAM = "skipDiagnosticVariants"; public final static String SKIP_UNTIERED_VARIANTS_PARAM = "skipUntieredVariants"; protected CellBaseClient cellBaseClient; protected AlignmentStorageManager alignmentStorageManager; public FamilyAnalysis(String clinicalAnalysisId, List<String> diseasePanelIds, Map<String, RoleInCancer> roleInCancer, Map<String, List<String>> actionableVariants, ObjectMap config, String studyStr, String opencgaHome, String token) { super(opencgaHome, studyStr, token); this.clinicalAnalysisId = clinicalAnalysisId; this.diseasePanelIds = diseasePanelIds; this.actionableVariants = actionableVariants; this.roleInCancer = roleInCancer; this.config = config != null ? config : new ObjectMap(); this.maxCoverage = 20; this.cellBaseClient = new CellBaseClient(storageConfiguration.getCellbase().toClientConfiguration()); this.alignmentStorageManager = new AlignmentStorageManager(catalogManager, StorageEngineFactory.get(storageConfiguration)); } @Override public abstract AnalysisResult<Interpretation> execute() throws Exception; protected ClinicalAnalysis getClinicalAnalysis() throws AnalysisException { QueryResult<ClinicalAnalysis> clinicalAnalysisQueryResult; try { clinicalAnalysisQueryResult = catalogManager.getClinicalAnalysisManager() .get(studyStr, clinicalAnalysisId, QueryOptions.empty(), token); } catch (CatalogException e) { throw new AnalysisException(e.getMessage(), e); } if (clinicalAnalysisQueryResult.getNumResults() == 0) { throw new AnalysisException("Clinical analysis " + clinicalAnalysisId + " not found in study " + studyStr); } ClinicalAnalysis clinicalAnalysis = clinicalAnalysisQueryResult.first(); // Sanity checks if (clinicalAnalysis.getFamily() == null || StringUtils.isEmpty(clinicalAnalysis.getFamily().getId())) { throw new AnalysisException("Missing family in clinical analysis " + clinicalAnalysisId); } if (clinicalAnalysis.getProband() == null || StringUtils.isEmpty(clinicalAnalysis.getProband().getId())) { throw new AnalysisException("Missing proband in clinical analysis " + clinicalAnalysisId); } return clinicalAnalysis; } protected Individual getProband(ClinicalAnalysis clinicalAnalysis) throws AnalysisException { Individual proband = clinicalAnalysis.getProband(); String clinicalAnalysisId = clinicalAnalysis.getId(); // Sanity checks if (proband == null) { throw new AnalysisException("Missing proband in clinical analysis " + clinicalAnalysisId); } if (ListUtils.isEmpty(proband.getSamples())) { throw new AnalysisException("Missing samples in proband " + proband.getId() + " in clinical analysis " + clinicalAnalysisId); } if (proband.getSamples().size() > 1) { throw new AnalysisException("Found more than one sample for proband " + proband.getId() + " in clinical analysis " + clinicalAnalysisId); } return proband; } protected List<String> getSampleNames(ClinicalAnalysis clinicalAnalysis) throws AnalysisException { return getSampleNames(clinicalAnalysis, null); } protected List<String> getSampleNames(ClinicalAnalysis clinicalAnalysis, Individual proband) throws AnalysisException { List<String> sampleList = new ArrayList<>(); // Sanity check if (clinicalAnalysis != null && clinicalAnalysis.getFamily() != null && CollectionUtils.isNotEmpty(clinicalAnalysis.getFamily().getMembers())) { Map<String, Individual> individualMap = new HashMap<>(); for (Individual member : clinicalAnalysis.getFamily().getMembers()) { if (member.getSamples().size() > 1) { throw new AnalysisException("More than one sample found for member " + member.getId()); } if (member.getSamples().size() == 0) { throw new AnalysisException("No samples found for member " + member.getId()); } sampleList.add(member.getSamples().get(0).getId()); individualMap.put(member.getId(), member); } if (proband != null) { // Fill proband information to be able to navigate to the parents and their samples easily // Sanity check if (proband.getFather() != null && StringUtils.isNotEmpty(proband.getFather().getId()) && individualMap.containsKey(proband.getFather().getId())) { proband.setFather(individualMap.get(proband.getFather().getId())); } if (proband.getMother() != null && StringUtils.isNotEmpty(proband.getMother().getId()) && individualMap.containsKey(proband.getMother().getId())) { proband.setMother(individualMap.get(proband.getMother().getId())); } } } return sampleList; } protected List<ReportedLowCoverage> getReportedLowCoverage(ClinicalAnalysis clinicalAnalysis, List<Panel> diseasePanels) throws AnalysisException { String clinicalAnalysisId = clinicalAnalysis.getId(); // Sanity check if (clinicalAnalysis.getProband() == null || CollectionUtils.isEmpty(clinicalAnalysis.getProband().getSamples())) { throw new AnalysisException("Missing proband when computing reported low coverage"); } String probandId; try { probandId = clinicalAnalysis.getProband().getSamples().get(0).getId(); } catch (Exception e) { throw new AnalysisException("Missing proband when computing reported low coverage", e); } // Reported low coverage map List<ReportedLowCoverage> reportedLowCoverages = new ArrayList<>(); Set<String> lowCoverageByGeneDone = new HashSet<>(); // Look for the bam file of the proband QueryResult<File> fileQueryResult; try { fileQueryResult = catalogManager.getFileManager().get(studyStr, new Query() .append(FileDBAdaptor.QueryParams.SAMPLES.key(), probandId) .append(FileDBAdaptor.QueryParams.FORMAT.key(), File.Format.BAM), new QueryOptions(QueryOptions.INCLUDE, FileDBAdaptor.QueryParams.UUID.key()), token); } catch (CatalogException e) { throw new AnalysisException(e.getMessage(), e); } if (fileQueryResult.getNumResults() > 1) { throw new AnalysisException("More than one BAM file found for proband " + probandId + " in clinical analysis " + clinicalAnalysisId); } String bamFileId = fileQueryResult.getNumResults() == 1 ? fileQueryResult.first().getUuid() : null; if (bamFileId != null) { for (Panel diseasePanel : diseasePanels) { for (DiseasePanel.GenePanel genePanel : diseasePanel.getDiseasePanel().getGenes()) { String geneName = genePanel.getId(); if (!lowCoverageByGeneDone.contains(geneName)) { reportedLowCoverages.addAll(getReportedLowCoverages(geneName, bamFileId, maxCoverage)); lowCoverageByGeneDone.add(geneName); } } } } return reportedLowCoverages; } private List<ReportedLowCoverage> getReportedLowCoverages(String geneName, String bamFileId, int maxCoverage) { List<ReportedLowCoverage> reportedLowCoverages = new ArrayList<>(); try { // Get gene exons from CellBase QueryResponse<Gene> geneQueryResponse = cellBaseClient.getGeneClient().get(Collections.singletonList(geneName), QueryOptions.empty()); List<RegionCoverage> regionCoverages; for (Transcript transcript: geneQueryResponse.getResponse().get(0).first().getTranscripts()) { for (Exon exon: transcript.getExons()) { regionCoverages = alignmentStorageManager.getLowCoverageRegions(studyStr, bamFileId, new Region(exon.getChromosome(), exon.getStart(), exon.getEnd()), maxCoverage, token).getResult(); for (RegionCoverage regionCoverage: regionCoverages) { ReportedLowCoverage reportedLowCoverage = new ReportedLowCoverage(regionCoverage) .setGeneName(geneName) .setId(exon.getId()); reportedLowCoverages.add(reportedLowCoverage); } } } } catch (Exception e) { logger.error("Error getting low coverage regions for panel genes.", e.getMessage()); } // And for that exon regions, get low coverage regions return reportedLowCoverages; } protected List<Panel> getDiseasePanelsFromIds(List<String> diseasePanelIds) throws AnalysisException { List<Panel> diseasePanels = new ArrayList<>(); if (diseasePanelIds != null && !diseasePanelIds.isEmpty()) { List<QueryResult<Panel>> queryResults; try { queryResults = catalogManager.getPanelManager() .get(studyStr, diseasePanelIds, new Query(), QueryOptions.empty(), token); } catch (CatalogException e) { throw new AnalysisException(e.getMessage(), e); } if (queryResults.size() != diseasePanelIds.size()) { throw new AnalysisException("The number of disease panels retrieved doesn't match the number of disease panels queried"); } for (QueryResult<Panel> queryResult : queryResults) { if (queryResult.getNumResults() != 1) { throw new AnalysisException("The number of disease panels retrieved doesn't match the number of disease panels " + "queried"); } diseasePanels.add(queryResult.first()); } } else { throw new AnalysisException("Missing disease panels"); } return diseasePanels; } protected Analyst getAnalyst(String token) throws AnalysisException { try { String userId = catalogManager.getUserManager().getUserId(token); QueryResult<User> userQueryResult = catalogManager.getUserManager().get(userId, new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(UserDBAdaptor.QueryParams.EMAIL.key(), UserDBAdaptor.QueryParams.ORGANIZATION.key())), token); return new Analyst(userId, userQueryResult.first().getEmail(), userQueryResult.first().getOrganization()); } catch (CatalogException e) { throw new AnalysisException(e.getMessage(), e); } } }
analysis: do not raise an exception when no samples are found
opencga-analysis/src/main/java/org/opencb/opencga/analysis/clinical/FamilyAnalysis.java
analysis: do not raise an exception when no samples are found
<ide><path>pencga-analysis/src/main/java/org/opencb/opencga/analysis/clinical/FamilyAnalysis.java <ide> <ide> Map<String, Individual> individualMap = new HashMap<>(); <ide> for (Individual member : clinicalAnalysis.getFamily().getMembers()) { <add> if (ListUtils.isEmpty(member.getSamples())) { <add>// throw new AnalysisException("No samples found for member " + member.getId()); <add> continue; <add> } <ide> if (member.getSamples().size() > 1) { <ide> throw new AnalysisException("More than one sample found for member " + member.getId()); <del> } <del> if (member.getSamples().size() == 0) { <del> throw new AnalysisException("No samples found for member " + member.getId()); <ide> } <ide> sampleList.add(member.getSamples().get(0).getId()); <ide> individualMap.put(member.getId(), member);
Java
agpl-3.0
a20e122495d7497c4e0e0bfe423a5cf6323df5db
0
skylow95/libreplan,poum/libreplan,PaulLuchyn/libreplan,skylow95/libreplan,PaulLuchyn/libreplan,Marine-22/libre,poum/libreplan,PaulLuchyn/libreplan,skylow95/libreplan,Marine-22/libre,poum/libreplan,LibrePlan/libreplan,skylow95/libreplan,LibrePlan/libreplan,Marine-22/libre,LibrePlan/libreplan,dgray16/libreplan,Marine-22/libre,poum/libreplan,LibrePlan/libreplan,Marine-22/libre,skylow95/libreplan,dgray16/libreplan,dgray16/libreplan,LibrePlan/libreplan,LibrePlan/libreplan,PaulLuchyn/libreplan,Marine-22/libre,poum/libreplan,PaulLuchyn/libreplan,LibrePlan/libreplan,PaulLuchyn/libreplan,poum/libreplan,PaulLuchyn/libreplan,dgray16/libreplan,dgray16/libreplan,dgray16/libreplan,skylow95/libreplan,dgray16/libreplan
/* * This file is part of NavalPlan * * Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e * Desenvolvemento Tecnolóxico de Galicia * Copyright (C) 2010-2011 Igalia, S.L. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.navalplanner.web.planner.allocation; import static org.navalplanner.web.I18nHelper._; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.WeakHashMap; import java.util.concurrent.Callable; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.joda.time.Period; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.navalplanner.business.planner.entities.AggregateOfResourceAllocations; import org.navalplanner.business.planner.entities.AssignmentFunction; import org.navalplanner.business.planner.entities.AssignmentFunction.AssignmentFunctionName; import org.navalplanner.business.planner.entities.CalculatedValue; import org.navalplanner.business.planner.entities.GenericResourceAllocation; import org.navalplanner.business.planner.entities.ManualFunction; import org.navalplanner.business.planner.entities.ResourceAllocation; import org.navalplanner.business.planner.entities.SigmoidFunction; import org.navalplanner.business.planner.entities.SpecificResourceAllocation; import org.navalplanner.business.planner.entities.StretchesFunctionTypeEnum; import org.navalplanner.business.planner.entities.Task; import org.navalplanner.business.planner.entities.TaskElement; import org.navalplanner.business.resources.entities.Criterion; import org.navalplanner.business.workingday.EffortDuration; import org.navalplanner.web.common.EffortDurationBox; import org.navalplanner.web.common.IMessagesForUser; import org.navalplanner.web.common.MessagesForUser; import org.navalplanner.web.common.OnlyOneVisible; import org.navalplanner.web.common.Util; import org.navalplanner.web.planner.allocation.streches.StrechesFunctionConfiguration; import org.zkoss.ganttz.timetracker.ICellForDetailItemRenderer; import org.zkoss.ganttz.timetracker.IConvertibleToColumn; import org.zkoss.ganttz.timetracker.PairOfLists; import org.zkoss.ganttz.timetracker.TimeTrackedTable; import org.zkoss.ganttz.timetracker.TimeTrackedTableWithLeftPane; import org.zkoss.ganttz.timetracker.TimeTracker; import org.zkoss.ganttz.timetracker.TimeTracker.IDetailItemFilter; import org.zkoss.ganttz.timetracker.TimeTrackerComponentWithoutColumns; import org.zkoss.ganttz.timetracker.zoom.DetailItem; import org.zkoss.ganttz.timetracker.zoom.IZoomLevelChangedListener; import org.zkoss.ganttz.timetracker.zoom.ZoomLevel; import org.zkoss.ganttz.util.Interval; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.WrongValueException; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.event.Events; import org.zkoss.zk.ui.util.Clients; import org.zkoss.zk.ui.util.GenericForwardComposer; import org.zkoss.zul.Button; import org.zkoss.zul.Div; import org.zkoss.zul.Grid; import org.zkoss.zul.Hbox; import org.zkoss.zul.Label; import org.zkoss.zul.LayoutRegion; import org.zkoss.zul.ListModel; import org.zkoss.zul.Listbox; import org.zkoss.zul.Listcell; import org.zkoss.zul.Listitem; import org.zkoss.zul.Messagebox; import org.zkoss.zul.SimpleListModel; import org.zkoss.zul.api.Column; /** * * @author Óscar González Fernández <[email protected]> * @author Diego Pino García <[email protected]> * */ public class AdvancedAllocationController extends GenericForwardComposer { public static class AllocationInput { private final AggregateOfResourceAllocations aggregate; private final IAdvanceAllocationResultReceiver resultReceiver; private final TaskElement task; public AllocationInput(AggregateOfResourceAllocations aggregate, TaskElement task, IAdvanceAllocationResultReceiver resultReceiver) { Validate.notNull(aggregate); Validate.notNull(resultReceiver); Validate.notNull(task); this.aggregate = aggregate; this.task = task; this.resultReceiver = resultReceiver; } List<ResourceAllocation<?>> getAllocationsSortedByStartDate() { return getAggregate().getAllocationsSortedByStartDate(); } EffortDuration getTotalEffort() { return getAggregate().getTotalEffort(); } AggregateOfResourceAllocations getAggregate() { return aggregate; } String getTaskName() { return task.getName(); } IAdvanceAllocationResultReceiver getResultReceiver() { return resultReceiver; } Interval calculateInterval() { List<ResourceAllocation<?>> all = getAllocationsSortedByStartDate(); if (all.isEmpty()) { return new Interval(task.getStartDate(), task .getEndDate()); } else { LocalDate start = min(all.get(0) .getStartConsideringAssignments(), all.get(0) .getStartDate()); LocalDate taskEndDate = LocalDate.fromDateFields(task .getEndDate()); LocalDate end = max(getEnd(all), taskEndDate); return new Interval(asDate(start), asDate(end)); } } private LocalDate min(LocalDate... dates) { return Collections.min(Arrays.asList(dates), null); } private LocalDate max(LocalDate... dates) { return Collections.max(Arrays.asList(dates), null); } private static LocalDate getEnd(List<ResourceAllocation<?>> all) { ArrayList<ResourceAllocation<?>> reversed = reverse(all); LocalDate end = reversed.get(0).getEndDate(); ListIterator<ResourceAllocation<?>> listIterator = reversed .listIterator(1); while (listIterator.hasNext()) { ResourceAllocation<?> current = listIterator.next(); if (current.getEndDate().compareTo(end) >= 0) { end = current.getEndDate(); } else { return end; } } return end; } private static ArrayList<ResourceAllocation<?>> reverse( List<ResourceAllocation<?>> all) { ArrayList<ResourceAllocation<?>> reversed = new ArrayList<ResourceAllocation<?>>( all); Collections.reverse(reversed); return reversed; } private static Date asDate(LocalDate start) { return start.toDateMidnight().toDate(); } } public interface IAdvanceAllocationResultReceiver { public Restriction createRestriction(); public void accepted(AggregateOfResourceAllocations modifiedAllocations); public void cancel(); } public interface IBack { public void goBack(); boolean isAdvanceAssignmentOfSingleTask(); } public abstract static class Restriction { public interface IRestrictionSource { EffortDuration getTotalEffort(); LocalDate getStart(); LocalDate getEnd(); CalculatedValue getCalculatedValue(); } public static Restriction build(IRestrictionSource restrictionSource) { switch (restrictionSource.getCalculatedValue()) { case END_DATE: return Restriction.emptyRestriction(); case NUMBER_OF_HOURS: return Restriction.onlyAssignOnInterval(restrictionSource .getStart(), restrictionSource.getEnd()); case RESOURCES_PER_DAY: return Restriction.emptyRestriction(); default: throw new RuntimeException("unhandled case: " + restrictionSource.getCalculatedValue()); } } private static Restriction emptyRestriction() { return new NoRestriction(); } private static Restriction onlyAssignOnInterval(LocalDate start, LocalDate end){ return new OnlyOnIntervalRestriction(start, end); } abstract LocalDate limitStartDate(LocalDate startDate); abstract LocalDate limitEndDate(LocalDate localDate); abstract boolean isDisabledEditionOn(DetailItem item); public abstract boolean isInvalidTotalEffort(EffortDuration totalEffort); public abstract void showInvalidEffort(IMessagesForUser messages, EffortDuration totalEffort); public abstract void markInvalidEffort(Row groupingRow, EffortDuration currentEffort); } private static class OnlyOnIntervalRestriction extends Restriction { private final LocalDate start; private final LocalDate end; private OnlyOnIntervalRestriction(LocalDate start, LocalDate end) { super(); this.start = start; this.end = end; } private org.joda.time.Interval intervalAllowed() { return new org.joda.time.Interval(start.toDateTimeAtStartOfDay(), end.toDateTimeAtStartOfDay()); } @Override boolean isDisabledEditionOn(DetailItem item) { return !intervalAllowed().overlaps( new org.joda.time.Interval(item.getStartDate(), item .getEndDate())); } @Override public boolean isInvalidTotalEffort(EffortDuration totalEffort) { return false; } @Override LocalDate limitEndDate(LocalDate argEnd) { return end.compareTo(argEnd) < 0 ? end : argEnd; } @Override LocalDate limitStartDate(LocalDate argStart) { return start.compareTo(argStart) > 0 ? start : argStart; } @Override public void showInvalidEffort(IMessagesForUser messages, EffortDuration totalEffort) { throw new UnsupportedOperationException(); } @Override public void markInvalidEffort(Row groupingRow, EffortDuration currentEffort) { throw new UnsupportedOperationException(); } } private static class NoRestriction extends Restriction { @Override boolean isDisabledEditionOn(DetailItem item) { return false; } @Override public boolean isInvalidTotalEffort(EffortDuration totalEffort) { return false; } @Override LocalDate limitEndDate(LocalDate endDate) { return endDate; } @Override LocalDate limitStartDate(LocalDate startDate) { return startDate; } @Override public void markInvalidEffort(Row groupingRow, EffortDuration currentEffort) { throw new UnsupportedOperationException(); } @Override public void showInvalidEffort(IMessagesForUser messages, EffortDuration totalEffort) { throw new UnsupportedOperationException(); } } private static final int VERTICAL_MAX_ELEMENTS = 25; private IMessagesForUser messages; private Component insertionPointTimetracker; private Div insertionPointLeftPanel; private LayoutRegion insertionPointRightPanel; private Button paginationDownButton; private Button paginationUpButton; private Button verticalPaginationUpButton; private Button verticalPaginationDownButton; private TimeTracker timeTracker; private PaginatorFilter paginatorFilter; private Listbox advancedAllocationZoomLevel; private TimeTrackerComponentWithoutColumns timeTrackerComponent; private Grid leftPane; private TimeTrackedTable<Row> table; private IBack back; private List<AllocationInput> allocationInputs; private Component associatedComponent; private Listbox advancedAllocationHorizontalPagination; private Listbox advancedAllocationVerticalPagination; public AdvancedAllocationController(IBack back, List<AllocationInput> allocationInputs) { setInputData(back, allocationInputs); } private void setInputData(IBack back, List<AllocationInput> allocationInputs) { Validate.notNull(back); Validate.noNullElements(allocationInputs); this.back = back; this.allocationInputs = allocationInputs; } public void reset(IBack back, List<AllocationInput> allocationInputs) { rowsCached = null; setInputData(back, allocationInputs); loadAndInitializeComponents(); } @Override public void doAfterCompose(Component comp) throws Exception { super.doAfterCompose(comp); normalLayout = comp.getFellow("normalLayout"); noDataLayout = comp.getFellow("noDataLayout"); onlyOneVisible = new OnlyOneVisible(normalLayout, noDataLayout); this.associatedComponent = comp; loadAndInitializeComponents(); Clients.evalJavaScript("ADVANCE_ALLOCATIONS.listenToScroll();"); } private void loadAndInitializeComponents() { messages = new MessagesForUser(associatedComponent .getFellow("messages")); if (allocationInputs.isEmpty()) { onlyOneVisible.showOnly(noDataLayout); } else { onlyOneVisible.showOnly(normalLayout); createComponents(); insertComponentsInLayout(); timeTrackerComponent.afterCompose(); table.afterCompose(); } } private class PaginatorFilter implements IDetailItemFilter { private DateTime intervalStart; private DateTime intervalEnd; private DateTime paginatorStart; private DateTime paginatorEnd; private ZoomLevel zoomLevel = ZoomLevel.DETAIL_ONE; @Override public Interval getCurrentPaginationInterval() { return new Interval(intervalStart.toDate(), intervalEnd.toDate()); } private Period intervalIncrease() { switch (zoomLevel) { case DETAIL_ONE: return Period.years(5); case DETAIL_TWO: return Period.years(5); case DETAIL_THREE: return Period.years(2); case DETAIL_FOUR: return Period.months(6); case DETAIL_FIVE: return Period.weeks(6); } return Period.years(5); } public void populateHorizontalListbox() { advancedAllocationHorizontalPagination.getItems().clear(); DateTimeFormatter df = DateTimeFormat.forPattern("dd/MMM/yyyy"); if (intervalStart != null) { DateTime itemStart = intervalStart; DateTime itemEnd = intervalStart.plus(intervalIncrease()); while (intervalEnd.isAfter(itemStart)) { if (intervalEnd.isBefore(itemEnd) || !intervalEnd.isAfter(itemEnd .plus(intervalIncrease()))) { itemEnd = intervalEnd; } Listitem item = new Listitem(df.print(itemStart) + " - " + df.print(itemEnd.minusDays(1))); advancedAllocationHorizontalPagination.appendChild(item); itemStart = itemEnd; itemEnd = itemEnd.plus(intervalIncrease()); } } advancedAllocationHorizontalPagination .setDisabled(advancedAllocationHorizontalPagination .getItems().size() < 2); advancedAllocationHorizontalPagination.setSelectedIndex(0); } public void goToHorizontalPage(int interval) { if (interval >= 0) { paginatorStart = intervalStart; for (int i = 0; i < interval; i++) { paginatorStart = paginatorStart.plus(intervalIncrease()); } paginatorEnd = paginatorStart.plus(intervalIncrease()); // Avoid reduced intervals if (!intervalEnd.isAfter(paginatorEnd.plus(intervalIncrease()))) { paginatorEnd = intervalEnd; } updatePaginationButtons(); } } @Override public Collection<DetailItem> selectsFirstLevel( Collection<DetailItem> firstLevelDetails) { ArrayList<DetailItem> result = new ArrayList<DetailItem>(); for (DetailItem each : firstLevelDetails) { if ((each.getStartDate() == null) || !(each.getStartDate().isBefore(paginatorStart)) && (each.getStartDate().isBefore(paginatorEnd))) { result.add(each); } } return result; } @Override public Collection<DetailItem> selectsSecondLevel( Collection<DetailItem> secondLevelDetails) { ArrayList<DetailItem> result = new ArrayList<DetailItem>(); for (DetailItem each : secondLevelDetails) { if ((each.getStartDate() == null) || !(each.getStartDate().isBefore(paginatorStart)) && (each.getStartDate().isBefore(paginatorEnd))) { result.add(each); } } return result; } public void next() { paginatorStart = paginatorStart.plus(intervalIncrease()); paginatorEnd = paginatorEnd.plus(intervalIncrease()); // Avoid reduced last intervals if (!intervalEnd.isAfter(paginatorEnd.plus(intervalIncrease()))) { paginatorEnd = paginatorEnd.plus(intervalIncrease()); } updatePaginationButtons(); } public void previous() { paginatorStart = paginatorStart.minus(intervalIncrease()); paginatorEnd = paginatorEnd.minus(intervalIncrease()); updatePaginationButtons(); } private void updatePaginationButtons() { paginationDownButton.setDisabled(isFirstPage()); paginationUpButton.setDisabled(isLastPage()); } public boolean isFirstPage() { return !(paginatorStart.isAfter(intervalStart)); } public boolean isLastPage() { return ((paginatorEnd.isAfter(intervalEnd)) || (paginatorEnd .isEqual(intervalEnd))); } public void setZoomLevel(ZoomLevel detailLevel) { zoomLevel = detailLevel; } public void setInterval(Interval realInterval) { intervalStart = realInterval.getStart().toDateTimeAtStartOfDay(); intervalEnd = realInterval.getFinish().toDateTimeAtStartOfDay(); paginatorStart = intervalStart; paginatorEnd = intervalStart.plus(intervalIncrease()); if ((paginatorEnd.plus(intervalIncrease()).isAfter(intervalEnd))) { paginatorEnd = intervalEnd; } updatePaginationButtons(); } @Override public void resetInterval() { setInterval(timeTracker.getRealInterval()); } } private void createComponents() { timeTracker = new TimeTracker(addMarginTointerval(), self); paginatorFilter = new PaginatorFilter(); paginatorFilter.setZoomLevel(timeTracker.getDetailLevel()); paginatorFilter.setInterval(timeTracker.getRealInterval()); paginationUpButton.setDisabled(isLastPage()); advancedAllocationZoomLevel.setSelectedIndex(timeTracker .getDetailLevel().ordinal()); timeTracker.setFilter(paginatorFilter); timeTracker.addZoomListener(new IZoomLevelChangedListener() { @Override public void zoomLevelChanged(ZoomLevel detailLevel) { paginatorFilter.setZoomLevel(detailLevel); paginatorFilter.setInterval(timeTracker.getRealInterval()); timeTracker.setFilter(paginatorFilter); populateHorizontalListbox(); Clients.evalJavaScript("ADVANCE_ALLOCATIONS.listenToScroll();"); } }); timeTrackerComponent = new TimeTrackerComponentWithoutColumns( timeTracker, "timetrackerheader"); timeTrackedTableWithLeftPane = new TimeTrackedTableWithLeftPane<Row, Row>( getDataSource(), getColumnsForLeft(), getLeftRenderer(), getRightRenderer(), timeTracker); table = timeTrackedTableWithLeftPane.getRightPane(); table.setSclass("timeTrackedTableWithLeftPane"); leftPane = timeTrackedTableWithLeftPane.getLeftPane(); leftPane.setFixedLayout(true); Clients.evalJavaScript("ADVANCE_ALLOCATIONS.listenToScroll();"); populateHorizontalListbox(); } public void paginationDown() { paginatorFilter.previous(); reloadComponent(); advancedAllocationHorizontalPagination .setSelectedIndex(advancedAllocationHorizontalPagination .getSelectedIndex() - 1); } public void paginationUp() { paginatorFilter.next(); reloadComponent(); advancedAllocationHorizontalPagination.setSelectedIndex(Math.max(0, advancedAllocationHorizontalPagination.getSelectedIndex()) + 1); } public void goToSelectedHorizontalPage() { paginatorFilter .goToHorizontalPage(advancedAllocationHorizontalPagination .getSelectedIndex()); reloadComponent(); } private void populateHorizontalListbox() { advancedAllocationHorizontalPagination.setVisible(true); paginatorFilter.populateHorizontalListbox(); } private void reloadComponent() { timeTrackedTableWithLeftPane.reload(); timeTrackerComponent.recreate(); // Reattach listener for zoomLevel changes. May be optimized timeTracker.addZoomListener(new IZoomLevelChangedListener() { @Override public void zoomLevelChanged(ZoomLevel detailLevel) { paginatorFilter.setZoomLevel(detailLevel); paginatorFilter.setInterval(timeTracker.getRealInterval()); timeTracker.setFilter(paginatorFilter); populateHorizontalListbox(); Clients.evalJavaScript("ADVANCE_ALLOCATIONS.listenToScroll();"); } }); Clients.evalJavaScript("ADVANCE_ALLOCATIONS.listenToScroll();"); } public boolean isFirstPage() { return paginatorFilter.isFirstPage(); } public boolean isLastPage() { return paginatorFilter.isLastPage(); } private void insertComponentsInLayout() { insertionPointRightPanel.getChildren().clear(); insertionPointRightPanel.appendChild(table); insertionPointLeftPanel.getChildren().clear(); insertionPointLeftPanel.appendChild(leftPane); insertionPointTimetracker.getChildren().clear(); insertionPointTimetracker.appendChild(timeTrackerComponent); } public void onClick$acceptButton() { for (AllocationInput allocationInput : allocationInputs) { EffortDuration totalEffort = allocationInput.getTotalEffort(); Restriction restriction = allocationInput.getResultReceiver() .createRestriction(); if (restriction.isInvalidTotalEffort(totalEffort)) { Row groupingRow = groupingRows.get(allocationInput); restriction.markInvalidEffort(groupingRow, totalEffort); } } back.goBack(); for (AllocationInput allocationInput : allocationInputs) { allocationInput.getResultReceiver().accepted(allocationInput .getAggregate()); } } public void onClick$saveButton() { for (AllocationInput allocationInput : allocationInputs) { EffortDuration totalEffort = allocationInput.getTotalEffort(); Restriction restriction = allocationInput.getResultReceiver() .createRestriction(); if (restriction.isInvalidTotalEffort(totalEffort)) { Row groupingRow = groupingRows.get(allocationInput); restriction.markInvalidEffort(groupingRow, totalEffort); } } for (AllocationInput allocationInput : allocationInputs) { allocationInput.getResultReceiver().accepted( allocationInput.getAggregate()); } try { Messagebox.show(_("Changes applied"), _("Information"), Messagebox.OK, Messagebox.INFORMATION); } catch (InterruptedException e) { throw new RuntimeException(e); } } public void onClick$cancelButton() { back.goBack(); for (AllocationInput allocationInput : allocationInputs) { allocationInput.getResultReceiver().cancel(); } } public ListModel getZoomLevels() { ZoomLevel[] selectableZoomlevels = { ZoomLevel.DETAIL_ONE, ZoomLevel.DETAIL_TWO, ZoomLevel.DETAIL_THREE, ZoomLevel.DETAIL_FOUR, ZoomLevel.DETAIL_FIVE }; return new SimpleListModel(selectableZoomlevels); } public void setZoomLevel(final ZoomLevel zoomLevel) { timeTracker.setZoomLevel(zoomLevel); } public void onClick$zoomIncrease() { timeTracker.zoomIncrease(); } public void onClick$zoomDecrease() { timeTracker.zoomDecrease(); } private List<Row> rowsCached = null; private Map<AllocationInput, Row> groupingRows = new HashMap<AllocationInput, Row>(); private OnlyOneVisible onlyOneVisible; private Component normalLayout; private Component noDataLayout; private TimeTrackedTableWithLeftPane<Row, Row> timeTrackedTableWithLeftPane; private int verticalIndex = 0; private List<Integer> verticalPaginationIndexes; private int verticalPage; private List<Row> getRows() { if (rowsCached != null) { return filterRows(rowsCached); } rowsCached = new ArrayList<Row>(); int position = 1; for (AllocationInput allocationInput : allocationInputs) { if (allocationInput.getAggregate() .getAllocationsSortedByStartDate().isEmpty()) { } else { Row groupingRow = buildGroupingRow(allocationInput); groupingRow.setDescription(position + " " + allocationInput.getTaskName()); groupingRows.put(allocationInput, groupingRow); rowsCached.add(groupingRow); List<Row> genericRows = genericRows(allocationInput); groupingRow.listenTo(genericRows); rowsCached.addAll(genericRows); List<Row> specificRows = specificRows(allocationInput); groupingRow.listenTo(specificRows); rowsCached.addAll(specificRows); position++; } } populateVerticalListbox(); return filterRows(rowsCached); } private List<Row> filterRows(List<Row> rows) { verticalPaginationUpButton.setDisabled(verticalIndex <= 0); verticalPaginationDownButton .setDisabled((verticalIndex + VERTICAL_MAX_ELEMENTS) >= rows .size()); if(advancedAllocationVerticalPagination.getChildren().size() >= 2) { advancedAllocationVerticalPagination.setDisabled(false); advancedAllocationVerticalPagination.setSelectedIndex( verticalPage); } else { advancedAllocationVerticalPagination.setDisabled(true); } return rows.subList(verticalIndex, verticalPage + 1 < verticalPaginationIndexes.size() ? verticalPaginationIndexes.get(verticalPage + 1).intValue() : rows.size()); } public void verticalPagedown() { verticalPage++; verticalIndex = verticalPaginationIndexes.get(verticalPage); timeTrackedTableWithLeftPane.reload(); } public void setVerticalPagedownButtonDisabled(boolean disabled) { verticalPaginationUpButton.setDisabled(disabled); } public void verticalPageup() { verticalPage--; verticalIndex = verticalPaginationIndexes.get(verticalPage); timeTrackedTableWithLeftPane.reload(); } public void goToSelectedVerticalPage() { verticalPage = advancedAllocationVerticalPagination. getSelectedIndex(); verticalIndex = verticalPaginationIndexes.get(verticalPage); timeTrackedTableWithLeftPane.reload(); } public void populateVerticalListbox() { if (rowsCached != null) { verticalPaginationIndexes = new ArrayList<Integer>(); advancedAllocationVerticalPagination.getChildren().clear(); for(int i=0; i<rowsCached.size(); i= correctVerticalPageDownPosition(i+VERTICAL_MAX_ELEMENTS)) { int endPosition = correctVerticalPageUpPosition(Math.min( rowsCached.size(), i+VERTICAL_MAX_ELEMENTS) - 1); String label = rowsCached.get(i).getDescription() + " - " + rowsCached.get(endPosition).getDescription(); Listitem item = new Listitem(); item.appendChild(new Listcell(label)); advancedAllocationVerticalPagination.appendChild(item); verticalPaginationIndexes.add(i); } if (!rowsCached.isEmpty()) { advancedAllocationVerticalPagination.setSelectedIndex(0); } } } private int correctVerticalPageUpPosition(int position) { int correctedPosition = position; //moves the pointer up until it finds the previous grouping row //or the beginning of the list while(correctedPosition > 0 && !rowsCached.get(correctedPosition).isGroupingRow()) { correctedPosition--; } return correctedPosition; } private int correctVerticalPageDownPosition(int position) { int correctedPosition = position; //moves the pointer down until it finds the next grouping row //or the end of the list while(correctedPosition < rowsCached.size() && !rowsCached.get(correctedPosition).isGroupingRow()) { correctedPosition++; } return correctedPosition; } private List<Row> specificRows(AllocationInput allocationInput) { List<Row> result = new ArrayList<Row>(); for (SpecificResourceAllocation specificResourceAllocation : allocationInput.getAggregate() .getSpecificAllocations()) { result.add(createSpecificRow(specificResourceAllocation, allocationInput.getResultReceiver().createRestriction(), allocationInput.task)); } return result; } private Row createSpecificRow( SpecificResourceAllocation specificResourceAllocation, Restriction restriction, TaskElement task) { return Row.createRow(messages, restriction, specificResourceAllocation.getResource() .getName(), 1, Arrays .asList(specificResourceAllocation), specificResourceAllocation .getResource().getShortDescription(), specificResourceAllocation.getResource().isLimitingResource(), task); } private List<Row> genericRows(AllocationInput allocationInput) { List<Row> result = new ArrayList<Row>(); for (GenericResourceAllocation genericResourceAllocation : allocationInput.getAggregate() .getGenericAllocations()) { result.add(buildGenericRow(genericResourceAllocation, allocationInput.getResultReceiver().createRestriction(), allocationInput.task)); } return result; } private Row buildGenericRow( GenericResourceAllocation genericResourceAllocation, Restriction restriction, TaskElement task) { return Row.createRow(messages, restriction, Criterion .getCaptionFor(genericResourceAllocation.getCriterions()), 1, Arrays .asList(genericResourceAllocation), genericResourceAllocation .isLimiting(), task); } private Row buildGroupingRow(AllocationInput allocationInput) { Restriction restriction = allocationInput.getResultReceiver() .createRestriction(); String taskName = allocationInput.getTaskName(); Row groupingRow = Row.createRow(messages, restriction, taskName, 0, allocationInput.getAllocationsSortedByStartDate(), false, allocationInput.task); return groupingRow; } private ICellForDetailItemRenderer<ColumnOnRow, Row> getLeftRenderer() { return new ICellForDetailItemRenderer<ColumnOnRow, Row>() { @Override public Component cellFor(ColumnOnRow column, Row row) { return column.cellFor(row); } }; } private List<ColumnOnRow> getColumnsForLeft() { List<ColumnOnRow> result = new ArrayList<ColumnOnRow>(); result.add(new ColumnOnRow(_("Name")) { @Override public Component cellFor(Row row) { return row.getNameLabel(); } }); result.add(new ColumnOnRow(_("Efforts"), "50px") { @Override public Component cellFor(Row row) { return row.getAllEffort(); } }); result.add(new ColumnOnRow(_("Function"), "130px") { @Override public Component cellFor(Row row) { return row.getFunction(); } }); return result; } private Callable<PairOfLists<Row, Row>> getDataSource() { return new Callable<PairOfLists<Row, Row>>() { @Override public PairOfLists<Row, Row> call() { List<Row> rows = getRows(); return new PairOfLists<Row, Row>(rows, rows); } }; } private ICellForDetailItemRenderer<DetailItem, Row> getRightRenderer() { return new ICellForDetailItemRenderer<DetailItem, Row>() { @Override public Component cellFor(DetailItem item, Row data) { return data.effortOnInterval(item); } }; } private Interval intervalFromData() { Interval result = null; for (AllocationInput each : allocationInputs) { Interval intervalForInput = each.calculateInterval(); result = result == null ? intervalForInput : result .coalesce(intervalForInput); } return result; } private Interval addMarginTointerval() { Interval interval = intervalFromData(); // No global margin is added by default return interval; } public boolean isAdvancedAllocationOfSingleTask() { return back.isAdvanceAssignmentOfSingleTask(); } } abstract class ColumnOnRow implements IConvertibleToColumn { private final String columnName; private String width = null; ColumnOnRow(String columnName) { this.columnName = columnName; } ColumnOnRow(String columnName, String width) { this.columnName = columnName; this.width = width; } public abstract Component cellFor(Row row); @Override public Column toColumn() { Column column = new org.zkoss.zul.Column(); column.setLabel(_(columnName)); column.setSclass(columnName.toLowerCase()); if (width != null) { column.setWidth(width); } return column; } public String getName() { return columnName; } } interface CellChangedListener { public void changeOn(DetailItem detailItem); public void changeOnGlobal(); } class Row { static Row createRow(IMessagesForUser messages, AdvancedAllocationController.Restriction restriction, String name, int level, List<? extends ResourceAllocation<?>> allocations, String description, boolean limiting, TaskElement task) { Row newRow = new Row(messages, restriction, name, level, allocations, limiting, task); newRow.setDescription(description); return newRow; } static Row createRow(IMessagesForUser messages, AdvancedAllocationController.Restriction restriction, String name, int level, List<? extends ResourceAllocation<?>> allocations, boolean limiting, TaskElement task) { return new Row(messages, restriction, name, level, allocations, limiting, task); } public void markErrorOnTotal(String message) { throw new WrongValueException(allEffortInput, message); } private EffortDurationBox allEffortInput; private Label nameLabel; private List<CellChangedListener> listeners = new ArrayList<CellChangedListener>(); private Map<DetailItem, Component> componentsByDetailItem = new WeakHashMap<DetailItem, Component>(); private String name; private String description; private int level; private final AggregateOfResourceAllocations aggregate; private final AdvancedAllocationController.Restriction restriction; private final IMessagesForUser messages; private final String functionName; private TaskElement task; void listenTo(Collection<Row> rows) { for (Row row : rows) { listenTo(row); } } void listenTo(Row row) { row.add(new CellChangedListener() { @Override public void changeOnGlobal() { reloadAllEffort(); reloadEffortsSameRowForDetailItems(); } @Override public void changeOn(DetailItem detailItem) { Component component = componentsByDetailItem.get(detailItem); if (component == null) { return; } reloadEffortOnInterval(component, detailItem); reloadAllEffort(); } }); } void add(CellChangedListener listener) { listeners.add(listener); } private void fireCellChanged(DetailItem detailItem) { for (CellChangedListener cellChangedListener : listeners) { cellChangedListener.changeOn(detailItem); } } private void fireCellChanged() { for (CellChangedListener cellChangedListener : listeners) { cellChangedListener.changeOnGlobal(); } } Component getAllEffort() { if (allEffortInput == null) { allEffortInput = buildSumAllEffort(); reloadAllEffort(); addListenerIfNeeded(allEffortInput); } return allEffortInput; } private EffortDurationBox buildSumAllEffort() { EffortDurationBox box = (isGroupingRow() || isLimiting) ? EffortDurationBox .notEditable() : new EffortDurationBox(); box.setWidth("40px"); return box; } private void addListenerIfNeeded(Component allEffortComponent) { if (isGroupingRow() || isLimiting) { return; } final EffortDurationBox effortDurationBox = (EffortDurationBox) allEffortComponent; effortDurationBox.addEventListener(Events.ON_CHANGE, new EventListener() { @Override public void onEvent(Event event) { EffortDuration value = effortDurationBox .getEffortDurationValue(); ResourceAllocation<?> resourceAllocation = getAllocation(); resourceAllocation .withPreviousAssociatedResources() .onIntervalWithinTask( resourceAllocation.getStartDate(), resourceAllocation.getEndDate()) .allocate(value); AssignmentFunction assignmentFunction = resourceAllocation.getAssignmentFunction(); if (assignmentFunction != null) { assignmentFunction.applyTo(resourceAllocation); } fireCellChanged(); reloadEffortsSameRowForDetailItems(); reloadAllEffort(); } }); } private void reloadEffortsSameRowForDetailItems() { for (Entry<DetailItem, Component> entry : componentsByDetailItem .entrySet()) { reloadEffortOnInterval(entry.getValue(), entry.getKey()); } } private void reloadAllEffort() { if (allEffortInput == null) { return; } EffortDuration allEffort = aggregate.getTotalEffort(); allEffortInput.setValue(allEffort); Clients.closeErrorBox(allEffortInput); if (isLimiting) { allEffortInput.setDisabled(true); } if (restriction.isInvalidTotalEffort(allEffort)) { restriction.showInvalidEffort(messages, allEffort); } } private Hbox hboxAssigmentFunctionsCombo = null; Component getFunction() { if (isGroupingRow()) { return new Label(); } else if (isLimiting) { return new Label(_("Limiting assignment")); } else { if (hboxAssigmentFunctionsCombo == null) { initializeAssigmentFunctionsCombo(); } return hboxAssigmentFunctionsCombo; } } private AssignmentFunctionListbox assignmentFunctionsCombo = null; private Button assignmentFunctionsConfigureButton = null; private void initializeAssigmentFunctionsCombo() { hboxAssigmentFunctionsCombo = new Hbox(); assignmentFunctionsCombo = new AssignmentFunctionListbox( functions, getAllocation().getAssignmentFunction()); hboxAssigmentFunctionsCombo.appendChild(assignmentFunctionsCombo); assignmentFunctionsConfigureButton = getAssignmentFunctionsConfigureButton(assignmentFunctionsCombo); hboxAssigmentFunctionsCombo.appendChild(assignmentFunctionsConfigureButton); } /** * @author Diego Pino García <[email protected]> * * Encapsulates the logic of the combobox used for selecting what * type of assignment function to apply */ class AssignmentFunctionListbox extends Listbox { private Listitem previousListitem; public AssignmentFunctionListbox(IAssignmentFunctionConfiguration[] functions, AssignmentFunction initialValue) { for (IAssignmentFunctionConfiguration each : functions) { Listitem listitem = listItem(each); this.appendChild(listitem); if (each.isTargetedTo(initialValue)) { selectItemAndSavePreviousValue(listitem); } } this.addEventListener(Events.ON_SELECT, onSelectListbox()); this.setMold("select"); } private void selectItemAndSavePreviousValue(Listitem listitem) { setSelectedItem(listitem); previousListitem = listitem; } private Listitem listItem( IAssignmentFunctionConfiguration assignmentFunction) { Listitem listitem = new Listitem(_(assignmentFunction.getName())); listitem.setValue(assignmentFunction); return listitem; } private EventListener onSelectListbox() { return new EventListener() { @Override public void onEvent(Event event) throws Exception { IAssignmentFunctionConfiguration function = (IAssignmentFunctionConfiguration) getSelectedItem() .getValue(); // Cannot apply function if task contains consolidated day assignments final ResourceAllocation<?> resourceAllocation = getAllocation(); if (function.isSigmoid() && !resourceAllocation .getConsolidatedAssignments().isEmpty()) { showCannotApplySigmoidFunction(); setSelectedItem(getPreviousListitem()); return; } // User didn't accept if (showConfirmChangeFunctionDialog() != Messagebox.YES) { setSelectedItem(getPreviousListitem()); return; } // Apply assignment function if (function != null) { setPreviousListitem(getSelectedItem()); function.applyOn(resourceAllocation); updateAssignmentFunctionsConfigureButton( assignmentFunctionsConfigureButton, function.isConfigurable()); } } }; } private Listitem getPreviousListitem() { return previousListitem; } private void setPreviousListitem(Listitem previousListitem) { this.previousListitem = previousListitem; } private void showCannotApplySigmoidFunction() { try { Messagebox .show(_("Task contains consolidated progress. Cannot apply sigmoid function."), _("Error"), Messagebox.OK, Messagebox.ERROR); } catch (InterruptedException e) { throw new RuntimeException(e); } } private int showConfirmChangeFunctionDialog() throws InterruptedException { return Messagebox .show(_("You are going to change the assignment function. Are you sure?"), _("Confirm change"), Messagebox.YES | Messagebox.NO, Messagebox.QUESTION); } private void setSelectedFunction(String functionName) { List<Listitem> children = getChildren(); for (Listitem item : children) { IAssignmentFunctionConfiguration function = (IAssignmentFunctionConfiguration) item .getValue(); if (function.getName().equals(functionName)) { setSelectedItem(item); } } } } private IAssignmentFunctionConfiguration flat = new IAssignmentFunctionConfiguration() { @Override public void goToConfigure() { throw new UnsupportedOperationException( "Flat allocation is not configurable"); } @Override public String getName() { return AssignmentFunctionName.FLAT.toString(); } @Override public boolean isTargetedTo(AssignmentFunction function) { return function == null; } @Override public void applyOn( ResourceAllocation<?> resourceAllocation) { resourceAllocation.setAssignmentFunctionWithoutApply(null); resourceAllocation .withPreviousAssociatedResources() .onIntervalWithinTask(resourceAllocation.getStartDate(), resourceAllocation.getEndDate()) .allocate(allEffortInput.getEffortDurationValue()); reloadEfforts(); } private void reloadEfforts() { reloadEffortsSameRowForDetailItems(); reloadAllEffort(); fireCellChanged(); } @Override public boolean isSigmoid() { return false; } @Override public boolean isConfigurable() { return false; } }; private IAssignmentFunctionConfiguration manualFunction = new IAssignmentFunctionConfiguration() { @Override public void goToConfigure() { throw new UnsupportedOperationException( "Manual allocation is not configurable"); } @Override public String getName() { return AssignmentFunctionName.MANUAL.toString(); } @Override public boolean isTargetedTo(AssignmentFunction function) { return function instanceof ManualFunction; } @Override public void applyOn(ResourceAllocation<?> resourceAllocation) { resourceAllocation.setAssignmentFunctionAndApplyIfNotFlat(ManualFunction.create()); } @Override public boolean isSigmoid() { return false; } @Override public boolean isConfigurable() { return false; } }; private abstract class CommonStrechesConfiguration extends StrechesFunctionConfiguration { @Override protected void assignmentFunctionChanged() { reloadEffortsSameRowForDetailItems(); reloadAllEffort(); fireCellChanged(); } @Override protected ResourceAllocation<?> getAllocation() { return Row.this.getAllocation(); } @Override protected Component getParentOnWhichOpenWindow() { return allEffortInput.getParent(); } } private IAssignmentFunctionConfiguration defaultStrechesFunction = new CommonStrechesConfiguration() { @Override protected String getTitle() { return _("Stretches list"); } @Override protected boolean getChartsEnabled() { return true; } @Override protected StretchesFunctionTypeEnum getType() { return StretchesFunctionTypeEnum.STRETCHES; } @Override public String getName() { return AssignmentFunctionName.STRETCHES.toString(); } }; private IAssignmentFunctionConfiguration strechesWithInterpolation = new CommonStrechesConfiguration() { @Override protected String getTitle() { return _("Stretches with Interpolation"); } @Override protected boolean getChartsEnabled() { return false; } @Override protected StretchesFunctionTypeEnum getType() { return StretchesFunctionTypeEnum.INTERPOLATED; } @Override public String getName() { return AssignmentFunctionName.INTERPOLATION.toString(); } }; private IAssignmentFunctionConfiguration sigmoidFunction = new IAssignmentFunctionConfiguration() { @Override public void goToConfigure() { throw new UnsupportedOperationException( "Sigmoid function is not configurable"); } @Override public String getName() { return AssignmentFunctionName.SIGMOID.toString(); } @Override public boolean isTargetedTo(AssignmentFunction function) { return function instanceof SigmoidFunction; } @Override public void applyOn( ResourceAllocation<?> resourceAllocation) { resourceAllocation.setAssignmentFunctionAndApplyIfNotFlat(SigmoidFunction.create()); reloadEfforts(); } private void reloadEfforts() { reloadEffortsSameRowForDetailItems(); reloadAllEffort(); fireCellChanged(); } @Override public boolean isSigmoid() { return true; } @Override public boolean isConfigurable() { return false; } }; private IAssignmentFunctionConfiguration[] functions = { flat, manualFunction, defaultStrechesFunction, strechesWithInterpolation, sigmoidFunction }; private boolean isLimiting; private Button getAssignmentFunctionsConfigureButton( final Listbox assignmentFunctionsListbox) { Button button = Util.createEditButton(new EventListener() { @Override public void onEvent(Event event) { IAssignmentFunctionConfiguration configuration = (IAssignmentFunctionConfiguration) assignmentFunctionsListbox .getSelectedItem().getValue(); configuration.goToConfigure(); } }); IAssignmentFunctionConfiguration configuration = (IAssignmentFunctionConfiguration) assignmentFunctionsListbox .getSelectedItem().getValue(); updateAssignmentFunctionsConfigureButton(button, configuration.isConfigurable()); return button; } private void updateAssignmentFunctionsConfigureButton(Button button, boolean configurable) { if (configurable) { button.setTooltiptext(_("Configure")); button.setDisabled(false); } else { button.setTooltiptext(_("Not configurable")); button.setDisabled(true); } } Component getNameLabel() { if (nameLabel == null) { nameLabel = new Label(); nameLabel.setValue(name); if (!StringUtils.isBlank(description)) { nameLabel.setTooltiptext(description); } else { nameLabel.setTooltiptext(name); } nameLabel.setSclass("level" + level); } return nameLabel; } private Row(IMessagesForUser messages, AdvancedAllocationController.Restriction restriction, String name, int level, List<? extends ResourceAllocation<?>> allocations, boolean limiting, TaskElement task) { this.messages = messages; this.restriction = restriction; this.name = name; this.level = level; this.isLimiting = limiting; this.task = task; this.aggregate = AggregateOfResourceAllocations .createFromSatisfied(new ArrayList<ResourceAllocation<?>>(allocations)); this.functionName = getAssignmentFunctionName(allocations); } private String getAssignmentFunctionName( List<? extends ResourceAllocation<?>> allocations) { AssignmentFunction function = getAssignmentFunction(allocations); return (function != null) ? function.getName() : AssignmentFunctionName.FLAT.toString(); } private AssignmentFunction getAssignmentFunction( List<? extends ResourceAllocation<?>> allocations) { if (allocations != null) { ResourceAllocation<?> allocation = allocations.iterator().next(); return allocation.getAssignmentFunction(); } return null; } private EffortDuration getEffortForDetailItem(DetailItem item) { DateTime startDate = item.getStartDate(); DateTime endDate = item.getEndDate(); return this.aggregate.effortBetween(startDate.toLocalDate(), endDate .toLocalDate()); } Component effortOnInterval(DetailItem item) { Component result = cannotBeEdited(item) ? new Label() : disableIfNeeded(item, new EffortDurationBox()); reloadEffortOnInterval(result, item); componentsByDetailItem.put(item, result); addListenerIfNeeded(item, result); return result; } private boolean cannotBeEdited(DetailItem item) { return isGroupingRow() || doesNotIntersectWithTask(item) || isBeforeLatestConsolidation(item); } private EffortDurationBox disableIfNeeded(DetailItem item, EffortDurationBox effortDurationBox) { effortDurationBox.setDisabled(restriction.isDisabledEditionOn(item)); return effortDurationBox; } private void addListenerIfNeeded(final DetailItem item, final Component component) { if (cannotBeEdited(item)) { return; } final EffortDurationBox effortBox = (EffortDurationBox) component; component.addEventListener(Events.ON_CHANGE, new EventListener() { @Override public void onEvent(Event event) { EffortDuration value = effortBox.getEffortDurationValue(); LocalDate startDate = restriction.limitStartDate(item .getStartDate().toLocalDate()); LocalDate endDate = restriction.limitEndDate(item.getEndDate() .toLocalDate()); changeAssignmentFunctionToManual(); getAllocation().withPreviousAssociatedResources() .onIntervalWithinTask(startDate, endDate) .allocate(value); fireCellChanged(item); effortBox.setRawValue(getEffortForDetailItem(item)); reloadAllEffort(); } }); } private void changeAssignmentFunctionToManual() { assignmentFunctionsCombo .setSelectedFunction(AssignmentFunctionName.MANUAL.toString()); ResourceAllocation<?> allocation = getAllocation(); if (!(allocation.getAssignmentFunction() instanceof ManualFunction)) { allocation.setAssignmentFunctionAndApplyIfNotFlat(ManualFunction.create()); } } private void reloadEffortOnInterval(Component component, DetailItem item) { if (cannotBeEdited(item)) { Label label = (Label) component; label.setValue(getEffortForDetailItem(item).toFormattedString()); label.setClass(getLabelClassFor(item)); } else { EffortDurationBox effortDurationBox = (EffortDurationBox) component; effortDurationBox.setValue(getEffortForDetailItem(item)); if (isLimiting) { effortDurationBox.setDisabled(true); effortDurationBox.setSclass(" limiting"); } } } private String getLabelClassFor(DetailItem item) { if (isGroupingRow()) { return "calculated-hours"; } if (doesNotIntersectWithTask(item)) { return "unmodifiable-hours"; } if (isBeforeLatestConsolidation(item)) { return "consolidated-hours"; } return ""; } private boolean doesNotIntersectWithTask(DetailItem item) { return isBeforeTaskStartDate(item) || isAfterTaskEndDate(item); } private boolean isBeforeTaskStartDate(DetailItem item) { return task.getIntraDayStartDate().compareTo( item.getEndDate().toLocalDate()) >= 0; } private boolean isAfterTaskEndDate(DetailItem item) { return task.getIntraDayEndDate().compareTo( item.getStartDate().toLocalDate()) <= 0; } private boolean isBeforeLatestConsolidation(DetailItem item) { if(!((Task)task).hasConsolidations()) { return false; } LocalDate d = ((Task) task).getFirstDayNotConsolidated().getDate(); DateTime firstDayNotConsolidated = new DateTime(d.getYear(), d.getMonthOfYear(), d.getDayOfMonth(), 0, 0, 0, 0); return item.getStartDate().compareTo(firstDayNotConsolidated) < 0; } private ResourceAllocation<?> getAllocation() { if (isGroupingRow()) { throw new IllegalStateException("is grouping row"); } return aggregate.getAllocationsSortedByStartDate().get(0); } public boolean isGroupingRow() { return level == 0; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
navalplanner-webapp/src/main/java/org/navalplanner/web/planner/allocation/AdvancedAllocationController.java
/* * This file is part of NavalPlan * * Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e * Desenvolvemento Tecnolóxico de Galicia * Copyright (C) 2010-2011 Igalia, S.L. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.navalplanner.web.planner.allocation; import static org.navalplanner.web.I18nHelper._; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.WeakHashMap; import java.util.concurrent.Callable; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.joda.time.Period; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.navalplanner.business.planner.entities.AggregateOfResourceAllocations; import org.navalplanner.business.planner.entities.AssignmentFunction; import org.navalplanner.business.planner.entities.AssignmentFunction.AssignmentFunctionName; import org.navalplanner.business.planner.entities.CalculatedValue; import org.navalplanner.business.planner.entities.GenericResourceAllocation; import org.navalplanner.business.planner.entities.ManualFunction; import org.navalplanner.business.planner.entities.ResourceAllocation; import org.navalplanner.business.planner.entities.SigmoidFunction; import org.navalplanner.business.planner.entities.SpecificResourceAllocation; import org.navalplanner.business.planner.entities.StretchesFunctionTypeEnum; import org.navalplanner.business.planner.entities.Task; import org.navalplanner.business.planner.entities.TaskElement; import org.navalplanner.business.resources.entities.Criterion; import org.navalplanner.business.workingday.EffortDuration; import org.navalplanner.web.common.EffortDurationBox; import org.navalplanner.web.common.IMessagesForUser; import org.navalplanner.web.common.MessagesForUser; import org.navalplanner.web.common.OnlyOneVisible; import org.navalplanner.web.common.Util; import org.navalplanner.web.planner.allocation.streches.StrechesFunctionConfiguration; import org.zkoss.ganttz.timetracker.ICellForDetailItemRenderer; import org.zkoss.ganttz.timetracker.IConvertibleToColumn; import org.zkoss.ganttz.timetracker.PairOfLists; import org.zkoss.ganttz.timetracker.TimeTrackedTable; import org.zkoss.ganttz.timetracker.TimeTrackedTableWithLeftPane; import org.zkoss.ganttz.timetracker.TimeTracker; import org.zkoss.ganttz.timetracker.TimeTracker.IDetailItemFilter; import org.zkoss.ganttz.timetracker.TimeTrackerComponentWithoutColumns; import org.zkoss.ganttz.timetracker.zoom.DetailItem; import org.zkoss.ganttz.timetracker.zoom.IZoomLevelChangedListener; import org.zkoss.ganttz.timetracker.zoom.ZoomLevel; import org.zkoss.ganttz.util.Interval; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.WrongValueException; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.event.Events; import org.zkoss.zk.ui.util.Clients; import org.zkoss.zk.ui.util.GenericForwardComposer; import org.zkoss.zul.Button; import org.zkoss.zul.Div; import org.zkoss.zul.Grid; import org.zkoss.zul.Hbox; import org.zkoss.zul.Label; import org.zkoss.zul.LayoutRegion; import org.zkoss.zul.ListModel; import org.zkoss.zul.Listbox; import org.zkoss.zul.Listcell; import org.zkoss.zul.Listitem; import org.zkoss.zul.Messagebox; import org.zkoss.zul.SimpleListModel; import org.zkoss.zul.api.Column; /** * * @author Óscar González Fernández <[email protected]> * @author Diego Pino García <[email protected]> * */ public class AdvancedAllocationController extends GenericForwardComposer { public static class AllocationInput { private final AggregateOfResourceAllocations aggregate; private final IAdvanceAllocationResultReceiver resultReceiver; private final TaskElement task; public AllocationInput(AggregateOfResourceAllocations aggregate, TaskElement task, IAdvanceAllocationResultReceiver resultReceiver) { Validate.notNull(aggregate); Validate.notNull(resultReceiver); Validate.notNull(task); this.aggregate = aggregate; this.task = task; this.resultReceiver = resultReceiver; } List<ResourceAllocation<?>> getAllocationsSortedByStartDate() { return getAggregate().getAllocationsSortedByStartDate(); } EffortDuration getTotalEffort() { return getAggregate().getTotalEffort(); } AggregateOfResourceAllocations getAggregate() { return aggregate; } String getTaskName() { return task.getName(); } IAdvanceAllocationResultReceiver getResultReceiver() { return resultReceiver; } Interval calculateInterval() { List<ResourceAllocation<?>> all = getAllocationsSortedByStartDate(); if (all.isEmpty()) { return new Interval(task.getStartDate(), task .getEndDate()); } else { LocalDate start = min(all.get(0) .getStartConsideringAssignments(), all.get(0) .getStartDate()); LocalDate taskEndDate = LocalDate.fromDateFields(task .getEndDate()); LocalDate end = max(getEnd(all), taskEndDate); return new Interval(asDate(start), asDate(end)); } } private LocalDate min(LocalDate... dates) { return Collections.min(Arrays.asList(dates), null); } private LocalDate max(LocalDate... dates) { return Collections.max(Arrays.asList(dates), null); } private static LocalDate getEnd(List<ResourceAllocation<?>> all) { ArrayList<ResourceAllocation<?>> reversed = reverse(all); LocalDate end = reversed.get(0).getEndDate(); ListIterator<ResourceAllocation<?>> listIterator = reversed .listIterator(1); while (listIterator.hasNext()) { ResourceAllocation<?> current = listIterator.next(); if (current.getEndDate().compareTo(end) >= 0) { end = current.getEndDate(); } else { return end; } } return end; } private static ArrayList<ResourceAllocation<?>> reverse( List<ResourceAllocation<?>> all) { ArrayList<ResourceAllocation<?>> reversed = new ArrayList<ResourceAllocation<?>>( all); Collections.reverse(reversed); return reversed; } private static Date asDate(LocalDate start) { return start.toDateMidnight().toDate(); } } public interface IAdvanceAllocationResultReceiver { public Restriction createRestriction(); public void accepted(AggregateOfResourceAllocations modifiedAllocations); public void cancel(); } public interface IBack { public void goBack(); boolean isAdvanceAssignmentOfSingleTask(); } public abstract static class Restriction { public interface IRestrictionSource { EffortDuration getTotalEffort(); LocalDate getStart(); LocalDate getEnd(); CalculatedValue getCalculatedValue(); } public static Restriction build(IRestrictionSource restrictionSource) { switch (restrictionSource.getCalculatedValue()) { case END_DATE: return Restriction.emptyRestriction(); case NUMBER_OF_HOURS: return Restriction.onlyAssignOnInterval(restrictionSource .getStart(), restrictionSource.getEnd()); case RESOURCES_PER_DAY: return Restriction.emptyRestriction(); default: throw new RuntimeException("unhandled case: " + restrictionSource.getCalculatedValue()); } } private static Restriction emptyRestriction() { return new NoRestriction(); } private static Restriction onlyAssignOnInterval(LocalDate start, LocalDate end){ return new OnlyOnIntervalRestriction(start, end); } abstract LocalDate limitStartDate(LocalDate startDate); abstract LocalDate limitEndDate(LocalDate localDate); abstract boolean isDisabledEditionOn(DetailItem item); public abstract boolean isInvalidTotalEffort(EffortDuration totalEffort); public abstract void showInvalidEffort(IMessagesForUser messages, EffortDuration totalEffort); public abstract void markInvalidEffort(Row groupingRow, EffortDuration currentEffort); } private static class OnlyOnIntervalRestriction extends Restriction { private final LocalDate start; private final LocalDate end; private OnlyOnIntervalRestriction(LocalDate start, LocalDate end) { super(); this.start = start; this.end = end; } private org.joda.time.Interval intervalAllowed() { return new org.joda.time.Interval(start.toDateTimeAtStartOfDay(), end.toDateTimeAtStartOfDay()); } @Override boolean isDisabledEditionOn(DetailItem item) { return !intervalAllowed().overlaps( new org.joda.time.Interval(item.getStartDate(), item .getEndDate())); } @Override public boolean isInvalidTotalEffort(EffortDuration totalEffort) { return false; } @Override LocalDate limitEndDate(LocalDate argEnd) { return end.compareTo(argEnd) < 0 ? end : argEnd; } @Override LocalDate limitStartDate(LocalDate argStart) { return start.compareTo(argStart) > 0 ? start : argStart; } @Override public void showInvalidEffort(IMessagesForUser messages, EffortDuration totalEffort) { throw new UnsupportedOperationException(); } @Override public void markInvalidEffort(Row groupingRow, EffortDuration currentEffort) { throw new UnsupportedOperationException(); } } private static class NoRestriction extends Restriction { @Override boolean isDisabledEditionOn(DetailItem item) { return false; } @Override public boolean isInvalidTotalEffort(EffortDuration totalEffort) { return false; } @Override LocalDate limitEndDate(LocalDate endDate) { return endDate; } @Override LocalDate limitStartDate(LocalDate startDate) { return startDate; } @Override public void markInvalidEffort(Row groupingRow, EffortDuration currentEffort) { throw new UnsupportedOperationException(); } @Override public void showInvalidEffort(IMessagesForUser messages, EffortDuration totalEffort) { throw new UnsupportedOperationException(); } } private static final int VERTICAL_MAX_ELEMENTS = 25; private IMessagesForUser messages; private Component insertionPointTimetracker; private Div insertionPointLeftPanel; private LayoutRegion insertionPointRightPanel; private Button paginationDownButton; private Button paginationUpButton; private Button verticalPaginationUpButton; private Button verticalPaginationDownButton; private TimeTracker timeTracker; private PaginatorFilter paginatorFilter; private Listbox advancedAllocationZoomLevel; private TimeTrackerComponentWithoutColumns timeTrackerComponent; private Grid leftPane; private TimeTrackedTable<Row> table; private IBack back; private List<AllocationInput> allocationInputs; private Component associatedComponent; private Listbox advancedAllocationHorizontalPagination; private Listbox advancedAllocationVerticalPagination; public AdvancedAllocationController(IBack back, List<AllocationInput> allocationInputs) { setInputData(back, allocationInputs); } private void setInputData(IBack back, List<AllocationInput> allocationInputs) { Validate.notNull(back); Validate.noNullElements(allocationInputs); this.back = back; this.allocationInputs = allocationInputs; } public void reset(IBack back, List<AllocationInput> allocationInputs) { rowsCached = null; setInputData(back, allocationInputs); loadAndInitializeComponents(); } @Override public void doAfterCompose(Component comp) throws Exception { super.doAfterCompose(comp); normalLayout = comp.getFellow("normalLayout"); noDataLayout = comp.getFellow("noDataLayout"); onlyOneVisible = new OnlyOneVisible(normalLayout, noDataLayout); this.associatedComponent = comp; loadAndInitializeComponents(); Clients.evalJavaScript("ADVANCE_ALLOCATIONS.listenToScroll();"); } private void loadAndInitializeComponents() { messages = new MessagesForUser(associatedComponent .getFellow("messages")); if (allocationInputs.isEmpty()) { onlyOneVisible.showOnly(noDataLayout); } else { onlyOneVisible.showOnly(normalLayout); createComponents(); insertComponentsInLayout(); timeTrackerComponent.afterCompose(); table.afterCompose(); } } private class PaginatorFilter implements IDetailItemFilter { private DateTime intervalStart; private DateTime intervalEnd; private DateTime paginatorStart; private DateTime paginatorEnd; private ZoomLevel zoomLevel = ZoomLevel.DETAIL_ONE; @Override public Interval getCurrentPaginationInterval() { return new Interval(intervalStart.toDate(), intervalEnd.toDate()); } private Period intervalIncrease() { switch (zoomLevel) { case DETAIL_ONE: return Period.years(5); case DETAIL_TWO: return Period.years(5); case DETAIL_THREE: return Period.years(2); case DETAIL_FOUR: return Period.months(6); case DETAIL_FIVE: return Period.weeks(6); } return Period.years(5); } public void populateHorizontalListbox() { advancedAllocationHorizontalPagination.getItems().clear(); DateTimeFormatter df = DateTimeFormat.forPattern("dd/MMM/yyyy"); if (intervalStart != null) { DateTime itemStart = intervalStart; DateTime itemEnd = intervalStart.plus(intervalIncrease()); while (intervalEnd.isAfter(itemStart)) { if (intervalEnd.isBefore(itemEnd) || !intervalEnd.isAfter(itemEnd .plus(intervalIncrease()))) { itemEnd = intervalEnd; } Listitem item = new Listitem(df.print(itemStart) + " - " + df.print(itemEnd.minusDays(1))); advancedAllocationHorizontalPagination.appendChild(item); itemStart = itemEnd; itemEnd = itemEnd.plus(intervalIncrease()); } } advancedAllocationHorizontalPagination .setDisabled(advancedAllocationHorizontalPagination .getItems().size() < 2); advancedAllocationHorizontalPagination.setSelectedIndex(0); } public void goToHorizontalPage(int interval) { if (interval >= 0) { paginatorStart = intervalStart; for (int i = 0; i < interval; i++) { paginatorStart = paginatorStart.plus(intervalIncrease()); } paginatorEnd = paginatorStart.plus(intervalIncrease()); // Avoid reduced intervals if (!intervalEnd.isAfter(paginatorEnd.plus(intervalIncrease()))) { paginatorEnd = intervalEnd; } updatePaginationButtons(); } } @Override public Collection<DetailItem> selectsFirstLevel( Collection<DetailItem> firstLevelDetails) { ArrayList<DetailItem> result = new ArrayList<DetailItem>(); for (DetailItem each : firstLevelDetails) { if ((each.getStartDate() == null) || !(each.getStartDate().isBefore(paginatorStart)) && (each.getStartDate().isBefore(paginatorEnd))) { result.add(each); } } return result; } @Override public Collection<DetailItem> selectsSecondLevel( Collection<DetailItem> secondLevelDetails) { ArrayList<DetailItem> result = new ArrayList<DetailItem>(); for (DetailItem each : secondLevelDetails) { if ((each.getStartDate() == null) || !(each.getStartDate().isBefore(paginatorStart)) && (each.getStartDate().isBefore(paginatorEnd))) { result.add(each); } } return result; } public void next() { paginatorStart = paginatorStart.plus(intervalIncrease()); paginatorEnd = paginatorEnd.plus(intervalIncrease()); // Avoid reduced last intervals if (!intervalEnd.isAfter(paginatorEnd.plus(intervalIncrease()))) { paginatorEnd = paginatorEnd.plus(intervalIncrease()); } updatePaginationButtons(); } public void previous() { paginatorStart = paginatorStart.minus(intervalIncrease()); paginatorEnd = paginatorEnd.minus(intervalIncrease()); updatePaginationButtons(); } private void updatePaginationButtons() { paginationDownButton.setDisabled(isFirstPage()); paginationUpButton.setDisabled(isLastPage()); } public boolean isFirstPage() { return !(paginatorStart.isAfter(intervalStart)); } public boolean isLastPage() { return ((paginatorEnd.isAfter(intervalEnd)) || (paginatorEnd .isEqual(intervalEnd))); } public void setZoomLevel(ZoomLevel detailLevel) { zoomLevel = detailLevel; } public void setInterval(Interval realInterval) { intervalStart = realInterval.getStart().toDateTimeAtStartOfDay(); intervalEnd = realInterval.getFinish().toDateTimeAtStartOfDay(); paginatorStart = intervalStart; paginatorEnd = intervalStart.plus(intervalIncrease()); if ((paginatorEnd.plus(intervalIncrease()).isAfter(intervalEnd))) { paginatorEnd = intervalEnd; } updatePaginationButtons(); } @Override public void resetInterval() { setInterval(timeTracker.getRealInterval()); } } private void createComponents() { timeTracker = new TimeTracker(addMarginTointerval(), self); paginatorFilter = new PaginatorFilter(); paginatorFilter.setZoomLevel(timeTracker.getDetailLevel()); paginatorFilter.setInterval(timeTracker.getRealInterval()); paginationUpButton.setDisabled(isLastPage()); advancedAllocationZoomLevel.setSelectedIndex(timeTracker .getDetailLevel().ordinal()); timeTracker.setFilter(paginatorFilter); timeTracker.addZoomListener(new IZoomLevelChangedListener() { @Override public void zoomLevelChanged(ZoomLevel detailLevel) { paginatorFilter.setZoomLevel(detailLevel); paginatorFilter.setInterval(timeTracker.getRealInterval()); timeTracker.setFilter(paginatorFilter); populateHorizontalListbox(); Clients.evalJavaScript("ADVANCE_ALLOCATIONS.listenToScroll();"); } }); timeTrackerComponent = new TimeTrackerComponentWithoutColumns( timeTracker, "timetrackerheader"); timeTrackedTableWithLeftPane = new TimeTrackedTableWithLeftPane<Row, Row>( getDataSource(), getColumnsForLeft(), getLeftRenderer(), getRightRenderer(), timeTracker); table = timeTrackedTableWithLeftPane.getRightPane(); table.setSclass("timeTrackedTableWithLeftPane"); leftPane = timeTrackedTableWithLeftPane.getLeftPane(); leftPane.setFixedLayout(true); Clients.evalJavaScript("ADVANCE_ALLOCATIONS.listenToScroll();"); populateHorizontalListbox(); } public void paginationDown() { paginatorFilter.previous(); reloadComponent(); advancedAllocationHorizontalPagination .setSelectedIndex(advancedAllocationHorizontalPagination .getSelectedIndex() - 1); } public void paginationUp() { paginatorFilter.next(); reloadComponent(); advancedAllocationHorizontalPagination.setSelectedIndex(Math.max(0, advancedAllocationHorizontalPagination.getSelectedIndex()) + 1); } public void goToSelectedHorizontalPage() { paginatorFilter .goToHorizontalPage(advancedAllocationHorizontalPagination .getSelectedIndex()); reloadComponent(); } private void populateHorizontalListbox() { advancedAllocationHorizontalPagination.setVisible(true); paginatorFilter.populateHorizontalListbox(); } private void reloadComponent() { timeTrackedTableWithLeftPane.reload(); timeTrackerComponent.recreate(); // Reattach listener for zoomLevel changes. May be optimized timeTracker.addZoomListener(new IZoomLevelChangedListener() { @Override public void zoomLevelChanged(ZoomLevel detailLevel) { paginatorFilter.setZoomLevel(detailLevel); paginatorFilter.setInterval(timeTracker.getRealInterval()); timeTracker.setFilter(paginatorFilter); populateHorizontalListbox(); Clients.evalJavaScript("ADVANCE_ALLOCATIONS.listenToScroll();"); } }); Clients.evalJavaScript("ADVANCE_ALLOCATIONS.listenToScroll();"); } public boolean isFirstPage() { return paginatorFilter.isFirstPage(); } public boolean isLastPage() { return paginatorFilter.isLastPage(); } private void insertComponentsInLayout() { insertionPointRightPanel.getChildren().clear(); insertionPointRightPanel.appendChild(table); insertionPointLeftPanel.getChildren().clear(); insertionPointLeftPanel.appendChild(leftPane); insertionPointTimetracker.getChildren().clear(); insertionPointTimetracker.appendChild(timeTrackerComponent); } public void onClick$acceptButton() { for (AllocationInput allocationInput : allocationInputs) { EffortDuration totalEffort = allocationInput.getTotalEffort(); Restriction restriction = allocationInput.getResultReceiver() .createRestriction(); if (restriction.isInvalidTotalEffort(totalEffort)) { Row groupingRow = groupingRows.get(allocationInput); restriction.markInvalidEffort(groupingRow, totalEffort); } } back.goBack(); for (AllocationInput allocationInput : allocationInputs) { allocationInput.getResultReceiver().accepted(allocationInput .getAggregate()); } } public void onClick$saveButton() { for (AllocationInput allocationInput : allocationInputs) { EffortDuration totalEffort = allocationInput.getTotalEffort(); Restriction restriction = allocationInput.getResultReceiver() .createRestriction(); if (restriction.isInvalidTotalEffort(totalEffort)) { Row groupingRow = groupingRows.get(allocationInput); restriction.markInvalidEffort(groupingRow, totalEffort); } } for (AllocationInput allocationInput : allocationInputs) { allocationInput.getResultReceiver().accepted( allocationInput.getAggregate()); } try { Messagebox.show(_("Changes applied"), _("Information"), Messagebox.OK, Messagebox.INFORMATION); } catch (InterruptedException e) { throw new RuntimeException(e); } } public void onClick$cancelButton() { back.goBack(); for (AllocationInput allocationInput : allocationInputs) { allocationInput.getResultReceiver().cancel(); } } public ListModel getZoomLevels() { ZoomLevel[] selectableZoomlevels = { ZoomLevel.DETAIL_ONE, ZoomLevel.DETAIL_TWO, ZoomLevel.DETAIL_THREE, ZoomLevel.DETAIL_FOUR, ZoomLevel.DETAIL_FIVE }; return new SimpleListModel(selectableZoomlevels); } public void setZoomLevel(final ZoomLevel zoomLevel) { timeTracker.setZoomLevel(zoomLevel); } public void onClick$zoomIncrease() { timeTracker.zoomIncrease(); } public void onClick$zoomDecrease() { timeTracker.zoomDecrease(); } private List<Row> rowsCached = null; private Map<AllocationInput, Row> groupingRows = new HashMap<AllocationInput, Row>(); private OnlyOneVisible onlyOneVisible; private Component normalLayout; private Component noDataLayout; private TimeTrackedTableWithLeftPane<Row, Row> timeTrackedTableWithLeftPane; private int verticalIndex = 0; private List<Integer> verticalPaginationIndexes; private int verticalPage; private List<Row> getRows() { if (rowsCached != null) { return filterRows(rowsCached); } rowsCached = new ArrayList<Row>(); int position = 1; for (AllocationInput allocationInput : allocationInputs) { if (allocationInput.getAggregate() .getAllocationsSortedByStartDate().isEmpty()) { } else { Row groupingRow = buildGroupingRow(allocationInput); groupingRow.setDescription(position + " " + allocationInput.getTaskName()); groupingRows.put(allocationInput, groupingRow); rowsCached.add(groupingRow); List<Row> genericRows = genericRows(allocationInput); groupingRow.listenTo(genericRows); rowsCached.addAll(genericRows); List<Row> specificRows = specificRows(allocationInput); groupingRow.listenTo(specificRows); rowsCached.addAll(specificRows); position++; } } populateVerticalListbox(); return filterRows(rowsCached); } private List<Row> filterRows(List<Row> rows) { verticalPaginationUpButton.setDisabled(verticalIndex <= 0); verticalPaginationDownButton .setDisabled((verticalIndex + VERTICAL_MAX_ELEMENTS) >= rows .size()); if(advancedAllocationVerticalPagination.getChildren().size() >= 2) { advancedAllocationVerticalPagination.setDisabled(false); advancedAllocationVerticalPagination.setSelectedIndex( verticalPage); } else { advancedAllocationVerticalPagination.setDisabled(true); } return rows.subList(verticalIndex, verticalPage + 1 < verticalPaginationIndexes.size() ? verticalPaginationIndexes.get(verticalPage + 1).intValue() : rows.size()); } public void verticalPagedown() { verticalPage++; verticalIndex = verticalPaginationIndexes.get(verticalPage); timeTrackedTableWithLeftPane.reload(); } public void setVerticalPagedownButtonDisabled(boolean disabled) { verticalPaginationUpButton.setDisabled(disabled); } public void verticalPageup() { verticalPage--; verticalIndex = verticalPaginationIndexes.get(verticalPage); timeTrackedTableWithLeftPane.reload(); } public void goToSelectedVerticalPage() { verticalPage = advancedAllocationVerticalPagination. getSelectedIndex(); verticalIndex = verticalPaginationIndexes.get(verticalPage); timeTrackedTableWithLeftPane.reload(); } public void populateVerticalListbox() { if (rowsCached != null) { verticalPage = 0; verticalPaginationIndexes = new ArrayList<Integer>(); advancedAllocationVerticalPagination.getChildren().clear(); for(int i=0; i<rowsCached.size(); i= correctVerticalPageDownPosition(i+VERTICAL_MAX_ELEMENTS)) { int endPosition = correctVerticalPageUpPosition(Math.min( rowsCached.size(), i+VERTICAL_MAX_ELEMENTS) - 1); String label = rowsCached.get(i).getDescription() + " - " + rowsCached.get(endPosition).getDescription(); Listitem item = new Listitem(); item.appendChild(new Listcell(label)); advancedAllocationVerticalPagination.appendChild(item); verticalPaginationIndexes.add(i); } if (!rowsCached.isEmpty()) { advancedAllocationVerticalPagination.setSelectedIndex(0); } } } private int correctVerticalPageUpPosition(int position) { int correctedPosition = position; //moves the pointer up until it finds the previous grouping row //or the beginning of the list while(correctedPosition > 0 && !rowsCached.get(correctedPosition).isGroupingRow()) { correctedPosition--; } return correctedPosition; } private int correctVerticalPageDownPosition(int position) { int correctedPosition = position; //moves the pointer down until it finds the next grouping row //or the end of the list while(correctedPosition < rowsCached.size() && !rowsCached.get(correctedPosition).isGroupingRow()) { correctedPosition++; } return correctedPosition; } private List<Row> specificRows(AllocationInput allocationInput) { List<Row> result = new ArrayList<Row>(); for (SpecificResourceAllocation specificResourceAllocation : allocationInput.getAggregate() .getSpecificAllocations()) { result.add(createSpecificRow(specificResourceAllocation, allocationInput.getResultReceiver().createRestriction(), allocationInput.task)); } return result; } private Row createSpecificRow( SpecificResourceAllocation specificResourceAllocation, Restriction restriction, TaskElement task) { return Row.createRow(messages, restriction, specificResourceAllocation.getResource() .getName(), 1, Arrays .asList(specificResourceAllocation), specificResourceAllocation .getResource().getShortDescription(), specificResourceAllocation.getResource().isLimitingResource(), task); } private List<Row> genericRows(AllocationInput allocationInput) { List<Row> result = new ArrayList<Row>(); for (GenericResourceAllocation genericResourceAllocation : allocationInput.getAggregate() .getGenericAllocations()) { result.add(buildGenericRow(genericResourceAllocation, allocationInput.getResultReceiver().createRestriction(), allocationInput.task)); } return result; } private Row buildGenericRow( GenericResourceAllocation genericResourceAllocation, Restriction restriction, TaskElement task) { return Row.createRow(messages, restriction, Criterion .getCaptionFor(genericResourceAllocation.getCriterions()), 1, Arrays .asList(genericResourceAllocation), genericResourceAllocation .isLimiting(), task); } private Row buildGroupingRow(AllocationInput allocationInput) { Restriction restriction = allocationInput.getResultReceiver() .createRestriction(); String taskName = allocationInput.getTaskName(); Row groupingRow = Row.createRow(messages, restriction, taskName, 0, allocationInput.getAllocationsSortedByStartDate(), false, allocationInput.task); return groupingRow; } private ICellForDetailItemRenderer<ColumnOnRow, Row> getLeftRenderer() { return new ICellForDetailItemRenderer<ColumnOnRow, Row>() { @Override public Component cellFor(ColumnOnRow column, Row row) { return column.cellFor(row); } }; } private List<ColumnOnRow> getColumnsForLeft() { List<ColumnOnRow> result = new ArrayList<ColumnOnRow>(); result.add(new ColumnOnRow(_("Name")) { @Override public Component cellFor(Row row) { return row.getNameLabel(); } }); result.add(new ColumnOnRow(_("Efforts"), "50px") { @Override public Component cellFor(Row row) { return row.getAllEffort(); } }); result.add(new ColumnOnRow(_("Function"), "130px") { @Override public Component cellFor(Row row) { return row.getFunction(); } }); return result; } private Callable<PairOfLists<Row, Row>> getDataSource() { return new Callable<PairOfLists<Row, Row>>() { @Override public PairOfLists<Row, Row> call() { List<Row> rows = getRows(); return new PairOfLists<Row, Row>(rows, rows); } }; } private ICellForDetailItemRenderer<DetailItem, Row> getRightRenderer() { return new ICellForDetailItemRenderer<DetailItem, Row>() { @Override public Component cellFor(DetailItem item, Row data) { return data.effortOnInterval(item); } }; } private Interval intervalFromData() { Interval result = null; for (AllocationInput each : allocationInputs) { Interval intervalForInput = each.calculateInterval(); result = result == null ? intervalForInput : result .coalesce(intervalForInput); } return result; } private Interval addMarginTointerval() { Interval interval = intervalFromData(); // No global margin is added by default return interval; } public boolean isAdvancedAllocationOfSingleTask() { return back.isAdvanceAssignmentOfSingleTask(); } } abstract class ColumnOnRow implements IConvertibleToColumn { private final String columnName; private String width = null; ColumnOnRow(String columnName) { this.columnName = columnName; } ColumnOnRow(String columnName, String width) { this.columnName = columnName; this.width = width; } public abstract Component cellFor(Row row); @Override public Column toColumn() { Column column = new org.zkoss.zul.Column(); column.setLabel(_(columnName)); column.setSclass(columnName.toLowerCase()); if (width != null) { column.setWidth(width); } return column; } public String getName() { return columnName; } } interface CellChangedListener { public void changeOn(DetailItem detailItem); public void changeOnGlobal(); } class Row { static Row createRow(IMessagesForUser messages, AdvancedAllocationController.Restriction restriction, String name, int level, List<? extends ResourceAllocation<?>> allocations, String description, boolean limiting, TaskElement task) { Row newRow = new Row(messages, restriction, name, level, allocations, limiting, task); newRow.setDescription(description); return newRow; } static Row createRow(IMessagesForUser messages, AdvancedAllocationController.Restriction restriction, String name, int level, List<? extends ResourceAllocation<?>> allocations, boolean limiting, TaskElement task) { return new Row(messages, restriction, name, level, allocations, limiting, task); } public void markErrorOnTotal(String message) { throw new WrongValueException(allEffortInput, message); } private EffortDurationBox allEffortInput; private Label nameLabel; private List<CellChangedListener> listeners = new ArrayList<CellChangedListener>(); private Map<DetailItem, Component> componentsByDetailItem = new WeakHashMap<DetailItem, Component>(); private String name; private String description; private int level; private final AggregateOfResourceAllocations aggregate; private final AdvancedAllocationController.Restriction restriction; private final IMessagesForUser messages; private final String functionName; private TaskElement task; void listenTo(Collection<Row> rows) { for (Row row : rows) { listenTo(row); } } void listenTo(Row row) { row.add(new CellChangedListener() { @Override public void changeOnGlobal() { reloadAllEffort(); reloadEffortsSameRowForDetailItems(); } @Override public void changeOn(DetailItem detailItem) { Component component = componentsByDetailItem.get(detailItem); if (component == null) { return; } reloadEffortOnInterval(component, detailItem); reloadAllEffort(); } }); } void add(CellChangedListener listener) { listeners.add(listener); } private void fireCellChanged(DetailItem detailItem) { for (CellChangedListener cellChangedListener : listeners) { cellChangedListener.changeOn(detailItem); } } private void fireCellChanged() { for (CellChangedListener cellChangedListener : listeners) { cellChangedListener.changeOnGlobal(); } } Component getAllEffort() { if (allEffortInput == null) { allEffortInput = buildSumAllEffort(); reloadAllEffort(); addListenerIfNeeded(allEffortInput); } return allEffortInput; } private EffortDurationBox buildSumAllEffort() { EffortDurationBox box = (isGroupingRow() || isLimiting) ? EffortDurationBox .notEditable() : new EffortDurationBox(); box.setWidth("40px"); return box; } private void addListenerIfNeeded(Component allEffortComponent) { if (isGroupingRow() || isLimiting) { return; } final EffortDurationBox effortDurationBox = (EffortDurationBox) allEffortComponent; effortDurationBox.addEventListener(Events.ON_CHANGE, new EventListener() { @Override public void onEvent(Event event) { EffortDuration value = effortDurationBox .getEffortDurationValue(); ResourceAllocation<?> resourceAllocation = getAllocation(); resourceAllocation .withPreviousAssociatedResources() .onIntervalWithinTask( resourceAllocation.getStartDate(), resourceAllocation.getEndDate()) .allocate(value); AssignmentFunction assignmentFunction = resourceAllocation.getAssignmentFunction(); if (assignmentFunction != null) { assignmentFunction.applyTo(resourceAllocation); } fireCellChanged(); reloadEffortsSameRowForDetailItems(); reloadAllEffort(); } }); } private void reloadEffortsSameRowForDetailItems() { for (Entry<DetailItem, Component> entry : componentsByDetailItem .entrySet()) { reloadEffortOnInterval(entry.getValue(), entry.getKey()); } } private void reloadAllEffort() { if (allEffortInput == null) { return; } EffortDuration allEffort = aggregate.getTotalEffort(); allEffortInput.setValue(allEffort); Clients.closeErrorBox(allEffortInput); if (isLimiting) { allEffortInput.setDisabled(true); } if (restriction.isInvalidTotalEffort(allEffort)) { restriction.showInvalidEffort(messages, allEffort); } } private Hbox hboxAssigmentFunctionsCombo = null; Component getFunction() { if (isGroupingRow()) { return new Label(); } else if (isLimiting) { return new Label(_("Limiting assignment")); } else { if (hboxAssigmentFunctionsCombo == null) { initializeAssigmentFunctionsCombo(); } return hboxAssigmentFunctionsCombo; } } private AssignmentFunctionListbox assignmentFunctionsCombo = null; private Button assignmentFunctionsConfigureButton = null; private void initializeAssigmentFunctionsCombo() { hboxAssigmentFunctionsCombo = new Hbox(); assignmentFunctionsCombo = new AssignmentFunctionListbox( functions, getAllocation().getAssignmentFunction()); hboxAssigmentFunctionsCombo.appendChild(assignmentFunctionsCombo); assignmentFunctionsConfigureButton = getAssignmentFunctionsConfigureButton(assignmentFunctionsCombo); hboxAssigmentFunctionsCombo.appendChild(assignmentFunctionsConfigureButton); } /** * @author Diego Pino García <[email protected]> * * Encapsulates the logic of the combobox used for selecting what * type of assignment function to apply */ class AssignmentFunctionListbox extends Listbox { private Listitem previousListitem; public AssignmentFunctionListbox(IAssignmentFunctionConfiguration[] functions, AssignmentFunction initialValue) { for (IAssignmentFunctionConfiguration each : functions) { Listitem listitem = listItem(each); this.appendChild(listitem); if (each.isTargetedTo(initialValue)) { selectItemAndSavePreviousValue(listitem); } } this.addEventListener(Events.ON_SELECT, onSelectListbox()); this.setMold("select"); } private void selectItemAndSavePreviousValue(Listitem listitem) { setSelectedItem(listitem); previousListitem = listitem; } private Listitem listItem( IAssignmentFunctionConfiguration assignmentFunction) { Listitem listitem = new Listitem(_(assignmentFunction.getName())); listitem.setValue(assignmentFunction); return listitem; } private EventListener onSelectListbox() { return new EventListener() { @Override public void onEvent(Event event) throws Exception { IAssignmentFunctionConfiguration function = (IAssignmentFunctionConfiguration) getSelectedItem() .getValue(); // Cannot apply function if task contains consolidated day assignments final ResourceAllocation<?> resourceAllocation = getAllocation(); if (function.isSigmoid() && !resourceAllocation .getConsolidatedAssignments().isEmpty()) { showCannotApplySigmoidFunction(); setSelectedItem(getPreviousListitem()); return; } // User didn't accept if (showConfirmChangeFunctionDialog() != Messagebox.YES) { setSelectedItem(getPreviousListitem()); return; } // Apply assignment function if (function != null) { setPreviousListitem(getSelectedItem()); function.applyOn(resourceAllocation); updateAssignmentFunctionsConfigureButton( assignmentFunctionsConfigureButton, function.isConfigurable()); } } }; } private Listitem getPreviousListitem() { return previousListitem; } private void setPreviousListitem(Listitem previousListitem) { this.previousListitem = previousListitem; } private void showCannotApplySigmoidFunction() { try { Messagebox .show(_("Task contains consolidated progress. Cannot apply sigmoid function."), _("Error"), Messagebox.OK, Messagebox.ERROR); } catch (InterruptedException e) { throw new RuntimeException(e); } } private int showConfirmChangeFunctionDialog() throws InterruptedException { return Messagebox .show(_("You are going to change the assignment function. Are you sure?"), _("Confirm change"), Messagebox.YES | Messagebox.NO, Messagebox.QUESTION); } private void setSelectedFunction(String functionName) { List<Listitem> children = getChildren(); for (Listitem item : children) { IAssignmentFunctionConfiguration function = (IAssignmentFunctionConfiguration) item .getValue(); if (function.getName().equals(functionName)) { setSelectedItem(item); } } } } private IAssignmentFunctionConfiguration flat = new IAssignmentFunctionConfiguration() { @Override public void goToConfigure() { throw new UnsupportedOperationException( "Flat allocation is not configurable"); } @Override public String getName() { return AssignmentFunctionName.FLAT.toString(); } @Override public boolean isTargetedTo(AssignmentFunction function) { return function == null; } @Override public void applyOn( ResourceAllocation<?> resourceAllocation) { resourceAllocation.setAssignmentFunctionWithoutApply(null); resourceAllocation .withPreviousAssociatedResources() .onIntervalWithinTask(resourceAllocation.getStartDate(), resourceAllocation.getEndDate()) .allocate(allEffortInput.getEffortDurationValue()); reloadEfforts(); } private void reloadEfforts() { reloadEffortsSameRowForDetailItems(); reloadAllEffort(); fireCellChanged(); } @Override public boolean isSigmoid() { return false; } @Override public boolean isConfigurable() { return false; } }; private IAssignmentFunctionConfiguration manualFunction = new IAssignmentFunctionConfiguration() { @Override public void goToConfigure() { throw new UnsupportedOperationException( "Manual allocation is not configurable"); } @Override public String getName() { return AssignmentFunctionName.MANUAL.toString(); } @Override public boolean isTargetedTo(AssignmentFunction function) { return function instanceof ManualFunction; } @Override public void applyOn(ResourceAllocation<?> resourceAllocation) { resourceAllocation.setAssignmentFunctionAndApplyIfNotFlat(ManualFunction.create()); } @Override public boolean isSigmoid() { return false; } @Override public boolean isConfigurable() { return false; } }; private abstract class CommonStrechesConfiguration extends StrechesFunctionConfiguration { @Override protected void assignmentFunctionChanged() { reloadEffortsSameRowForDetailItems(); reloadAllEffort(); fireCellChanged(); } @Override protected ResourceAllocation<?> getAllocation() { return Row.this.getAllocation(); } @Override protected Component getParentOnWhichOpenWindow() { return allEffortInput.getParent(); } } private IAssignmentFunctionConfiguration defaultStrechesFunction = new CommonStrechesConfiguration() { @Override protected String getTitle() { return _("Stretches list"); } @Override protected boolean getChartsEnabled() { return true; } @Override protected StretchesFunctionTypeEnum getType() { return StretchesFunctionTypeEnum.STRETCHES; } @Override public String getName() { return AssignmentFunctionName.STRETCHES.toString(); } }; private IAssignmentFunctionConfiguration strechesWithInterpolation = new CommonStrechesConfiguration() { @Override protected String getTitle() { return _("Stretches with Interpolation"); } @Override protected boolean getChartsEnabled() { return false; } @Override protected StretchesFunctionTypeEnum getType() { return StretchesFunctionTypeEnum.INTERPOLATED; } @Override public String getName() { return AssignmentFunctionName.INTERPOLATION.toString(); } }; private IAssignmentFunctionConfiguration sigmoidFunction = new IAssignmentFunctionConfiguration() { @Override public void goToConfigure() { throw new UnsupportedOperationException( "Sigmoid function is not configurable"); } @Override public String getName() { return AssignmentFunctionName.SIGMOID.toString(); } @Override public boolean isTargetedTo(AssignmentFunction function) { return function instanceof SigmoidFunction; } @Override public void applyOn( ResourceAllocation<?> resourceAllocation) { resourceAllocation.setAssignmentFunctionAndApplyIfNotFlat(SigmoidFunction.create()); reloadEfforts(); } private void reloadEfforts() { reloadEffortsSameRowForDetailItems(); reloadAllEffort(); fireCellChanged(); } @Override public boolean isSigmoid() { return true; } @Override public boolean isConfigurable() { return false; } }; private IAssignmentFunctionConfiguration[] functions = { flat, manualFunction, defaultStrechesFunction, strechesWithInterpolation, sigmoidFunction }; private boolean isLimiting; private Button getAssignmentFunctionsConfigureButton( final Listbox assignmentFunctionsListbox) { Button button = Util.createEditButton(new EventListener() { @Override public void onEvent(Event event) { IAssignmentFunctionConfiguration configuration = (IAssignmentFunctionConfiguration) assignmentFunctionsListbox .getSelectedItem().getValue(); configuration.goToConfigure(); } }); IAssignmentFunctionConfiguration configuration = (IAssignmentFunctionConfiguration) assignmentFunctionsListbox .getSelectedItem().getValue(); updateAssignmentFunctionsConfigureButton(button, configuration.isConfigurable()); return button; } private void updateAssignmentFunctionsConfigureButton(Button button, boolean configurable) { if (configurable) { button.setTooltiptext(_("Configure")); button.setDisabled(false); } else { button.setTooltiptext(_("Not configurable")); button.setDisabled(true); } } Component getNameLabel() { if (nameLabel == null) { nameLabel = new Label(); nameLabel.setValue(name); if (!StringUtils.isBlank(description)) { nameLabel.setTooltiptext(description); } else { nameLabel.setTooltiptext(name); } nameLabel.setSclass("level" + level); } return nameLabel; } private Row(IMessagesForUser messages, AdvancedAllocationController.Restriction restriction, String name, int level, List<? extends ResourceAllocation<?>> allocations, boolean limiting, TaskElement task) { this.messages = messages; this.restriction = restriction; this.name = name; this.level = level; this.isLimiting = limiting; this.task = task; this.aggregate = AggregateOfResourceAllocations .createFromSatisfied(new ArrayList<ResourceAllocation<?>>(allocations)); this.functionName = getAssignmentFunctionName(allocations); } private String getAssignmentFunctionName( List<? extends ResourceAllocation<?>> allocations) { AssignmentFunction function = getAssignmentFunction(allocations); return (function != null) ? function.getName() : AssignmentFunctionName.FLAT.toString(); } private AssignmentFunction getAssignmentFunction( List<? extends ResourceAllocation<?>> allocations) { if (allocations != null) { ResourceAllocation<?> allocation = allocations.iterator().next(); return allocation.getAssignmentFunction(); } return null; } private EffortDuration getEffortForDetailItem(DetailItem item) { DateTime startDate = item.getStartDate(); DateTime endDate = item.getEndDate(); return this.aggregate.effortBetween(startDate.toLocalDate(), endDate .toLocalDate()); } Component effortOnInterval(DetailItem item) { Component result = cannotBeEdited(item) ? new Label() : disableIfNeeded(item, new EffortDurationBox()); reloadEffortOnInterval(result, item); componentsByDetailItem.put(item, result); addListenerIfNeeded(item, result); return result; } private boolean cannotBeEdited(DetailItem item) { return isGroupingRow() || doesNotIntersectWithTask(item) || isBeforeLatestConsolidation(item); } private EffortDurationBox disableIfNeeded(DetailItem item, EffortDurationBox effortDurationBox) { effortDurationBox.setDisabled(restriction.isDisabledEditionOn(item)); return effortDurationBox; } private void addListenerIfNeeded(final DetailItem item, final Component component) { if (cannotBeEdited(item)) { return; } final EffortDurationBox effortBox = (EffortDurationBox) component; component.addEventListener(Events.ON_CHANGE, new EventListener() { @Override public void onEvent(Event event) { EffortDuration value = effortBox.getEffortDurationValue(); LocalDate startDate = restriction.limitStartDate(item .getStartDate().toLocalDate()); LocalDate endDate = restriction.limitEndDate(item.getEndDate() .toLocalDate()); changeAssignmentFunctionToManual(); getAllocation().withPreviousAssociatedResources() .onIntervalWithinTask(startDate, endDate) .allocate(value); fireCellChanged(item); effortBox.setRawValue(getEffortForDetailItem(item)); reloadAllEffort(); } }); } private void changeAssignmentFunctionToManual() { assignmentFunctionsCombo .setSelectedFunction(AssignmentFunctionName.MANUAL.toString()); ResourceAllocation<?> allocation = getAllocation(); if (!(allocation.getAssignmentFunction() instanceof ManualFunction)) { allocation.setAssignmentFunctionAndApplyIfNotFlat(ManualFunction.create()); } } private void reloadEffortOnInterval(Component component, DetailItem item) { if (cannotBeEdited(item)) { Label label = (Label) component; label.setValue(getEffortForDetailItem(item).toFormattedString()); label.setClass(getLabelClassFor(item)); } else { EffortDurationBox effortDurationBox = (EffortDurationBox) component; effortDurationBox.setValue(getEffortForDetailItem(item)); if (isLimiting) { effortDurationBox.setDisabled(true); effortDurationBox.setSclass(" limiting"); } } } private String getLabelClassFor(DetailItem item) { if (isGroupingRow()) { return "calculated-hours"; } if (doesNotIntersectWithTask(item)) { return "unmodifiable-hours"; } if (isBeforeLatestConsolidation(item)) { return "consolidated-hours"; } return ""; } private boolean doesNotIntersectWithTask(DetailItem item) { return isBeforeTaskStartDate(item) || isAfterTaskEndDate(item); } private boolean isBeforeTaskStartDate(DetailItem item) { return task.getIntraDayStartDate().compareTo( item.getEndDate().toLocalDate()) >= 0; } private boolean isAfterTaskEndDate(DetailItem item) { return task.getIntraDayEndDate().compareTo( item.getStartDate().toLocalDate()) <= 0; } private boolean isBeforeLatestConsolidation(DetailItem item) { if(!((Task)task).hasConsolidations()) { return false; } LocalDate d = ((Task) task).getFirstDayNotConsolidated().getDate(); DateTime firstDayNotConsolidated = new DateTime(d.getYear(), d.getMonthOfYear(), d.getDayOfMonth(), 0, 0, 0, 0); return item.getStartDate().compareTo(firstDayNotConsolidated) < 0; } private ResourceAllocation<?> getAllocation() { if (isGroupingRow()) { throw new IllegalStateException("is grouping row"); } return aggregate.getAllocationsSortedByStartDate().get(0); } public boolean isGroupingRow() { return level == 0; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
[Bug #1184] Fix issue avoiding reset verticalPage to zero FEA: ItEr75S04BugFixing
navalplanner-webapp/src/main/java/org/navalplanner/web/planner/allocation/AdvancedAllocationController.java
[Bug #1184] Fix issue avoiding reset verticalPage to zero
<ide><path>avalplanner-webapp/src/main/java/org/navalplanner/web/planner/allocation/AdvancedAllocationController.java <ide> <ide> public void populateVerticalListbox() { <ide> if (rowsCached != null) { <del> verticalPage = 0; <ide> verticalPaginationIndexes = new ArrayList<Integer>(); <ide> advancedAllocationVerticalPagination.getChildren().clear(); <ide> for(int i=0; i<rowsCached.size(); i=
JavaScript
agpl-3.0
c5602770741e9f419a7a8488e6b9f60ec5603888
0
seemecnc/OctoGUI,seemecnc/OctoGUI,seemecnc/OctoGUI,seemecnc/OctoGUI
var hotLoadZLift = 0; // Specify how high to lift the head when changing filament var sock = new SockJS('http://' + window.location.host + '/sockjs?apikey='+apikey); var api = "http://" + window.location.host + "/api/"; var apikey = "ABAABABB"; var printerStatus = "Checking..."; var etemp = "--"; // Current Nozzel Temperature var etempTarget = "--"; // Current Nozzel Target Temperature var btemp = "--"; // Current Bed Temperature var btempTarget = "--"; // Current Bed Target Temperature var sortBy = "name"; // Sort Order var sortRev = false; // Sort order reverse flag var printerId; // Printer profile ID var heatedBed = false; // Heated Bed Flag var currentZ; // Current Z height var returnX = null; // X pos to return to after lifting head var returnY = null; // Y pos to return to after lifting head var returnZ; // Z pos to return to after lifting head var returnE; // Extruder position to return to after chaning filament var watchLogFor = []; // Array of thing to watch the printer logs for var watchForZ = []; // Array of Z heights to watch for var zdt; // Z Menu DataTable handle var zIndex = 0; // Z Menu build number var zNum = 0; // Z Menu item count var zEventList = []; // Array for handing entry of Z events var hotLoading = false; // Flag for changing filament mid-print var liftOnPause = false; // Flag for automatically lifting the print head and retracting filament on pause var maxZHeight = 0; // Max printable Z height var currentSpeed = 100; // Current speed (percentage) of print var pauseTimeout = 0; // Time when current print job was paused var pauseTemp = 0; // Extruder temp when print job was paused var dt; // fileList DataTables handle var reconnect = false; // variable to automatically reconnect to the printer when disconnected // Z Events var zEvents = []; zEvents.push({ "command":"Filament", "label":"Change Filament" }); zEvents.push({ "command":"Speed", "label":"Change Speed" }); zEvents.push({ "command":"ExtruderTemp", "label":"Extruder Temperature" }); zEvents.push({ "command":"BedTemp", "label":"Bed Temperature" }); // Calibration GCODE var calibrateString = []; calibrateString['eris'] = [ "M202 Z1850", "G69 S2", "G68", "G30 S2", "M202 Z400", "M500", "G4 S2", "M115" ]; calibrateString['orion'] = [ "G69 S2", "M117 ENDSTOPS CALIBRATED", "G68 ", "M117 HORIZONTAL RADIUS CALIBRATED", "G30 S2 ", "M117 Z Height Calibrated", "G4 S2", "M500", "M117 CALIBRATION SAVED", "M115" ]; calibrateString['rostock_max_v3'] = [ "G69 S2", "M117 ENDSTOPS CALIBRATED", "G68 ", "M117 HORIZONTAL RADIUS CALIBRATED", "G30 S2 ", "M117 Z Height Calibrated", "G4 S2", "M500", "M117 CALIBRATION SAVED", "M115" ]; // GCODE to Load filament var loadFilamentString = []; loadFilamentString['eris'] = [ "G28", "M109 S220", "G91", "G1 E530 F5000", "G1 E100 F150", "G90", "G92 E0", "M104 S0", "M84", "M115" ]; loadFilamentString['orion'] = [ "G28", "M109 S220", "G91", "G1 E560 F5000", "G1 E100 F150", "G90", "G92 E0", "M104 S0", "M84", "M115" ]; loadFilamentString['rostock_max_v3'] = [ "G28", "M109 S220", "G91", "G1 E750 F5000", "G1 E100 F150", "G90", "G92 E0", "M104 S0", "M84", "M115" ]; // GCODE to unload filament var unloadFilamentString = []; unloadFilamentString['eris'] = [ "G28", "M109 S220", "G91", "G1 E30 F75", "G1 E-75 F5000", "G90", "G92 E0", "G4 S3", "G91", "G1 E-600", "M104 S0", "G90", "G92 E0", "M84", "M115" ]; unloadFilamentString['orion'] = [ "G28", "M109 S220", "G91", "G1 E30 F75", "G1 E-75 F5000", "G90", "G92 E0", "G4 S3", "G91", "G1 E-600", "M104 S0", "G90", "G92 E0", "M84", "M115" ]; unloadFilamentString['rostock_max_v3'] = [ "G28", "M109 S220", "G91", "G1 E30 F75", "G1 E-75 F5000", "G90", "G92 E0", "G4 S3", "G91", "G1 E-840", "M104 S0", "G90", "G92 E0", "M84", "M115" ]; // GCODE to unload filament mid-print var hotUnloadString = []; hotUnloadString['eris'] = [ "G91", "G1 E-75 F5000", "G90", "G92 E0", "G4 S3", "G91", "G1 E-600", "G90", "G92 E0" ]; hotUnloadString['orion'] = [ "G91", "G1 E-75 F5000", "G90", "G92 E0", "G4 S3", "G91", "G1 E-600", "G90", "G92 E0" ]; hotUnloadString['rostock_max_v3'] = [ "G91", "G1 E-75 F5000", "G90", "G92 E0", "G4 S3", "G91", "G1 E-830", "G90", "G92 E0" ]; // GCODE to load filament mid-print var hotLoadString = []; hotLoadString['eris'] = [ "G91", "G1 E530 F5000", "G1 E80 F150", "G90", "G92 E0" ]; hotLoadString['orion'] = [ "G91", "G1 E560 F5000", "G1 E80 F150", "G90", "G92 E0" ]; hotLoadString['rostock_max_v3'] = [ "G91", "G1 E750 F5000", "G1 E100 F150", "G90", "G92 E0" ]; // SockJS info from Octoprint sock.onopen = function(){ //Slow down the update frequency to 1hz sock.send( JSON.stringify({"throttle": 2} )); //Ask for M115 info on status change if(typeof watchLogFor['filamentInfo'] == 'undefined' && printerStatus != "Closed" && printerStatus != "Connecting" && printerStatus != "Detecting serial port"){ watchLogFor['firmwareInfo'] = "FIRMWARE"; watchLogFor.length++; watchLogFor['filamentInfo'] = "Printed filament"; watchLogFor.length++; sendCommand("M115"); } } // SockJS message handling sock.onmessage = function(e) { //Only process "current" messages if (typeof e.data.current !== 'undefined'){ var t; //watch for Z height actions if(typeof watchForZ[0] !== 'undefined'){ if(printerStatus == "Printing" && currentZ == e.data.current.currentZ && currentZ >= watchForZ[0]['height'] && currentZ != null){ spottedZ(watchForZ[0]['action'],watchForZ[0]['arg']); watchForZ.splice(0,1); } } currentZ = e.data.current.currentZ; document.getElementById('currentZ').innerHTML = currentZ; if (e.data.current.progress.completion !== null){ document.getElementById('currentPercent').innerHTML = e.data.current.progress.completion.toFixed(2); } document.getElementById('currentPrintTime').innerHTML = humanTime(e.data.current.progress.printTime); document.getElementById('currentPrintTimeLeft').innerHTML = humanTime(e.data.current.progress.printTimeLeft); //watch for Log actions if(watchLogFor.length > 0){ for(var i in watchLogFor){ for(var l in e.data.current.logs){ if(t = e.data.current.logs[l].includes(watchLogFor[i])){ spottedLog(i, e.data.current.logs[l]); } } } } } }; // Actions to take when Z height is hit function spottedZ(action,arg){ switch(action){ case "Speed": console.log("Setting speed to " + arg + " at z: " + currentZ); setSpeedFactor(arg); break; case "Filament": console.log("Changing Filament at z: " + currentZ); printCommand("pause"); liftOnPause = true; break; case "ExtruderTemp": console.log("Setting Extruder Temp to " + arg + " at z: " + currentZ); setExtruderTemp(arg); break; case "BedTemp": console.log("Setting Bed Temp to " + arg + " at z: " + currentZ); setBedTemp(arg); break; } } // Actions to take when a given string is spotted in the log function spottedLog(key, log){ log = log.replace(/Recv:\ /,''); switch(key){ case "COMMERROR": // Connection error - usually happens after cancelling a print on a Rostock delete watchLogFor[key]; watchLogFor.length--; connectPrinter("disconnect"); reconnect = true; break; case "E": // Logging return extruder position returnE = log.replace(/.*\ E/,''); returnE = returnE.replace(/\*.*/,''); if(log.includes("X")){ returnX = log.replace(/.*\ X/,''); returnX = returnX.replace(/\*.*/,''); } if(log.includes("Y")){ returnY = log.replace(/.*\ Y/,''); returnY = returnY.replace(/\*.*/,''); } break; case "stateToPaused": // Hotunload trigger console.log("Printer is paused. Last E is " + returnE); if(returnE > 0) { document.getElementById('hotUnload').style.visibility = "visible"; if(liftOnPause){ pauseUnload(); } } delete watchLogFor[key]; watchLogFor.length--; delete watchLogFor["E"]; watchLogFor.length--; console.log("Return XY: " + returnX + "/" + returnY); break; case "firmwareInfo": // Use Firmware info to verify printer model var pId; var fw = log.replace(/FIRMWARE_NAME:/,''); var fwd = log.replace(/.*_DATE:/,''); var fwp = log.replace(/.*MACHINE_TYPE:/,''); fw = fw.replace(/\ .*/,''); fwd = fwd.replace(/\ .*/,''); document.getElementById('firmwareInfo').style.visibility = "visible"; document.getElementById('firmwareInfo').innerHTML = fw; document.getElementById('firmwareDate').style.visibility = "visible"; document.getElementById('firmwareDate').innerHTML = fwd; switch(fwp){ case "ERIS Delta": pId = "eris"; break; case "ORION Delta": pId = "orion"; break; case "Rostock Max v2": pId = "rostock_max_v2"; break; case "Rostock MAX v3": pId = "rostock_max_v3"; break; default: pId = 'default'; console.log("Printer ("+fwp+") not supported!"); break; } if(pId != printerId){ setPrinterProfile(pId); } delete watchLogFor[key]; watchLogFor.length--; //Init trap for Comm Error if it's not alreay set if(typeof watchLogFor['COMMERROR'] == 'undefined'){ watchLogFor['COMMERROR'] = 'sufficient'; watchLogFor.length++; } break; case "filamentInfo": // Update amount of filament used document.getElementById('filamentInfo').style.visibility = "visible"; document.getElementById('filamentInfo').innerHTML = log; delete watchLogFor[key]; watchLogFor.length--; break; case "hideOverlay": // Set the Overlay to hidden hideOverlay(); delete watchLogFor[key]; watchLogFor.length--; break; } } // Find the current IP of the client and update it on screen function getClientIP() { window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){}; pc.createDataChannel(""); pc.createOffer(pc.setLocalDescription.bind(pc), noop); pc.onicecandidate = function(ice){ if(!ice || !ice.candidate || !ice.candidate.candidate) return; var myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1]; window.clientIP = myIP; document.getElementById("clientIP").innerHTML = myIP; pc.onicecandidate = noop; }; } // Sort an array by the given property function dynamicSort(property) { var sortOrder = 1; if(property[0] === "-") { sortOrder = -1; property = property.substr(1); } return function (a,b) { var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0; return result * sortOrder; } } // Basic on/off fan controll function fanControl(c){ var gcode; if(c == "on"){ sendCommand("M106"); } else { sendCommand("M107"); } } // Send the Calibrate GCODE to the printer if it is configured and the printer is Operational function calibratePrinter(){ if(printerStatus == "Operational"){ if (typeof calibrateString[printerId] !== 'undefined'){ bootbox.confirm("Make sure the print bed is clear and there is no filament hanging from the extruder.", function(result){ if(result){ sendCommand(calibrateString[printerId]); watchLogFor["hideOverlay"] = "MACHINE_TYPE"; watchLogFor.length++; showOverlay("Printer is Calibrating"); } }); }else{ bootbox.alert({ message: "Calibration script is not set for the " + printerId, backdrop: true }); } }else{ bootbox.alert({ message: "Cannot calibrate when printer is " + printerStatus, backdrop: true }); } } // Load filament if it is configured and the printer is Operational function loadFilament(){ if(printerStatus == "Operational"){ if (typeof loadFilamentString[printerId] !== 'undefined'){ bootbox.confirm("You are about to LOAD filament. Make sure that it is 1 inch past the end of the extruder.", function(result){ if(result){ sendCommand(loadFilamentString[printerId]); watchLogFor["hideOverlay"] = "MACHINE_TYPE"; watchLogFor.length++; showOverlay("Heating nozzel and<br>Loading Filament"); } }); } else{ bootbox.alert({ message: "Load Filament script is not set for the " + printerId, backdrop: true }); } }else{ bootbox.alert({ message: "Cannot load filament when printer is " + printerStatus, backdrop: true }); } } // Unload filament if it is configured and the printer is Operational function unloadFilament(){ if(printerStatus == "Operational"){ if (typeof unloadFilamentString[printerId] !== 'undefined'){ bootbox.confirm("You are about to UNLOAD filament. Please Confirm this is what you want to do.", function(result){ if(result){ sendCommand(unloadFilamentString[printerId]); watchLogFor["hideOverlay"] = "MACHINE_TYPE"; watchLogFor.length++; showOverlay("Heating nozzel and<br>Retracting Filament"); } }); } else{ bootbox.alert({ message: "Unload Filament script is not set for the " + printerId, backdrop: true }); } }else{ bootbox.alert({ message: "Cannot load filament when printer is " + printerStatus, backdrop: true }); } } // Set the Nozzel temperature function setExtruderTemp(target){ $.ajax({ url: api+"printer/tool?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: JSON.stringify({"command":"target","targets":{"tool0": target}}) }); etempTarget = target; document.getElementById('extruderTempTarget').innerHTML = etempTarget; document.getElementById('eTempInput').value = etempTarget; } // Set the Bed temperature function setBedTemp(target){ if(heatedBed){ $.ajax({ url: api+"printer/bed?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: JSON.stringify({"command":"target","target":target}) }); btempTarget = target; document.getElementById('bedTempTarget').innerHTML = btempTarget; document.getElementById('bTempInput').value = btempTarget; }else{ bootbox.alert({ message: "Cannot set bed temp.<br>No heated bed detected.", backdrop: true }); } } // Check and updated the current connection status for the printer function updateConnectionStatus(){ $.ajax({ url: api+"connection?apikey="+apikey, type: "get", contentType:"application/json; charset=utf-8", complete: (function(data,type){ if(type == "success"){ jdata = JSON.parse(data.responseText); //Reconnect check when connection is closed if(printerStatus == "Closed" && reconnect){ reconnect = false; connectPrinter("connect"); } //Clear Z events when a print job is completed or cancelled if(printerStatus == "Printing" && jdata.current.state != "Printing" && jdata.current.state != "Paused" && typeof watchForZ[0] !== 'undefined'){ watchForZ = []; console.log("Clearing Z events"); } //Update filament and firmware info when printer enters Operational state if(printerStatus != "Operational" && jdata.current.state == "Operational" && typeof watchLogFor['filamentInfo'] == 'undefined'){ watchLogFor['firmwareInfo'] = "FIRMWARE"; watchLogFor.length++; watchLogFor['filamentInfo'] = "Printed filament"; watchLogFor.length++; sendCommand("M115"); }else{ //In case the M115 command gets lost in the shuffle if(typeof watchLogFor['filamentInfo'] !== 'undefined' && printerStatus == "Operational"){ sendCommand("M115"); } } printerStatus = jdata.current.state; //Automaticaly reconnect if Z-probe errors borks the connection if(printerStatus.includes("Error: Z-probe failed")){ connectPrinter("connect"); printerStatus = "Connecting"; } }else{ printerStatus = "Unknown"; } }) }); } // Update non SockJS fields on the user interface function updateStatus(){ updateConnectionStatus(); //Shut down the hot end if paused too long if(printerStatus == "Paused" && pauseTimeout > 0){ if(pauseTimeout + (5 * 60 * 1000) <= (new Date().valueOf())){ console.log("Printer paused for too long. Shutting off hot end"); pauseTemp = etempTarget; setExtruderTemp(0); pauseTimeout = 0; } } if(printerStatus == "Operational" || printerStatus == "Printing" || printerStatus == "Paused"){ $.ajax({ url: api+"printer?apikey="+apikey, type: "get", contentType:"application/json; charset=utf-8", complete: (function(data,type){ if(type == "success"){ jdata = JSON.parse(data.responseText); etemp = jdata.temperature.tool0.actual; etempTarget = jdata.temperature.tool0.target; if(heatedBed && typeof jdata.temperature.bed !== 'undefined'){ btemp = jdata.temperature.bed.actual; btempTarget = jdata.temperature.bed.target; } updateJobStatus(); }else{ updateConnectionStatus(); etemp = "--"; btemp = "--"; } }) }); }else{ etemp = "--"; btemp = "--"; } document.getElementById('currentStatus').innerHTML = printerStatus; document.getElementById('extruderTemp').innerHTML = etemp; document.getElementById('bedTemp').innerHTML = btemp; document.getElementById('extruderTempTarget').innerHTML = etempTarget; document.getElementById('eTempInput').value = etempTarget; document.getElementById('bedTempTarget').innerHTML = btempTarget; document.getElementById('bTempInput').value = btempTarget; } // Updates the status fields for the current print job function updateJobStatus(){ $.ajax({ url: api+"job?apikey="+apikey, type: "get", contentType:"application/json; charset=utf-8", complete: (function(data,type){ if(type == "success"){ jdata = JSON.parse(data.responseText); document.getElementById('currentName').innerHTML = jdata.job.file.name; if (jdata.job.filament !== null && typeof jdata.job.filament.tool0 !== 'undefined') { document.getElementById('currentFilament').innerHTML = (jdata.job.filament.tool0.length / 1000).toFixed(2) + "m"; } }else{ document.getElementById('currentName').innerHTML = ""; document.getElementById('currentFilament').innerHTML = ""; } }) }); } // Have Octoprint load the current file and prep it for printing. Sending a second argument (true) starts the print after loading function selectFile(file,print){ print = print || 0; var c; if(print){ c = {"command":"select","print":true}; } else{ c = {"command":"select"}; } $.ajax({ url: api+"files/" + file +"?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: JSON.stringify(c), success: (function(){ updateStatus(); }) }); } // Changes the File sort field function setSortBy(s){ if(sortBy == s){ if(sortRev){ sortRev = false; } else{ sortRev = true; } }else{ sortRev = false; } sortBy = s; updateFiles(); } // Copies file from local storage to USB function copyToUsb(file){ var text; var currentPage = dt.page(); $.ajax({ url: "include/f.php?c=copyToUsb&f=" + file, type: "get", contentType:"application/json; charset=utf-8", complete: (function(data,type){ jdata = JSON.parse(data.responseText); if(jdata.status){ text = "File " + file + " copied to USB storage"; } else{ text = "Error copying " + file; } bootbox.alert({ message: text, backdrop: true }); }) }); } // Copies file from the USB stick to local storage function copyToLocal(file){ var text; var currentPage = dt.page(); $.ajax({ url: "include/f.php?c=copy&f=" + file, type: "get", contentType:"application/json; charset=utf-8", complete: (function(data,type){ jdata = JSON.parse(data.responseText); if(jdata.status){ text = "File " + file + " copied to local storage"; } else{ text = "Error copying " + file; } bootbox.alert({ message: text, backdrop: true }); document.getElementById('currentName').innerHTML = "Loading..."; document.getElementById('currentFilament').innerHTML = "Calculating..."; updateFiles(currentPage); updateStatus(); }) }); } // Deletes a given file from the given locations function deleteFile(origin, file){ var currentPage = dt.page(); switch(origin){ case "local": $.ajax({ url: api+ "files/local/" + file + "?apikey=" +apikey, type: "delete", contentType:"application/json; charset=utf-8", complete: (function(data,type){ if(data.status == 204){ updateFiles(currentPage); } else{ alert("Error deleting " + file); } }) }); break; case "usb": $.ajax({ url: "include/f.php?c=delete", type: "post", data: {"f" : file}, complete: (function(data,type){ jdata = JSON.parse(data.responseText); if(jdata.status == 1){ updateFiles(currentPage); } else{ alert("Error deleting " + file); } }) }); break; case "sdcard": $.ajax({ url: api+ "files/sdcard/" + file + "?apikey=" +apikey, type: "delete", contentType:"application/json; charset=utf-8", complete: (function(data,type){ if(data.status == 204){ updateFiles(currentPage); } else{ alert("Error deleting " + file); } }) }); break; } } // Refreshes the fileList table - keeps current page if provided function updateFiles(page){ page = page || 0; $.ajax({ url: "include/f.php?c=list", type: "get", contentType:"application/json; charset=utf-8", complete: (function(data,type){ if(type == "success"){ jdata = JSON.parse(data.responseText); dt.clear(); if(jdata == null){ dt.draw(); } else{ var sortString; if(sortRev){ sortString = "-" + sortBy; } else{ sortString = sortBy; } var files = jdata.sort(dynamicSort(sortString)); files.forEach(function(f){ dt.row.add([ f.origin, f.name ]); }); if(page > 0){ if(page >= (dt.page.info().pages)){ page = dt.page.info().pages - 1; } dt.page(page).draw(false); }else { dt.draw(); } } } }) }); } // Converts seconds to human readable hours, minutes, seconds function humanTime(d) { d = Number(d); var h = Math.floor(d / 3600); var m = Math.floor(d % 3600 / 60); var s = Math.floor(d % 3600 % 60); return ((h > 0 ? h + ":" + (m < 10 ? "0" : "") : "") + m + ":" + (s < 10 ? "0" : "") + s); } // Send given GCODE (single command or array of commands) to the printer via Octoprint function sendCommand(command){ var c; if(command instanceof Array){ c = { "commands": command }; } else{ c = { "command": command }; } $.ajax({ url: api+"printer/command?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: JSON.stringify(c) }); } // Home all Axis and disabled the stepper motors. TODO: Setup motor enable/disable fuctions/buttons function homePrinter(){ if(printerStatus == "Printing"){ bootbox.alert({ message: "Print job in progress. Cancel the job if you really want to home the print head.", backdrop: true }); }else{ $.ajax({ url: api+"printer/printhead?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: JSON.stringify({ 'command': "home", 'axes': [ 'x', 'y', 'z' ] }), success: (function(){ sendCommand("M84"); }) }); } } // Initiate connection to the printer function connectPrinter(com){ var c; if(com == "connect"){ $.ajax({ url: "include/f.php?c=port", type: "get", contentType:"application/json; charset=utf-8", complete: (function(data,type){ jdata = JSON.parse(data.responseText); if(jdata.port == "ERROR"){ c = { 'command': "connect","baudrate": 250000 }; } else{ c = { 'command': "connect","baudrate": 250000,"port": jdata.port }; } $.ajax({ url: api+"connection?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: JSON.stringify(c), success: (function(){ updateStatus(); }) }); }) }); } else { c = { 'command': "disconnect"}; printerStatus = "Disconnecting"; document.getElementById('currentStatus').innerHTML = printerStatus; $.ajax({ url: api+"connection?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: JSON.stringify(c), success: (function(){ updateStatus(); }) }); } } // Resume printing after pausing and changing filament function resumeHotLoad(){ document.getElementById('hotUnload').style.visibility = "hidden"; if(hotLoading){ if(returnX != null && returnY != null){ sendCommand( [ "G28", "90", "G0 X" + returnX + " Y" + returnY + " Z" + returnZ +" F1440 E2", "G92 E" + returnE ] ); }else{ sendCommand( [ "G28", "90", "G0 Z" + returnZ +" F1440 E2", "G92 E" + returnE ] ); } document.getElementById('hotLoad').style.visibility = "hidden"; hotLoading = false; returnE = 0; returnX = null; returnY = null; } } // Send basic print job command ( play, pause, cancel ) function printCommand(command){ var c; if(command == "pause"){ c = JSON.stringify({ 'command': "pause", 'action': 'toggle' }); if(printerStatus == "Printing" && currentZ < (maxZHeight - hotLoadZLift - 10)) { console.log("Printing paused at " + currentZ); watchLogFor['E'] = ' E'; watchLogFor.length++; watchLogFor['stateToPaused'] = 'Paused'; watchLogFor.length++; } if(printerStatus == "Paused") { resumeHotLoad(); } }else{ if(command == "start" && printerStatus == "Paused"){ c = JSON.stringify({ 'command': "pause", 'action': 'toggle' }); resumeHotLoad(); } else{ c = JSON.stringify({ 'command': command }); } } if(command == "cancel"){ bootbox.confirm("Are you sure you want to cancel the current print job?.", function(result){ if(result){ showOverlay("Canceling print job"); watchLogFor["hideOverlay"] = "Operational"; watchLogFor.length++; $.ajax({ url: api+"job?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: c, success: (function(){ setExtruderTemp(0); if(heatedBed){ setBedTemp(0); } }) }); } }); }else{ $.ajax({ url: api+"job?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: c }); } } // Head Jog command pulling increment from the GUI function jogHead(axis,dir){ var d; //jog distance jogI = $('input[name="jogIncrement"]:checked').val(); if(dir == "-"){ d = Number(dir + jogI); } else{ d = Number(jogI); } var c = {'command':'jog'}; c[axis] = d; $.ajax({ url: api+"printer/printhead?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: JSON.stringify(c) }); } // Head Job command with specified axis and increment function moveHead(axis,distance){ var c = {'command':'jog'}; c[axis] = distance; $.ajax({ url: api+"printer/printhead?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: JSON.stringify(c) }); } // Set a new default connection profile and disconnect. Prompt to notify and delay reconnect function setPrinterProfile(newPrinterId){ connectPrinter("disconnect"); $.ajax({ url: api+"printerprofiles/" + newPrinterId + "?apikey="+apikey, type: "patch", contentType:"application/json; charset=utf-8", data: JSON.stringify({"profile":{"default":1}}), success: (function(){ getPrinterProfile(); bootbox.alert("New printer detected. Press OK to reconnect", function(){ connectPrinter("connect"); }); }) }); } // Get the currently selected default printer profile and set global vars function getPrinterProfile(){ $.ajax({ url: api+"printerprofiles?apikey="+apikey, type: "get", contentType:"application/json; charset=utf-8", complete: (function(data,type){ jdata = JSON.parse(data.responseText); for(i in jdata.profiles){ if(jdata.profiles[i].default){ printerId = jdata.profiles[i].id; heatedBed = jdata.profiles[i].heatedBed; maxZHeight = jdata.profiles[i].volume.height; document.getElementById('printerModel').innerHTML = jdata.profiles[i].name; if(heatedBed) { document.getElementById('bedTempDisplay').style.visibility = "visible"; document.getElementById('bedTempSet').style.visibility = "visible"; }else { document.getElementById('bedTempDisplay').style.visibility = "hidden"; document.getElementById('bedTempSet').style.visibility = "hidden"; } if(typeof calibrateString[printerId] !== 'undefined'){ document.getElementById('calibratePrinter').style.visibility = "visible"; } else { document.getElementById('calibratePrinter').style.visibility = "hidden"; } if(typeof loadFilamentString[printerId] !== 'undefined'){ document.getElementById('loadFilament').style.visibility = "visible"; } else { document.getElementById('loadFilament').style.visibility = "hidden"; } if(typeof unloadFilamentString[printerId] !== 'undefined'){ document.getElementById('unloadFilament').style.visibility = "visible"; } else { document.getElementById('unloadFilament').style.visibility = "hidden"; } if(typeof loadFilamentString[printerId] !== 'undefined'){ document.getElementById('loadFilament').style.visibility = "visible"; } else { document.getElementById('loadFilament').style.visibility = "hidden"; } if(printerId == 'eris'){ document.getElementById('fanControl').style.visibility = "hidden"; } else { document.getElementById('fanControl').style.visibility = "visible"; } } } }) }); } // whie paused, Raise print head and unload filament function pauseUnload(){ if(printerStatus == "Paused" && typeof hotUnloadString[printerId] !== 'undefined' && currentZ < (maxZHeight - hotLoadZLift - 10)){ if(returnE > 0){ hotLoading = true; returnZ = currentZ; //if(hotLoadZLift > 0){ moveHead('z',hotLoadZLift); } //else{ moveHead('z',(maxZHeight - 15)); } sendCommand("G28"); sendCommand(hotUnloadString[printerId]); document.getElementById('hotUnload').style.visibility = "hidden"; document.getElementById('hotLoad').style.visibility = "visible"; pauseTimeout = new Date().valueOf(); }else{ alert("Error. Last extruder position not found. Please Resume your print, then pause to try again."); } } } // Load filament after changing mid print, heating nozzel if necissary function playLoad(){ var c = hotLoadString[printerId]; if(printerStatus == "Paused" && typeof hotLoadString[printerId] !== 'undefined'){ if(pauseTemp > 0){ console.log("Heating extruder before loading filament"); c.unshift("M109 S"+pauseTemp); pauseTemp = 0; } sendCommand(c); document.getElementById('hotLoad').style.visibility = "hidden"; } } // Set the speed factor (percent) function setSpeedFactor(speed){ console.log("Setting speed factor to: "+speed); sendCommand("M220 S" + speed); currentSpeed = speed; document.getElementById('speedFactor').value = currentSpeed; } // One off inits, tasks, etc to be done after page is loaded function startupTasks(){ dt = $('#filesList').DataTable( { columns: [ { title: "L" }, { title: "Name" } ], searching: false, fixedHeader: false, ordering: false, info: false, pageLength: 4, lengthChange: false, select: { items: "row", single: true}, fnDrawCallback: function() { $("#filesList thead").remove(); } } ); // Onclick handlers for file list $('#filesList tbody').on( 'click', 'tr', function () { var origin = this.cells[0].innerHTML; var name = this.cells[1].innerHTML; switch(origin){ case "local": bootbox.prompt({ title: name, inputType: 'checkbox', inputOptions: [ { text: 'Load ' + name + ' for printing', value: '1' }, { text: 'Print ' + name + ' now', value: '2' }, { text: 'Copy ' + name + ' to USB', value: '3' }, { text: 'Delete ' + name, value: '4' }], callback: function (result) { if(typeof result !== 'undefined' && result != null){ result.forEach(function(r){ switch(r){ case "1": selectFile("local/" + name); break; case "2": selectFile("local/" + name,true); watchLogFor["hideOverlay"] = "Printing"; watchLogFor.length++; showOverlay("Preparing to Print:\n" + name); break; case "3": copyToUsb(name); break; case "4": deleteFile(origin, name); break; } }); } } }); break; case "sdcard": selectFile(origin + "/" + name); break; case "usb": bootbox.prompt({ title: name, inputType: 'checkbox', inputOptions: [ { text: 'Copy ' + name + ' to local storage', value: '1' }, { text: 'Delete ' + name + ' from USB', value: '2' } ], callback: function (result) { if(typeof result !== 'undefined' && result != null){ result.forEach(function(r){ switch(r){ case "1": copyToLocal(name); break; case "2": deleteFile(origin, name); break; } }); } } }); break; } } ); getClientIP(); //Init the different popup number pads $('#eTempInput').numpad({ onKeypadClose: function(){ setExtruderTemp(Number(document.getElementById('eTempInput').value)); }, hidePlusMinusButton: true, hideDecimalButton: true }); $('#bTempInput').numpad({ onKeypadClose: function(){ setBedTemp(Number(document.getElementById('bTempInput').value)); }, hidePlusMinusButton: true, hideDecimalButton: true }); $('#speedFactor').numpad({ onKeypadClose: function(){ setSpeedFactor(Number(document.getElementById('speedFactor').value)); }, hidePlusMinusButton: true, hideDecimalButton: true }); //Init zMenu zdt = $('#zMenuTable').DataTable( { columns: [ { title: "Height" }, { title: "Event" }, { title: "Arg" }, { title: "Remove" } ], searching: false, fixedHeader: false, ordering: false, info: false, pageLength: 6, lengthChange: false, fnDrawCallback: function() { $("#zMenuTable thead").remove(); } } ); $('#zMenuTable tbody').on( 'click', 'div.zdelete', function (){ zdt.row( $(this).parents('tr') ).remove().draw(); zNum--; if(zNum == 0){ addZMenuRow(); } } ); addZMenuRow(); document.getElementById('apiKey').innerHTML = apikey; document.getElementById('speedFactor').value = currentSpeed; getPrinterProfile(); updateFiles(); } function saveZMenu(){ hideZMenu(); if(printerStatus == "Printing" || printerStatus == "Paused"){ bootbox.alert({ message: "You cannot modify Z events while printing", backdrop: true }); }else{ if(zNum > 0){ watchForZ = []; var zCurrent = 0; var zVal; zdt.page('first').draw('page'); while(zCurrent < zIndex){ if(zCurrent % 6 == 0 && zCurrent > 0){ zdt.page('next').draw('page'); } if($.isNumeric(document.getElementById('zh'+zCurrent).value)){ watchForZ[zCurrent] = { 'height': Number(document.getElementById('zh'+zCurrent).value), 'action': document.getElementById('ze'+zCurrent).value, 'arg': document.getElementById('za'+zCurrent).value }; } zCurrent++; } } watchForZ.sort(dynamicSort("height")); console.log(watchForZ); bootbox.alert({ message: "Z Events Saved", backdrop: true }); rebuildZMenu(); } } function rebuildZMenu(){ zdt.clear(); if(typeof watchForZ[0] !== 'undefined' && watchForZ[0] != null){ zIndex = 0; zNum = 0; var h; var e; var a; watchForZ.forEach(function(f){ h = "<input type=text size=3 id='zh" + zIndex + "' value='" + f.height + "'>"; e = "<select id='ze" + zIndex + "'>"; zEvents.forEach(function(z){ e = e + "<option value='" + z.command + "'"; if(f.action == z.command){ e = e + " selected=true"; } e = e +">" + z.label + "</option>"; }); e = e + "</select>"; a = "<input type=text size=3 id='za" + zIndex + "' value = '" + f.arg + "'>"; zdt.row.add([h, e, a, "<div class='zdelete'>X</div>"]).draw(); zdt.page('last').draw('page'); $('#zh'+zIndex).numpad({ hidePlusMinusButton: true, decimalSeparator: '.' }); $('#za'+zIndex).numpad({ hidePlusMinusButton: true, decimalSeparator: '.' }); zIndex++; zNum++; }); }else{ addZMenuRow(); } } // add new Blank row to Z Menu function addZMenuRow(){ if(printerStatus == "Printing" || printerStatus == "Paused"){ bootbox.alert({ message: "You cannot modify Z events while printing", backdrop: true }); }else{ var h = "<input type=text size=3 id='zh" + zIndex + "'>"; var e = "<select id='ze" + zIndex + "'>"; zEvents.forEach(function(z){ e = e + "<option value='" + z.command + "'>" + z.label + "</option>"; }); e = e + "</select>"; var a = "<input type=text size=3 id='za" + zIndex + "'>"; zdt.row.add([h, e, a, "<div class='zdelete'>X</div>"]).draw(); zdt.page('last').draw('page'); $('#zh'+zIndex).numpad({ hidePlusMinusButton: true, decimalSeparator: '.' }); $('#za'+zIndex).numpad({ hidePlusMinusButton: true, decimalSeparator: '.' }); zIndex++; zNum++; } } // Show zMenu function showZMenu(){ if(zIndex == 0){ addZMenuRow(); } document.getElementById('zMenu').style.width = "100%"; } // Hide zMenu function hideZMenu(){ document.getElementById('zMenu').style.width = "0"; } // Set overlay to visible with given content function showOverlay(content){ document.getElementById('overlayContent').innerHTML = content; document.getElementById('overlay').style.width = "100%"; } // Hide the overlay and empty it's content function hideOverlay(){ document.getElementById('overlay').style.width = "0"; document.getElementById('overlayContent').innerHTML = ""; } //Update status every second window.setInterval( function(){ updateStatus(); }, 1000); //Basic settings for all popup touchpads $.fn.numpad.defaults.gridTpl = '<table class="table modal-content" style="width:80%"></table>'; $.fn.numpad.defaults.backgroundTpl = '<div class="modal-backdrop in"></div>'; $.fn.numpad.defaults.displayTpl = '<input type="text" class="form-control" />'; $.fn.numpad.defaults.buttonNumberTpl = '<button type="button" class="btn btn-default" style="width:75%"></button>'; $.fn.numpad.defaults.buttonFunctionTpl = '<button type="button" class="btn" style="width:100%;"></button>'; $.fn.numpad.defaults.onKeypadCreate = function(){$(this).find('.done').addClass('btn-primary');}
www/include/octogui.js
var hotLoadZLift = 0; // Specify how high to lift the head when changing filament var sock = new SockJS('http://' + window.location.host + '/sockjs?apikey='+apikey); var api = "http://" + window.location.host + "/api/"; var apikey = "ABAABABB"; var printerStatus = "Checking..."; var etemp = "--"; // Current Nozzel Temperature var etempTarget = "--"; // Current Nozzel Target Temperature var btemp = "--"; // Current Bed Temperature var btempTarget = "--"; // Current Bed Target Temperature var sortBy = "name"; // Sort Order var sortRev = false; // Sort order reverse flag var printerId; // Printer profile ID var heatedBed = false; // Heated Bed Flag var currentZ; // Current Z height var returnX = null; // X pos to return to after lifting head var returnY = null; // Y pos to return to after lifting head var returnZ; // Z pos to return to after lifting head var returnE; // Extruder position to return to after chaning filament var watchLogFor = []; // Array of thing to watch the printer logs for var watchForZ = []; // Array of Z heights to watch for var zdt; // Z Menu DataTable handle var zIndex = 0; // Z Menu build number var zNum = 0; // Z Menu item count var zEventList = []; // Array for handing entry of Z events var hotLoading = false; // Flag for changing filament mid-print var liftOnPause = false; // Flag for automatically lifting the print head and retracting filament on pause var maxZHeight = 0; // Max printable Z height var currentSpeed = 100; // Current speed (percentage) of print var pauseTimeout = 0; // Time when current print job was paused var pauseTemp = 0; // Extruder temp when print job was paused var dt; // fileList DataTables handle var reconnect = false; // variable to automatically reconnect to the printer when disconnected // Z Events var zEvents = []; zEvents.push({ "command":"Filament", "label":"Change Filament" }); zEvents.push({ "command":"Speed", "label":"Change Speed" }); zEvents.push({ "command":"ExtruderTemp", "label":"Extruder Temperature" }); zEvents.push({ "command":"BedTemp", "label":"Bed Temperature" }); // Calibration GCODE var calibrateString = []; calibrateString['eris'] = [ "M202 Z1850", "G69 S2", "G68", "G30 S2", "M202 Z400", "M500", "G4 S2", "M115" ]; calibrateString['orion'] = [ "G69 S2", "M117 ENDSTOPS CALIBRATED", "G68 ", "M117 HORIZONTAL RADIUS CALIBRATED", "G30 S2 ", "M117 Z Height Calibrated", "G4 S2", "M500", "M117 CALIBRATION SAVED", "M115" ]; calibrateString['rostock_max_v3'] = [ "G69 S2", "M117 ENDSTOPS CALIBRATED", "G68 ", "M117 HORIZONTAL RADIUS CALIBRATED", "G30 S2 ", "M117 Z Height Calibrated", "G4 S2", "M500", "M117 CALIBRATION SAVED", "M115" ]; // GCODE to Load filament var loadFilamentString = []; loadFilamentString['eris'] = [ "G28", "M109 S220", "G91", "G1 E530 F5000", "G1 E100 F150", "G90", "G92 E0", "M104 S0", "M84", "M115" ]; loadFilamentString['orion'] = [ "G28", "M109 S220", "G91", "G1 E560 F5000", "G1 E100 F150", "G90", "G92 E0", "M104 S0", "M84", "M115" ]; loadFilamentString['rostock_max_v3'] = [ "G28", "M109 S220", "G91", "G1 E750 F5000", "G1 E100 F150", "G90", "G92 E0", "M104 S0", "M84", "M115" ]; // GCODE to unload filament var unloadFilamentString = []; unloadFilamentString['eris'] = [ "G28", "M109 S220", "G91", "G1 E30 F75", "G1 E-75 F5000", "G90", "G92 E0", "G4 S3", "G91", "G1 E-600", "M104 S0", "G90", "G92 E0", "M84", "M115" ]; unloadFilamentString['orion'] = [ "G28", "M109 S220", "G91", "G1 E30 F75", "G1 E-75 F5000", "G90", "G92 E0", "G4 S3", "G91", "G1 E-600", "M104 S0", "G90", "G92 E0", "M84", "M115" ]; unloadFilamentString['rostock_max_v3'] = [ "G28", "M109 S220", "G91", "G1 E30 F75", "G1 E-75 F5000", "G90", "G92 E0", "G4 S3", "G91", "G1 E-840", "M104 S0", "G90", "G92 E0", "M84", "M115" ]; // GCODE to unload filament mid-print var hotUnloadString = []; hotUnloadString['eris'] = [ "G91", "G1 E-75 F5000", "G90", "G92 E0", "G4 S3", "G91", "G1 E-600", "G90", "G92 E0" ]; hotUnloadString['orion'] = [ "G91", "G1 E-75 F5000", "G90", "G92 E0", "G4 S3", "G91", "G1 E-600", "G90", "G92 E0" ]; hotUnloadString['rostock_max_v3'] = [ "G91", "G1 E-75 F5000", "G90", "G92 E0", "G4 S3", "G91", "G1 E-830", "G90", "G92 E0" ]; // GCODE to load filament mid-print var hotLoadString = []; hotLoadString['eris'] = [ "G91", "G1 E530 F5000", "G1 E80 F150", "G90", "G92 E0" ]; hotLoadString['orion'] = [ "G91", "G1 E560 F5000", "G1 E80 F150", "G90", "G92 E0" ]; hotLoadString['rostock_max_v3'] = [ "G91", "G1 E750 F5000", "G1 E100 F150", "G90", "G92 E0" ]; // SockJS info from Octoprint sock.onopen = function(){ //Slow down the update frequency to 1hz sock.send( JSON.stringify({"throttle": 2} )); //Ask for M115 info on status change if(typeof watchLogFor['filamentInfo'] == 'undefined' && printerStatus != "Closed" && printerStatus != "Connecting" && printerStatus != "Detecting serial port"){ watchLogFor['firmwareInfo'] = "FIRMWARE"; watchLogFor.length++; watchLogFor['filamentInfo'] = "Printed filament"; watchLogFor.length++; sendCommand("M115"); } } // SockJS message handling sock.onmessage = function(e) { //Only process "current" messages if (typeof e.data.current !== 'undefined'){ var t; //watch for Z height actions if(typeof watchForZ[0] !== 'undefined'){ if(printerStatus == "Printing" && currentZ == e.data.current.currentZ && currentZ >= watchForZ[0]['height'] && currentZ != null){ spottedZ(watchForZ[0]['action'],watchForZ[0]['arg']); watchForZ.splice(0,1); } } currentZ = e.data.current.currentZ; document.getElementById('currentZ').innerHTML = currentZ; if (e.data.current.progress.completion !== null){ document.getElementById('currentPercent').innerHTML = e.data.current.progress.completion.toFixed(2); } document.getElementById('currentPrintTime').innerHTML = humanTime(e.data.current.progress.printTime); document.getElementById('currentPrintTimeLeft').innerHTML = humanTime(e.data.current.progress.printTimeLeft); //watch for Log actions if(watchLogFor.length > 0){ for(var i in watchLogFor){ for(var l in e.data.current.logs){ if(t = e.data.current.logs[l].includes(watchLogFor[i])){ spottedLog(i, e.data.current.logs[l]); } } } } } }; // Actions to take when Z height is hit function spottedZ(action,arg){ switch(action){ case "Speed": console.log("Setting speed to " + arg + " at z: " + currentZ); setSpeedFactor(arg); break; case "Filament": console.log("Changing Filament at z: " + currentZ); printCommand("pause"); liftOnPause = true; break; case "ExtruderTemp": console.log("Setting Extruder Temp to " + arg + " at z: " + currentZ); setExtruderTemp(arg); break; case "BedTemp": console.log("Setting Bed Temp to " + arg + " at z: " + currentZ); setBedTemp(arg); break; } } // Actions to take when a given string is spotted in the log function spottedLog(key, log){ log = log.replace(/Recv:\ /,''); switch(key){ case "COMMERROR": // Connection error - usually happens after cancelling a print on a Rostock delete watchLogFor[key]; watchLogFor.length--; connectPrinter("disconnect"); reconnect = true; break; case "E": // Logging return extruder position returnE = log.replace(/.*\ E/,''); returnE = returnE.replace(/\*.*/,''); if(log.includes("X")){ returnX = log.replace(/.*\ X/,''); returnX = returnX.replace(/\*.*/,''); } if(log.includes("Y")){ returnY = log.replace(/.*\ Y/,''); returnY = returnY.replace(/\*.*/,''); } break; case "stateToPaused": // Hotunload trigger console.log("Printer is paused. Last E is " + returnE); if(returnE > 0) { document.getElementById('hotUnload').style.visibility = "visible"; if(liftOnPause){ pauseUnload(); } } delete watchLogFor[key]; watchLogFor.length--; delete watchLogFor["E"]; watchLogFor.length--; console.log("Return XY: " + returnX + "/" + returnY); break; case "firmwareInfo": // Use Firmware info to verify printer model var pId; var fw = log.replace(/FIRMWARE_NAME:/,''); var fwd = log.replace(/.*_DATE:/,''); var fwp = log.replace(/.*MACHINE_TYPE:/,''); fw = fw.replace(/\ .*/,''); fwd = fwd.replace(/\ .*/,''); document.getElementById('firmwareInfo').style.visibility = "visible"; document.getElementById('firmwareInfo').innerHTML = fw; document.getElementById('firmwareDate').style.visibility = "visible"; document.getElementById('firmwareDate').innerHTML = fwd; switch(fwp){ case "ERIS Delta": pId = "eris"; break; case "ORION Delta": pId = "orion"; break; case "Rostock Max v2": pId = "rostock_max_v2"; break; case "Rostock MAX v3": pId = "rostock_max_v3"; break; default: pId = 'default'; console.log("Printer ("+fwp+") not supported!"); break; } if(pId != printerId){ setPrinterProfile(pId); } delete watchLogFor[key]; watchLogFor.length--; //Init trap for Comm Error if it's not alreay set if(typeof watchLogFor['COMMERROR'] == 'undefined'){ watchLogFor['COMMERROR'] = 'sufficient'; watchLogFor.length++; } break; case "filamentInfo": // Update amount of filament used document.getElementById('filamentInfo').style.visibility = "visible"; document.getElementById('filamentInfo').innerHTML = log; delete watchLogFor[key]; watchLogFor.length--; break; case "hideOverlay": // Set the Overlay to hidden hideOverlay(); delete watchLogFor[key]; watchLogFor.length--; break; } } // Find the current IP of the client and update it on screen function getClientIP() { window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){}; pc.createDataChannel(""); pc.createOffer(pc.setLocalDescription.bind(pc), noop); pc.onicecandidate = function(ice){ if(!ice || !ice.candidate || !ice.candidate.candidate) return; var myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1]; window.clientIP = myIP; document.getElementById("clientIP").innerHTML = myIP; pc.onicecandidate = noop; }; } // Sort an array by the given property function dynamicSort(property) { var sortOrder = 1; if(property[0] === "-") { sortOrder = -1; property = property.substr(1); } return function (a,b) { var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0; return result * sortOrder; } } // Basic on/off fan controll function fanControl(c){ var gcode; if(c == "on"){ sendCommand("M106"); } else { sendCommand("M107"); } } // Send the Calibrate GCODE to the printer if it is configured and the printer is Operational function calibratePrinter(){ if(printerStatus == "Operational"){ if (typeof calibrateString[printerId] !== 'undefined'){ bootbox.confirm("Make sure the print bed is clear and there is no filament hanging from the extruder.", function(result){ if(result){ sendCommand(calibrateString[printerId]); watchLogFor["hideOverlay"] = "MACHINE_TYPE"; watchLogFor.length++; showOverlay("Printer is Calibrating"); } }); }else{ bootbox.alert({ message: "Calibration script is not set for the " + printerId, backdrop: true }); } }else{ bootbox.alert({ message: "Cannot calibrate when printer is " + printerStatus, backdrop: true }); } } // Load filament if it is configured and the printer is Operational function loadFilament(){ if(printerStatus == "Operational"){ if (typeof loadFilamentString[printerId] !== 'undefined'){ bootbox.confirm("You are about to LOAD filament. Make sure that it is 1 inch past the end of the extruder.", function(result){ if(result){ sendCommand(loadFilamentString[printerId]); watchLogFor["hideOverlay"] = "MACHINE_TYPE"; watchLogFor.length++; showOverlay("Heating nozzel and<br>Loading Filament"); } }); } else{ bootbox.alert({ message: "Load Filament script is not set for the " + printerId, backdrop: true }); } }else{ bootbox.alert({ message: "Cannot load filament when printer is " + printerStatus, backdrop: true }); } } // Unload filament if it is configured and the printer is Operational function unloadFilament(){ if(printerStatus == "Operational"){ if (typeof unloadFilamentString[printerId] !== 'undefined'){ bootbox.confirm("You are about to UNLOAD filament. Please Confirm this is what you want to do.", function(result){ if(result){ sendCommand(unloadFilamentString[printerId]); watchLogFor["hideOverlay"] = "MACHINE_TYPE"; watchLogFor.length++; showOverlay("Heating nozzel and<br>Retracting Filament"); } }); } else{ bootbox.alert({ message: "Unload Filament script is not set for the " + printerId, backdrop: true }); } }else{ bootbox.alert({ message: "Cannot load filament when printer is " + printerStatus, backdrop: true }); } } // Set the Nozzel temperature function setExtruderTemp(target){ $.ajax({ url: api+"printer/tool?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: JSON.stringify({"command":"target","targets":{"tool0": target}}) }); etempTarget = target; document.getElementById('extruderTempTarget').innerHTML = etempTarget; document.getElementById('eTempInput').value = etempTarget; } // Set the Bed temperature function setBedTemp(target){ if(heatedBed){ $.ajax({ url: api+"printer/bed?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: JSON.stringify({"command":"target","target":target}) }); btempTarget = target; document.getElementById('bedTempTarget').innerHTML = btempTarget; document.getElementById('bTempInput').value = btempTarget; }else{ bootbox.alert({ message: "Cannot set bed temp.<br>No heated bed detected.", backdrop: true }); } } // Check and updated the current connection status for the printer function updateConnectionStatus(){ $.ajax({ url: api+"connection?apikey="+apikey, type: "get", contentType:"application/json; charset=utf-8", complete: (function(data,type){ if(type == "success"){ jdata = JSON.parse(data.responseText); //Reconnect check when connection is closed if(printerStatus == "Closed" && reconnect){ reconnect = false; connectPrinter("connect"); } //Clear Z events when a print job is completed or cancelled if(printerStatus == "Printing" && jdata.current.state != "Printing" && jdata.current.state != "Paused" && typeof watchForZ[0] !== 'undefined'){ watchForZ = []; console.log("Clearing Z events"); } //Update filament and firmware info when printer enters Operational state if(printerStatus != "Operational" && jdata.current.state == "Operational" && typeof watchLogFor['filamentInfo'] == 'undefined'){ watchLogFor['firmwareInfo'] = "FIRMWARE"; watchLogFor.length++; watchLogFor['filamentInfo'] = "Printed filament"; watchLogFor.length++; sendCommand("M115"); }else{ //In case the M115 command gets lost in the shuffle if(typeof watchLogFor['filamentInfo'] !== 'undefined' && printerStatus == "Operational"){ sendCommand("M115"); } } printerStatus = jdata.current.state; //Automaticaly reconnect if Z-probe errors borks the connection if(printerStatus.includes("Error: Z-probe failed")){ connectPrinter("connect"); printerStatus = "Connecting"; } }else{ printerStatus = "Unknown"; } }) }); } // Update non SockJS fields on the user interface function updateStatus(){ updateConnectionStatus(); //Shut down the hot end if paused too long if(printerStatus == "Paused" && pauseTimeout > 0){ if(pauseTimeout + (5 * 60 * 1000) <= (new Date().valueOf())){ console.log("Printer paused for too long. Shutting off hot end"); pauseTemp = etempTarget; setExtruderTemp(0); pauseTimeout = 0; } } if(printerStatus == "Operational" || printerStatus == "Printing" || printerStatus == "Paused"){ $.ajax({ url: api+"printer?apikey="+apikey, type: "get", contentType:"application/json; charset=utf-8", complete: (function(data,type){ if(type == "success"){ jdata = JSON.parse(data.responseText); etemp = jdata.temperature.tool0.actual; etempTarget = jdata.temperature.tool0.target; if(heatedBed && typeof jdata.temperature.bed !== 'undefined'){ btemp = jdata.temperature.bed.actual; btempTarget = jdata.temperature.bed.target; } updateJobStatus(); }else{ updateConnectionStatus(); etemp = "--"; btemp = "--"; } }) }); }else{ etemp = "--"; btemp = "--"; } document.getElementById('currentStatus').innerHTML = printerStatus; document.getElementById('extruderTemp').innerHTML = etemp; document.getElementById('bedTemp').innerHTML = btemp; document.getElementById('extruderTempTarget').innerHTML = etempTarget; document.getElementById('eTempInput').value = etempTarget; document.getElementById('bedTempTarget').innerHTML = btempTarget; document.getElementById('bTempInput').value = btempTarget; } // Updates the status fields for the current print job function updateJobStatus(){ $.ajax({ url: api+"job?apikey="+apikey, type: "get", contentType:"application/json; charset=utf-8", complete: (function(data,type){ if(type == "success"){ jdata = JSON.parse(data.responseText); document.getElementById('currentName').innerHTML = jdata.job.file.name; if (jdata.job.filament !== null && typeof jdata.job.filament.tool0 !== 'undefined') { document.getElementById('currentFilament').innerHTML = (jdata.job.filament.tool0.length / 1000).toFixed(2) + "m"; } }else{ document.getElementById('currentName').innerHTML = ""; document.getElementById('currentFilament').innerHTML = ""; } }) }); } // Have Octoprint load the current file and prep it for printing. Sending a second argument (true) starts the print after loading function selectFile(file,print){ print = print || 0; var c; if(print){ c = {"command":"select","print":true}; } else{ c = {"command":"select"}; } $.ajax({ url: api+"files/" + file +"?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: JSON.stringify(c), success: (function(){ updateStatus(); }) }); } // Changes the File sort field function setSortBy(s){ if(sortBy == s){ if(sortRev){ sortRev = false; } else{ sortRev = true; } }else{ sortRev = false; } sortBy = s; updateFiles(); } // Copies file from local storage to USB function copyToUsb(file){ var text; var currentPage = dt.page(); $.ajax({ url: "include/f.php?c=copyToUsb&f=" + file, type: "get", contentType:"application/json; charset=utf-8", complete: (function(data,type){ jdata = JSON.parse(data.responseText); if(jdata.status){ text = "File " + file + " copied to USB storage"; } else{ text = "Error copying " + file; } bootbox.alert({ message: text, backdrop: true }); }) }); } // Copies file from the USB stick to local storage function copyToLocal(file){ var text; var currentPage = dt.page(); $.ajax({ url: "include/f.php?c=copy&f=" + file, type: "get", contentType:"application/json; charset=utf-8", complete: (function(data,type){ jdata = JSON.parse(data.responseText); if(jdata.status){ text = "File " + file + " copied to local storage"; } else{ text = "Error copying " + file; } bootbox.alert({ message: text, backdrop: true }); document.getElementById('currentName').innerHTML = "Loading..."; document.getElementById('currentFilament').innerHTML = "Calculating..."; updateFiles(currentPage); updateStatus(); }) }); } // Deletes a given file from the given locations function deleteFile(origin, file){ var currentPage = dt.page(); switch(origin){ case "local": $.ajax({ url: api+ "files/local/" + file + "?apikey=" +apikey, type: "delete", contentType:"application/json; charset=utf-8", complete: (function(data,type){ if(data.status == 204){ updateFiles(currentPage); } else{ alert("Error deleting " + file); } }) }); break; case "usb": $.ajax({ url: "include/f.php?c=delete", type: "post", data: {"f" : file}, complete: (function(data,type){ jdata = JSON.parse(data.responseText); if(jdata.status == 1){ updateFiles(currentPage); } else{ alert("Error deleting " + file); } }) }); break; case "sdcard": $.ajax({ url: api+ "files/sdcard/" + file + "?apikey=" +apikey, type: "delete", contentType:"application/json; charset=utf-8", complete: (function(data,type){ if(data.status == 204){ updateFiles(currentPage); } else{ alert("Error deleting " + file); } }) }); break; } } // Refreshes the fileList table - keeps current page if provided function updateFiles(page){ page = page || 0; $.ajax({ url: "include/f.php?c=list", type: "get", contentType:"application/json; charset=utf-8", complete: (function(data,type){ if(type == "success"){ jdata = JSON.parse(data.responseText); dt.clear(); if(jdata == null){ dt.draw(); } else{ var sortString; if(sortRev){ sortString = "-" + sortBy; } else{ sortString = sortBy; } var files = jdata.sort(dynamicSort(sortString)); files.forEach(function(f){ dt.row.add([ f.origin, f.name ]); }); if(page > 0){ if(page >= (dt.page.info().pages)){ page = dt.page.info().pages - 1; } dt.page(page).draw(false); }else { dt.draw(); } } } }) }); } // Converts seconds to human readable hours, minutes, seconds function humanTime(d) { d = Number(d); var h = Math.floor(d / 3600); var m = Math.floor(d % 3600 / 60); var s = Math.floor(d % 3600 % 60); return ((h > 0 ? h + ":" + (m < 10 ? "0" : "") : "") + m + ":" + (s < 10 ? "0" : "") + s); } // Send given GCODE (single command or array of commands) to the printer via Octoprint function sendCommand(command){ var c; if(command instanceof Array){ c = { "commands": command }; } else{ c = { "command": command }; } $.ajax({ url: api+"printer/command?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: JSON.stringify(c) }); } // Home all Axis and disabled the stepper motors. TODO: Setup motor enable/disable fuctions/buttons function homePrinter(){ if(printerStatus == "Printing"){ bootbox.alert({ message: "Print job in progress. Cancel the job if you really want to home the print head.", backdrop: true }); }else{ $.ajax({ url: api+"printer/printhead?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: JSON.stringify({ 'command': "home", 'axes': [ 'x', 'y', 'z' ] }), success: (function(){ sendCommand("M84"); }) }); } } // Initiate connection to the printer function connectPrinter(com){ var c; if(com == "connect"){ $.ajax({ url: "include/f.php?c=port", type: "get", contentType:"application/json; charset=utf-8", complete: (function(data,type){ jdata = JSON.parse(data.responseText); if(jdata.port == "ERROR"){ c = { 'command': "connect","baudrate": 250000 }; } else{ c = { 'command': "connect","baudrate": 250000,"port": jdata.port }; } $.ajax({ url: api+"connection?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: JSON.stringify(c), success: (function(){ updateStatus(); }) }); }) }); } else { c = { 'command': "disconnect"}; printerStatus = "Disconnecting"; document.getElementById('currentStatus').innerHTML = printerStatus; $.ajax({ url: api+"connection?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: JSON.stringify(c), success: (function(){ updateStatus(); }) }); } } // Resume printing after pausing and changing filament function resumeHotLoad(){ document.getElementById('hotUnload').style.visibility = "hidden"; if(hotLoading){ if(returnX != null && returnY != null){ sendCommand( [ "G28", "90", "G0 X" + returnX + " Y" + returnY + " Z" + returnZ +" F1440 E2", "G92 E" + returnE ] ); }else{ sendCommand( [ "G28", "90", "G0 Z" + returnZ +" F1440 E2", "G92 E" + returnE ] ); } document.getElementById('hotLoad').style.visibility = "hidden"; hotLoading = false; returnE = 0; returnX = null; returnY = null; } } // Send basic print job command ( play, pause, cancel ) function printCommand(command){ var c; if(command == "pause"){ c = JSON.stringify({ 'command': "pause", 'action': 'toggle' }); if(printerStatus == "Printing" && currentZ < (maxZHeight - hotLoadZLift - 10)) { console.log("Printing paused at " + currentZ); watchLogFor['E'] = ' E'; watchLogFor.length++; watchLogFor['stateToPaused'] = 'Paused'; watchLogFor.length++; } if(printerStatus == "Paused") { resumeHotLoad(); } }else{ if(command == "start" && printerStatus == "Paused"){ c = JSON.stringify({ 'command': "pause", 'action': 'toggle' }); resumeHotLoad(); } else{ c = JSON.stringify({ 'command': command }); } } if(command == "cancel"){ bootbox.confirm("Are you sure you want to cancel the current print job?.", function(result){ if(result){ showOverlay("Canceling print job"); watchLogFor["hideOverlay"] = "Operational"; watchLogFor.length++; $.ajax({ url: api+"job?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: c, success: (function(){ setExtruderTemp(0); if(heatedBed){ setBedTemp(0); } }) }); } }); }else{ $.ajax({ url: api+"job?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: c }); } } // Head Jog command pulling increment from the GUI function jogHead(axis,dir){ var d; //jog distance jogI = $('input[name="jogIncrement"]:checked').val(); if(dir == "-"){ d = Number(dir + jogI); } else{ d = Number(jogI); } var c = {'command':'jog'}; c[axis] = d; $.ajax({ url: api+"printer/printhead?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: JSON.stringify(c) }); } // Head Job command with specified axis and increment function moveHead(axis,distance){ var c = {'command':'jog'}; c[axis] = distance; $.ajax({ url: api+"printer/printhead?apikey="+apikey, type: "post", contentType:"application/json; charset=utf-8", data: JSON.stringify(c) }); } // Set a new default connection profile and disconnect. Prompt to notify and delay reconnect function setPrinterProfile(newPrinterId){ connectPrinter("disconnect"); $.ajax({ url: api+"printerprofiles/" + newPrinterId + "?apikey="+apikey, type: "patch", contentType:"application/json; charset=utf-8", data: JSON.stringify({"profile":{"default":1}}), success: (function(){ getPrinterProfile(); bootbox.alert("New printer detected. Press OK to reconnect", function(){ connectPrinter("connect"); }); }) }); } // Get the currently selected default printer profile and set global vars function getPrinterProfile(){ $.ajax({ url: api+"printerprofiles?apikey="+apikey, type: "get", contentType:"application/json; charset=utf-8", complete: (function(data,type){ jdata = JSON.parse(data.responseText); for(i in jdata.profiles){ if(jdata.profiles[i].default){ printerId = jdata.profiles[i].id; heatedBed = jdata.profiles[i].heatedBed; maxZHeight = jdata.profiles[i].volume.height; document.getElementById('printerModel').innerHTML = jdata.profiles[i].name; if(heatedBed) { document.getElementById('bedTempDisplay').style.visibility = "visible"; document.getElementById('bedTempSet').style.visibility = "visible"; }else { document.getElementById('bedTempDisplay').style.visibility = "hidden"; document.getElementById('bedTempSet').style.visibility = "hidden"; } if(typeof calibrateString[printerId] !== 'undefined'){ document.getElementById('calibratePrinter').style.visibility = "visible"; } else { document.getElementById('calibratePrinter').style.visibility = "hidden"; } if(typeof loadFilamentString[printerId] !== 'undefined'){ document.getElementById('loadFilament').style.visibility = "visible"; } else { document.getElementById('loadFilament').style.visibility = "hidden"; } if(typeof unloadFilamentString[printerId] !== 'undefined'){ document.getElementById('unloadFilament').style.visibility = "visible"; } else { document.getElementById('unloadFilament').style.visibility = "hidden"; } if(typeof loadFilamentString[printerId] !== 'undefined'){ document.getElementById('loadFilament').style.visibility = "visible"; } else { document.getElementById('loadFilament').style.visibility = "hidden"; } if(printerId == 'eris'){ document.getElementById('fanControl').style.visibility = "hidden"; } else { document.getElementById('fanControl').style.visibility = "visible"; } } } }) }); } // whie paused, Raise print head and unload filament function pauseUnload(){ if(printerStatus == "Paused" && typeof hotUnloadString[printerId] !== 'undefined' && currentZ < (maxZHeight - hotLoadZLift - 10)){ if(returnE > 0){ hotLoading = true; returnZ = currentZ; //if(hotLoadZLift > 0){ moveHead('z',hotLoadZLift); } //else{ moveHead('z',(maxZHeight - 15)); } sendCommand("G28"); sendCommand(hotUnloadString[printerId]); document.getElementById('hotUnload').style.visibility = "hidden"; document.getElementById('hotLoad').style.visibility = "visible"; pauseTimeout = new Date().valueOf(); }else{ alert("Error. Last extruder position not found. Please Resume your print, then pause to try again."); } } } // Load filament after changing mid print, heating nozzel if necissary function playLoad(){ var c = hotLoadString[printerId]; if(printerStatus == "Paused" && typeof hotLoadString[printerId] !== 'undefined'){ if(pauseTemp > 0){ console.log("Heating extruder before loading filament"); c.unshift("M109 S"+pauseTemp); pauseTemp = 0; } sendCommand(c); document.getElementById('hotLoad').style.visibility = "hidden"; } } // Set the speed factor (percent) function setSpeedFactor(speed){ console.log("Setting speed factor to: "+speed); sendCommand("M220 S" + speed); currentSpeed = speed; document.getElementById('speedFactor').value = currentSpeed; } // One off inits, tasks, etc to be done after page is loaded function startupTasks(){ dt = $('#filesList').DataTable( { columns: [ { title: "L" }, { title: "Name" } ], searching: false, fixedHeader: false, ordering: false, info: false, pageLength: 4, lengthChange: false, select: { items: "row", single: true}, fnDrawCallback: function() { $("#filesList thead").remove(); } } ); // Onclick handlers for file list $('#filesList tbody').on( 'click', 'tr', function () { var origin = this.cells[0].innerHTML; var name = this.cells[1].innerHTML; switch(origin){ case "local": bootbox.prompt({ title: name, inputType: 'checkbox', inputOptions: [ { text: 'Load ' + name + ' for printing', value: '1' }, { text: 'Print ' + name + ' now', value: '2' }, { text: 'Copy ' + name + ' to USB', value: '3' }, { text: 'Delete ' + name, value: '4' }], callback: function (result) { if(typeof result !== 'undefined' && result != null){ result.forEach(function(r){ switch(r){ case "1": selectFile("local/" + name); break; case "2": selectFile("local/" + name,true); watchLogFor["hideOverlay"] = "Printing"; watchLogFor.length++; showOverlay("Preparing to Print:\n" + name); break; case "3": copyToUsb(name); break; case "4": deleteFile(origin, name); break; } }); } } }); break; case "sdcard": selectFile(origin + "/" + name); break; case "usb": bootbox.prompt({ title: name, inputType: 'checkbox', inputOptions: [ { text: 'Copy ' + name + ' to local storage', value: '1' }, { text: 'Delete ' + name + ' from USB', value: '2' } ], callback: function (result) { if(typeof result !== 'undefined' && result != null){ result.forEach(function(r){ switch(r){ case "1": copyToLocal(name); break; case "2": deleteFile(origin, name); break; } }); } } }); break; } } ); getClientIP(); //Init the different popup number pads $('#eTempInput').numpad({ onKeypadClose: function(){ setExtruderTemp(Number(document.getElementById('eTempInput').value)); }, hidePlusMinusButton: true, hideDecimalButton: true }); $('#bTempInput').numpad({ onKeypadClose: function(){ setBedTemp(Number(document.getElementById('bTempInput').value)); }, hidePlusMinusButton: true, hideDecimalButton: true }); $('#speedFactor').numpad({ onKeypadClose: function(){ setSpeedFactor(Number(document.getElementById('speedFactor').value)); }, hidePlusMinusButton: true, hideDecimalButton: true }); //Init zMenu zdt = $('#zMenuTable').DataTable( { columns: [ { title: "Height" }, { title: "Event" }, { title: "Arg" }, { title: "Remove" } ], searching: false, fixedHeader: false, ordering: false, info: false, pageLength: 6, lengthChange: false, fnDrawCallback: function() { $("#zMenuTable thead").remove(); } } ); $('#zMenuTable tbody').on( 'click', 'div.zdelete', function (){ zdt.row( $(this).parents('tr') ).remove().draw(); zNum--; if(zNum == 0){ addZMenuRow(); } } ); addZMenuRow(); document.getElementById('apiKey').innerHTML = apikey; document.getElementById('speedFactor').value = currentSpeed; getPrinterProfile(); updateFiles(); } function saveZMenu(){ if(printerStatus == "Printing" || printerStatus == "Paused"){ bootbox.alert({ message: "You cannot modify Z events while printing", backdrop: true }); }else{ if(zNum > 0){ watchForZ = []; var zCurrent = 0; var zVal; while(zCurrent < zIndex){ if($.isNumeric(document.getElementById('zh'+zCurrent).value)){ watchForZ[zCurrent] = { 'height': Number(document.getElementById('zh'+zCurrent).value), 'action': document.getElementById('ze'+zCurrent).value, 'arg': document.getElementById('za'+zCurrent).value }; } zCurrent++; } } watchForZ.sort(dynamicSort("height")); console.log(watchForZ); bootbox.alert({ message: "Z Events Saved", backdrop: true }); hideZMenu(); rebuildZMenu(); } } function rebuildZMenu(){ zdt.clear(); if(typeof watchForZ[0] !== 'undefined' && watchForZ[0] != null){ zIndex = 0; zNum = 0; var h e a; watchForZ.forEach(function(f){ h = "<input type=text size=3 id='zh" + zIndex + "' value='" + f.height + "'>"; e = "<select id='ze" + zIndex + "'>"; zEvents.forEach(function(z){ e = e + "<option value='" + z.command + "'"; if(f.action == z.command){ e = e + " selected=true"; } e = e +">" + z.label + "</option>"; }); e = e + "</select>"; a = "<input type=text size=3 id='za" + zIndex + "' value = '" + f.arg + "'>"; zdt.row.add([h, e, a, "<div class='zdelete'>X</div>"]).draw(); zdt.page('last').draw('page'); $('#zh'+zIndex).numpad({ hidePlusMinusButton: true, decimalSeparator: '.' }); $('#za'+zIndex).numpad({ hidePlusMinusButton: true, decimalSeparator: '.' }); zIndex++; zNum++; }); }else{ addZMenuRow(); } } // add new Blank row to Z Menu function addZMenuRow(){ if(printerStatus == "Printing" || printerStatus == "Paused"){ bootbox.alert({ message: "You cannot modify Z events while printing", backdrop: true }); }else{ var h = "<input type=text size=3 id='zh" + zIndex + "'>"; var e = "<select id='ze" + zIndex + "'>"; zEvents.forEach(function(z){ e = e + "<option value='" + z.command + "'>" + z.label + "</option>"; }); e = e + "</select>"; var a = "<input type=text size=3 id='za" + zIndex + "'>"; zdt.row.add([h, e, a, "<div class='zdelete'>X</div>"]).draw(); zdt.page('last').draw('page'); $('#zh'+zIndex).numpad({ hidePlusMinusButton: true, decimalSeparator: '.' }); $('#za'+zIndex).numpad({ hidePlusMinusButton: true, decimalSeparator: '.' }); zIndex++; zNum++; } } // Show zMenu function showZMenu(){ if(zIndex == 0){ addZMenuRow(); } document.getElementById('zMenu').style.width = "100%"; } // Hide zMenu function hideZMenu(){ document.getElementById('zMenu').style.width = "0"; } // Set overlay to visible with given content function showOverlay(content){ document.getElementById('overlayContent').innerHTML = content; document.getElementById('overlay').style.width = "100%"; } // Hide the overlay and empty it's content function hideOverlay(){ document.getElementById('overlay').style.width = "0"; document.getElementById('overlayContent').innerHTML = ""; } //Update status every second window.setInterval( function(){ updateStatus(); }, 1000); //Basic settings for all popup touchpads $.fn.numpad.defaults.gridTpl = '<table class="table modal-content" style="width:80%"></table>'; $.fn.numpad.defaults.backgroundTpl = '<div class="modal-backdrop in"></div>'; $.fn.numpad.defaults.displayTpl = '<input type="text" class="form-control" />'; $.fn.numpad.defaults.buttonNumberTpl = '<button type="button" class="btn btn-default" style="width:75%"></button>'; $.fn.numpad.defaults.buttonFunctionTpl = '<button type="button" class="btn" style="width:100%;"></button>'; $.fn.numpad.defaults.onKeypadCreate = function(){$(this).find('.done').addClass('btn-primary');}
Dancing around the visibility zmenu problem
www/include/octogui.js
Dancing around the visibility zmenu problem
<ide><path>ww/include/octogui.js <ide> <ide> function saveZMenu(){ <ide> <add> hideZMenu(); <ide> if(printerStatus == "Printing" || printerStatus == "Paused"){ <ide> bootbox.alert({ message: "You cannot modify Z events while printing", backdrop: true }); <ide> }else{ <ide> watchForZ = []; <ide> var zCurrent = 0; <ide> var zVal; <add> zdt.page('first').draw('page'); <ide> while(zCurrent < zIndex){ <add> if(zCurrent % 6 == 0 && zCurrent > 0){ zdt.page('next').draw('page'); } <ide> if($.isNumeric(document.getElementById('zh'+zCurrent).value)){ <ide> watchForZ[zCurrent] = { 'height': Number(document.getElementById('zh'+zCurrent).value), 'action': document.getElementById('ze'+zCurrent).value, 'arg': document.getElementById('za'+zCurrent).value }; <ide> } <ide> watchForZ.sort(dynamicSort("height")); <ide> console.log(watchForZ); <ide> bootbox.alert({ message: "Z Events Saved", backdrop: true }); <del> hideZMenu(); <ide> rebuildZMenu(); <ide> } <ide> <ide> zdt.clear(); <ide> if(typeof watchForZ[0] !== 'undefined' && watchForZ[0] != null){ <ide> zIndex = 0; zNum = 0; <del> var h e a; <add> var h; <add> var e; <add> var a; <ide> watchForZ.forEach(function(f){ <ide> h = "<input type=text size=3 id='zh" + zIndex + "' value='" + f.height + "'>"; <ide> e = "<select id='ze" + zIndex + "'>";
Java
apache-2.0
error: pathspec 'jsprit-core/src/main/java/jsprit/core/reporting/SolutionPrinter.java' did not match any file(s) known to git
7cff3c58eccfdc4fa787d6acf50fff350f1a8875
1
HeinrichFilter/jsprit,michalmac/jsprit,balage1551/jsprit,sinhautkarsh2014/winter_jsprit,muzuro/jsprit,graphhopper/jsprit
/******************************************************************************* * Copyright (C) 2013 Stefan Schroeder * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3.0 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package jsprit.core.reporting; import jsprit.core.problem.VehicleRoutingProblem; import jsprit.core.problem.job.Job; import jsprit.core.problem.job.Service; import jsprit.core.problem.job.Shipment; import jsprit.core.problem.solution.VehicleRoutingProblemSolution; import jsprit.core.problem.solution.route.VehicleRoute; import jsprit.core.problem.solution.route.activity.TourActivity; import jsprit.core.problem.solution.route.activity.TourActivity.JobActivity; /** * Printer to print the details of a vehicle-routing-problem solution. * * @author stefan schroeder * */ public class SolutionPrinter { /** * Enum to indicate verbose-level. * * <p> Print.CONCISE and Print.VERBOSE are available. * * @author stefan schroeder * */ public enum Print { CONCISE,VERBOSE } /** * Prints costs and #vehicles to stdout (System.out.println). * * @param solution */ public static void print(VehicleRoutingProblemSolution solution){ System.out.println("[costs="+solution.getCost() + "]"); System.out.println("[#vehicles="+solution.getRoutes().size() + "]"); } private static class Jobs { int nServices; int nShipments; public Jobs(int nServices, int nShipments) { super(); this.nServices = nServices; this.nShipments = nShipments; } } public static void print(VehicleRoutingProblem problem, VehicleRoutingProblemSolution solution, Print print){ String leftAlign = "| %-13s | %-8s | %n"; System.out.format("+--------------------------+%n"); System.out.printf("| problem |%n"); System.out.format("+---------------+----------+%n"); System.out.printf("| indicator | value |%n"); System.out.format("+---------------+----------+%n"); System.out.format(leftAlign, "nJobs", problem.getJobs().values().size()); Jobs jobs = getNuOfJobs(problem); System.out.format(leftAlign, "nServices",jobs.nServices); System.out.format(leftAlign, "nShipments",jobs.nShipments); System.out.format(leftAlign, "fleetsize",problem.getFleetSize().toString()); System.out.format("+--------------------------+%n"); String leftAlignSolution = "| %-13s | %-40s | %n"; System.out.format("+----------------------------------------------------------+%n"); System.out.printf("| solution |%n"); System.out.format("+---------------+------------------------------------------+%n"); System.out.printf("| indicator | value |%n"); System.out.format("+---------------+------------------------------------------+%n"); System.out.format(leftAlignSolution, "costs",solution.getCost()); System.out.format(leftAlignSolution, "nVehicles",solution.getRoutes().size()); System.out.format("+----------------------------------------------------------+%n"); if(print.equals(Print.VERBOSE)){ printVerbose(problem,solution); } } private static void printVerbose(VehicleRoutingProblem problem, VehicleRoutingProblemSolution solution) { String leftAlgin = "| %-7s | %-20s | %-21s | %-15s | %-15s | %-15s | %-15s |%n"; System.out.format("+--------------------------------------------------------------------------------------------------------------------------------+%n"); System.out.printf("| detailed solution |%n"); System.out.format("+---------+----------------------+-----------------------+-----------------+-----------------+-----------------+-----------------+%n"); System.out.printf("| route | vehicle | activity | job | arrTime | endTime | costs |%n"); int routeNu = 1; for(VehicleRoute route : solution.getRoutes()){ System.out.format("+---------+----------------------+-----------------------+-----------------+-----------------+-----------------+-----------------+%n"); double costs = 0; System.out.format(leftAlgin, routeNu, route.getVehicle().getId(), route.getStart().getName(), "-", "undef", Math.round(route.getStart().getEndTime()),Math.round(costs)); TourActivity prevAct = route.getStart(); for(TourActivity act : route.getActivities()){ String jobId; if(act instanceof JobActivity) jobId = ((JobActivity)act).getJob().getId(); else jobId = "-"; double c = problem.getTransportCosts().getTransportCost(prevAct.getLocationId(), act.getLocationId(), prevAct.getEndTime(), route.getDriver(), route.getVehicle()); c+= problem.getActivityCosts().getActivityCost(act, act.getArrTime(), route.getDriver(), route.getVehicle()); costs+=c; System.out.format(leftAlgin, routeNu, route.getVehicle().getId(), act.getName(), jobId, Math.round(act.getArrTime()), Math.round(act.getEndTime()),Math.round(costs)); prevAct=act; } double c = problem.getTransportCosts().getTransportCost(prevAct.getLocationId(), route.getEnd().getLocationId(), prevAct.getEndTime(), route.getDriver(), route.getVehicle()); c+= problem.getActivityCosts().getActivityCost(route.getEnd(), route.getEnd().getArrTime(), route.getDriver(), route.getVehicle()); costs+=c; System.out.format(leftAlgin, routeNu, route.getVehicle().getId(), route.getEnd().getName(), "-", Math.round(route.getEnd().getArrTime()), "undef", Math.round(costs)); routeNu++; } System.out.format("+--------------------------------------------------------------------------------------------------------------------------------+%n"); } private static Jobs getNuOfJobs(VehicleRoutingProblem problem) { int nShipments = 0; int nServices = 0; for(Job j : problem.getJobs().values()){ if(j instanceof Shipment) nShipments++; if(j instanceof Service) nServices++; } return new Jobs(nServices,nShipments); } // /** // * Prints the details of the solution according to a print-level, i.e. Print.CONCISE or PRINT.VERBOSE. // * // * <p>CONCISE prints total-costs and #vehicles. // * <p>VERBOSE prints the route-details additionally. If the DefaultVehicleRouteCostCalculator (which is the standard-calculator) // * is used in VehicleRoute, then route-costs are differentiated further between transport, activity, vehicle, driver and other-costs. // * // * @param solution // * @param level // * // * @deprecated is not going to work anymore // */ // @Deprecated // public static void print(VehicleRoutingProblemSolution solution, Print level){ // if(level.equals(Print.CONCISE)){ // print(solution); // } // else{ // print(solution); // System.out.println("routes"); // int routeCount = 1; // for(VehicleRoute route : solution.getRoutes()){ // System.out.println("[route="+routeCount+"][departureTime="+route.getStart().getEndTime()+"[total=" + route.getCost() + "]"); // if(route.getVehicleRouteCostCalculator() instanceof DefaultVehicleRouteCostCalculator){ // DefaultVehicleRouteCostCalculator defaultCalc = (DefaultVehicleRouteCostCalculator) route.getVehicleRouteCostCalculator(); // System.out.println("[transport=" + defaultCalc.getTpCosts() + "][activity=" + defaultCalc.getActCosts() + // "][vehicle=" + defaultCalc.getVehicleCosts() + "][driver=" + defaultCalc.getDriverCosts() + "][other=" + defaultCalc.getOther() + "]"); // } // routeCount++; // } // } // // // } }
jsprit-core/src/main/java/jsprit/core/reporting/SolutionPrinter.java
add SolutionPrinter to core
jsprit-core/src/main/java/jsprit/core/reporting/SolutionPrinter.java
add SolutionPrinter to core
<ide><path>sprit-core/src/main/java/jsprit/core/reporting/SolutionPrinter.java <add>/******************************************************************************* <add> * Copyright (C) 2013 Stefan Schroeder <add> * <add> * This library is free software; you can redistribute it and/or <add> * modify it under the terms of the GNU Lesser General Public <add> * License as published by the Free Software Foundation; either <add> * version 3.0 of the License, or (at your option) any later version. <add> * <add> * This library is distributed in the hope that it will be useful, <add> * but WITHOUT ANY WARRANTY; without even the implied warranty of <add> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU <add> * Lesser General Public License for more details. <add> * <add> * You should have received a copy of the GNU Lesser General Public <add> * License along with this library. If not, see <http://www.gnu.org/licenses/>. <add> ******************************************************************************/ <add>package jsprit.core.reporting; <add> <add>import jsprit.core.problem.VehicleRoutingProblem; <add>import jsprit.core.problem.job.Job; <add>import jsprit.core.problem.job.Service; <add>import jsprit.core.problem.job.Shipment; <add>import jsprit.core.problem.solution.VehicleRoutingProblemSolution; <add>import jsprit.core.problem.solution.route.VehicleRoute; <add>import jsprit.core.problem.solution.route.activity.TourActivity; <add>import jsprit.core.problem.solution.route.activity.TourActivity.JobActivity; <add> <add>/** <add> * Printer to print the details of a vehicle-routing-problem solution. <add> * <add> * @author stefan schroeder <add> * <add> */ <add>public class SolutionPrinter { <add> <add> /** <add> * Enum to indicate verbose-level. <add> * <add> * <p> Print.CONCISE and Print.VERBOSE are available. <add> * <add> * @author stefan schroeder <add> * <add> */ <add> public enum Print { <add> <add> CONCISE,VERBOSE <add> } <add> <add> /** <add> * Prints costs and #vehicles to stdout (System.out.println). <add> * <add> * @param solution <add> */ <add> public static void print(VehicleRoutingProblemSolution solution){ <add> System.out.println("[costs="+solution.getCost() + "]"); <add> System.out.println("[#vehicles="+solution.getRoutes().size() + "]"); <add> <add> } <add> <add> private static class Jobs { <add> int nServices; <add> int nShipments; <add> public Jobs(int nServices, int nShipments) { <add> super(); <add> this.nServices = nServices; <add> this.nShipments = nShipments; <add> } <add> } <add> <add> public static void print(VehicleRoutingProblem problem, VehicleRoutingProblemSolution solution, Print print){ <add> String leftAlign = "| %-13s | %-8s | %n"; <add> <add> System.out.format("+--------------------------+%n"); <add> System.out.printf("| problem |%n"); <add> System.out.format("+---------------+----------+%n"); <add> System.out.printf("| indicator | value |%n"); <add> System.out.format("+---------------+----------+%n"); <add> <add> System.out.format(leftAlign, "nJobs", problem.getJobs().values().size()); <add> Jobs jobs = getNuOfJobs(problem); <add> System.out.format(leftAlign, "nServices",jobs.nServices); <add> System.out.format(leftAlign, "nShipments",jobs.nShipments); <add> System.out.format(leftAlign, "fleetsize",problem.getFleetSize().toString()); <add> System.out.format("+--------------------------+%n"); <add> <add> <add> String leftAlignSolution = "| %-13s | %-40s | %n"; <add> System.out.format("+----------------------------------------------------------+%n"); <add> System.out.printf("| solution |%n"); <add> System.out.format("+---------------+------------------------------------------+%n"); <add> System.out.printf("| indicator | value |%n"); <add> System.out.format("+---------------+------------------------------------------+%n"); <add> System.out.format(leftAlignSolution, "costs",solution.getCost()); <add> System.out.format(leftAlignSolution, "nVehicles",solution.getRoutes().size()); <add> System.out.format("+----------------------------------------------------------+%n"); <add> <add> if(print.equals(Print.VERBOSE)){ <add> printVerbose(problem,solution); <add> } <add> } <add> <add> private static void printVerbose(VehicleRoutingProblem problem, VehicleRoutingProblemSolution solution) { <add> String leftAlgin = "| %-7s | %-20s | %-21s | %-15s | %-15s | %-15s | %-15s |%n"; <add> System.out.format("+--------------------------------------------------------------------------------------------------------------------------------+%n"); <add> System.out.printf("| detailed solution |%n"); <add> System.out.format("+---------+----------------------+-----------------------+-----------------+-----------------+-----------------+-----------------+%n"); <add> System.out.printf("| route | vehicle | activity | job | arrTime | endTime | costs |%n"); <add> int routeNu = 1; <add> for(VehicleRoute route : solution.getRoutes()){ <add> System.out.format("+---------+----------------------+-----------------------+-----------------+-----------------+-----------------+-----------------+%n"); <add> double costs = 0; <add> System.out.format(leftAlgin, routeNu, route.getVehicle().getId(), route.getStart().getName(), "-", "undef", Math.round(route.getStart().getEndTime()),Math.round(costs)); <add> TourActivity prevAct = route.getStart(); <add> for(TourActivity act : route.getActivities()){ <add> String jobId; <add> if(act instanceof JobActivity) jobId = ((JobActivity)act).getJob().getId(); <add> else jobId = "-"; <add> double c = problem.getTransportCosts().getTransportCost(prevAct.getLocationId(), act.getLocationId(), prevAct.getEndTime(), route.getDriver(), route.getVehicle()); <add> c+= problem.getActivityCosts().getActivityCost(act, act.getArrTime(), route.getDriver(), route.getVehicle()); <add> costs+=c; <add> System.out.format(leftAlgin, routeNu, route.getVehicle().getId(), act.getName(), jobId, Math.round(act.getArrTime()), Math.round(act.getEndTime()),Math.round(costs)); <add> prevAct=act; <add> } <add> double c = problem.getTransportCosts().getTransportCost(prevAct.getLocationId(), route.getEnd().getLocationId(), prevAct.getEndTime(), route.getDriver(), route.getVehicle()); <add> c+= problem.getActivityCosts().getActivityCost(route.getEnd(), route.getEnd().getArrTime(), route.getDriver(), route.getVehicle()); <add> costs+=c; <add> System.out.format(leftAlgin, routeNu, route.getVehicle().getId(), route.getEnd().getName(), "-", Math.round(route.getEnd().getArrTime()), "undef", Math.round(costs)); <add> routeNu++; <add> } <add> System.out.format("+--------------------------------------------------------------------------------------------------------------------------------+%n"); <add> } <add> <add> private static Jobs getNuOfJobs(VehicleRoutingProblem problem) { <add> int nShipments = 0; <add> int nServices = 0; <add> for(Job j : problem.getJobs().values()){ <add> if(j instanceof Shipment) nShipments++; <add> if(j instanceof Service) nServices++; <add> } <add> return new Jobs(nServices,nShipments); <add> } <add> <add>// /** <add>// * Prints the details of the solution according to a print-level, i.e. Print.CONCISE or PRINT.VERBOSE. <add>// * <add>// * <p>CONCISE prints total-costs and #vehicles. <add>// * <p>VERBOSE prints the route-details additionally. If the DefaultVehicleRouteCostCalculator (which is the standard-calculator) <add>// * is used in VehicleRoute, then route-costs are differentiated further between transport, activity, vehicle, driver and other-costs. <add>// * <add>// * @param solution <add>// * @param level <add>// * <add>// * @deprecated is not going to work anymore <add>// */ <add>// @Deprecated <add>// public static void print(VehicleRoutingProblemSolution solution, Print level){ <add>// if(level.equals(Print.CONCISE)){ <add>// print(solution); <add>// } <add>// else{ <add>// print(solution); <add>// System.out.println("routes"); <add>// int routeCount = 1; <add>// for(VehicleRoute route : solution.getRoutes()){ <add>// System.out.println("[route="+routeCount+"][departureTime="+route.getStart().getEndTime()+"[total=" + route.getCost() + "]"); <add>// if(route.getVehicleRouteCostCalculator() instanceof DefaultVehicleRouteCostCalculator){ <add>// DefaultVehicleRouteCostCalculator defaultCalc = (DefaultVehicleRouteCostCalculator) route.getVehicleRouteCostCalculator(); <add>// System.out.println("[transport=" + defaultCalc.getTpCosts() + "][activity=" + defaultCalc.getActCosts() + <add>// "][vehicle=" + defaultCalc.getVehicleCosts() + "][driver=" + defaultCalc.getDriverCosts() + "][other=" + defaultCalc.getOther() + "]"); <add>// } <add>// routeCount++; <add>// } <add>// } <add>// <add>// <add>// } <add> <add>}
JavaScript
mit
25bd3966f2d8f2eafcc9659268a219071034b72e
0
svangordon/latrones-cli,svangordon/latrones-cli
/* * * Navbar * */ import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; // import Drawer from 'material-ui/Drawer'; // import AppBar from 'material-ui/AppBar'; import SideNav from 'components/SideNav'; import TopNav from 'components/TopNav'; import { makeSelectWidth, makeSelectUser } from './selectors'; // import messages from './messages'; export class Navbar extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(props); this.state = { collapseDrawer: false, }; this.handleCollapseDrawer = this.handleCollapseDrawer.bind(this); this.expandedSideNavWidth = 140; this.collapsedSideNavWidth = 50; this.allowedRoutes = ['/', '/play']; // const MenuItems = [ // { // primaryText: 'Latr', // }, // { // primaryText: 'Home', // }, // { // primaryText: 'Play', // }, // ]; } handleCollapseDrawer() { this.setState({ collapseDrawer: !this.state.collapseDrawer }); } render() { if (!this.allowedRoutes.includes(this.props.location) || !this.props.user) { return null; } if (this.props.width >= 960) { const expanded = this.props.width >= 1280 && !this.state.collapseDrawer; return ( <SideNav avatar={this.props.user.avatar} expanded={expanded} handleCollapse={this.handleCollapseDrawer} /> ); } return <TopNav />; } } Navbar.propTypes = { // dispatch: PropTypes.func.isRequired, location: React.PropTypes.string, user: React.PropTypes.objectOf(PropTypes.string), width: PropTypes.number, }; const mapStateToProps = createStructuredSelector({ // Navbar: makeSelectNavbar(), user: makeSelectUser(), width: makeSelectWidth(), // route: makeSelectRoute(), }); function mapDispatchToProps(dispatch) { return { dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(Navbar);
app/containers/Navbar/index.js
/* * * Navbar * */ import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; // import Drawer from 'material-ui/Drawer'; // import AppBar from 'material-ui/AppBar'; import SideNav from 'components/SideNav'; import TopNav from 'components/TopNav'; import { makeSelectWidth, makeSelectUser } from './selectors'; // import messages from './messages'; export class Navbar extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(props); this.state = { collapseDrawer: false, }; this.handleCollapseDrawer = this.handleCollapseDrawer.bind(this); this.expandedSideNavWidth = 140; this.collapsedSideNavWidth = 50; this.allowedRoutes = ['/', '/play']; // const MenuItems = [ // { // primaryText: 'Latr', // }, // { // primaryText: 'Home', // }, // { // primaryText: 'Play', // }, // ]; } handleCollapseDrawer() { this.setState({ collapseDrawer: !this.state.collapseDrawer }); } render() { if (!this.allowedRoutes.includes(this.props.location) || !this.props.user) { return null; } if (this.props.width >= 960) { const expanded = this.props.width >= 1280 && !this.state.collapseDrawer; return ( <SideNav avatar={this.props.user.avatar} expanded={expanded} handleCollapse={this.handleCollapseDrawer} /> ); } return <TopNav />; } } Navbar.propTypes = { // dispatch: PropTypes.func.isRequired, location: React.PropTypes.string, user: { avatar: PropTypes.string, }, width: PropTypes.number, }; const mapStateToProps = createStructuredSelector({ // Navbar: makeSelectNavbar(), user: makeSelectUser(), width: makeSelectWidth(), // route: makeSelectRoute(), }); function mapDispatchToProps(dispatch) { return { dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(Navbar);
fix prop type
app/containers/Navbar/index.js
fix prop type
<ide><path>pp/containers/Navbar/index.js <ide> Navbar.propTypes = { <ide> // dispatch: PropTypes.func.isRequired, <ide> location: React.PropTypes.string, <del> user: { <del> avatar: PropTypes.string, <del> }, <add> user: React.PropTypes.objectOf(PropTypes.string), <ide> width: PropTypes.number, <ide> }; <ide>
JavaScript
mit
1d55d794568d194374b6326ebda8a9a022bcf4b6
0
JariRuinemans/curvitra,JariRuinemans/curvitra
/** * Base Avatar * * @param {Player} player */ function BaseAvatar(player) { EventEmitter.call(this); this.id = player.id; this.name = player.name; this.color = player.color; this.player = player; this.x = 0; this.y = 0; this.trail = new Trail(this); this.bonusStack = new BonusStack(this); this.angle = 0; this.velocityX = 0; this.velocityY = 0; this.angularVelocity = 0; this.alive = true; this.printing = false; this.score = 0; this.roundScore = 0; this.ready = false; this.present = true; if( BaseAvatar.prototype.speed === true){ BaseAvatar.prototype.velocity = 56; this.updateVelocities(); console.log('speed mode'); }else{ BaseAvatar.prototype.velocity = 16; this.updateVelocities(); console.log('normal mode'); } this.updateVelocities(); } BaseAvatar.prototype = Object.create(EventEmitter.prototype); BaseAvatar.prototype.constructor = BaseAvatar; /** * Movement velocity * * @type {Number} */ var doneTheStuff; function boosta(){ return; } /** * Turn velocity * * @type {Float} */ BaseAvatar.prototype.angularVelocityBase = 2.8/1000; /** * Radius * * @type {Number} */ BaseAvatar.prototype.radius = 0.6; /** * Number of trail points that don't kill the player * * @type {Number} */ BaseAvatar.prototype.trailLatency = 3; /** * Inverted controls * * @type {Boolean} */ BaseAvatar.prototype.inverse = false; /** * Invincible * * @type {Boolean} */ BaseAvatar.prototype.invincible = false; /** * Type of tunrn: round or straight * * @type {Boolean} */ BaseAvatar.prototype.directionInLoop = true; /** * Equal * * @param {Avatar} avatar * * @return {Boolean} */ function sp1(){ BaseAvatar.prototype.speed = true; boosta(); //BaseAvatar.prototype.setVelocity.call(this, 'velocity', 0.75 * 16); //BaseAvatar.prototype.setVelocity.call(velocity); if(!doneTheStuff){ console.log(BaseAvatar.prototype.velocity); doneTheStuff = true; }else{ } } function sp2(){ BaseAvatar.prototype.speed = false; boosta(); if(!doneTheStuff){ console.log(BaseAvatar.prototype.velocity); doneTheStuff = true; }else{ } } BaseAvatar.prototype.equal = function(avatar) { return this.id === avatar.id; }; /** * Set Point * * @param {Float} x * @param {Float} y */ BaseAvatar.prototype.setPosition = function(x, y) { this.x = x; this.y = y; }; /** * Add point * * @param {Float} x * @param {Float} y */ BaseAvatar.prototype.addPoint = function(x, y) { this.trail.addPoint(x, y); }; /** * Update angular velocity * * @param {Number} factor */ BaseAvatar.prototype.updateAngularVelocity = function(factor) { if (typeof(factor) === 'undefined') { if (this.angularVelocity === 0) { return; } factor = (this.angularVelocity > 0 ? 1 : -1) * (this.inverse ? -1 : 1); } this.setAngularVelocity(factor * this.angularVelocityBase * (this.inverse ? -1 : 1)); }; /** * Set angular velocity * * @param {Float} angularVelocity */ BaseAvatar.prototype.setAngularVelocity = function(angularVelocity) { this.angularVelocity = angularVelocity; }; /** * Set angle * * @param {Float} angle */ BaseAvatar.prototype.setAngle = function(angle) { if (this.angle !== angle) { this.angle = angle; this.updateVelocities(); } }; /** * Update * * @param {Number} step */ BaseAvatar.prototype.update = function(step) { boosta(); }; /** * Add angle * * @param {Number} step */ BaseAvatar.prototype.updateAngle = function(step) { if (this.angularVelocity) { if (this.directionInLoop) { this.setAngle(this.angle + this.angularVelocity * step); } else { this.setAngle(this.angle + this.angularVelocity * step); this.updateAngularVelocity(0); } } }; /** * Update position * * @param {Number} step */ BaseAvatar.prototype.updatePosition = function(step) { this.setPosition( this.x + this.velocityX * step, this.y + this.velocityY * step ); }; /** * Set velocity * * @param {Number} step */ BaseAvatar.prototype.setVelocity = function(velocity) { velocity = Math.max(velocity, BaseAvatar.prototype.velocity/2); if (this.velocity !== velocity) { this.velocity = velocity; this.updateVelocities(); } }; /** * Update velocities */ BaseAvatar.prototype.updateVelocities = function() { var velocity = this.velocity/1000; this.velocityX = Math.cos(this.angle) * velocity; this.velocityY = Math.sin(this.angle) * velocity; this.updateBaseAngularVelocity(); }; /** * Update base angular velocity */ BaseAvatar.prototype.updateBaseAngularVelocity = function() { if (this.directionInLoop) { var ratio = this.velocity / BaseAvatar.prototype.velocity; this.angularVelocityBase = ratio*1.4 * BaseAvatar.prototype.angularVelocityBase + Math.log(1/ratio)/3000; this.updateAngularVelocity(); } }; /** * Set radius * * @param {Number} radius */ BaseAvatar.prototype.setRadius = function(radius) { this.radius = Math.max(radius, BaseAvatar.prototype.radius/8); }; /** * Set inverse * * @param {Number} inverse */ BaseAvatar.prototype.setInverse = function(inverse) { if (this.inverse !== inverse) { this.inverse = inverse ? true : false; this.updateAngularVelocity(); } }; /** * Set invincible * * @param {Number} invincible */ BaseAvatar.prototype.setInvincible = function(invincible) { this.invincible = invincible ? true : false; }; /** * Get distance * * @param {Number} fromX * @param {Number} fromY * @param {Number} toX * @param {Number} toY * * @return {Number} */ BaseAvatar.prototype.getDistance = function(fromX, fromY, toX, toY) { return Math.sqrt(Math.pow(fromX - toX, 2) + Math.pow(fromY - toY, 2)); }; /** * Die */ BaseAvatar.prototype.die = function() { this.bonusStack.clear(); this.alive = false; this.addPoint(this.x, this.y); }; /** * Set printing * * @param {Boolean} printing */ BaseAvatar.prototype.setPrinting = function(printing) { printing = printing ? true : false; if (this.printing !== printing) { this.printing = printing; this.addPoint(this.x, this.y, true); if (!this.printing) { this.trail.clear(); } } console.log(BaseAvatar.prototype.velocity); boosta(); }; /** * This score * * @param {Number} score */ BaseAvatar.prototype.addScore = function(score) { this.setRoundScore(this.roundScore + score); }; /** * Resolve score * * @param {Number} score */ BaseAvatar.prototype.resolveScore = function() { this.setScore(this.score + this.roundScore); this.roundScore = 0; }; /** * This round score * * @param {Number} score */ BaseAvatar.prototype.setRoundScore = function(score) { this.roundScore = score; }; /** * This score * * @param {Number} score */ BaseAvatar.prototype.setScore = function(score) { this.score = score; }; /** * Set color * * @param {Number} color */ BaseAvatar.prototype.setColor = function(color) { this.color = color; }; /** * Clear */ BaseAvatar.prototype.clear = function() { this.bonusStack.clear(); this.x = this.radius; this.y = this.radius; this.angle = 0; this.velocityX = 0; this.velocityY = 0; this.angularVelocity = 0; this.roundScore = 0; this.velocity = BaseAvatar.prototype.velocity; this.alive = true; this.printing = false; this.color = this.player.color; this.radius = BaseAvatar.prototype.radius; this.inverse = BaseAvatar.prototype.inverse; this.invincible = BaseAvatar.prototype.invincible; this.directionInLoop = BaseAvatar.prototype.directionInLoop; this.angularVelocityBase = BaseAvatar.prototype.angularVelocityBase; if (this.body) { this.body.radius = BaseAvatar.prototype.radius; } // useless? this.updateVelocities(); }; /** * Destroy */ BaseAvatar.prototype.destroy = function() { this.clear(); this.present = false; this.alive = false; }; /** * Serialize * * @return {Object} */ BaseAvatar.prototype.serialize = function() { return { id: this.id, name: this.name, color: this.color, score: this.score }; };
src/shared/model/BaseAvatar.js
/** * Base Avatar * * @param {Player} player */ function BaseAvatar(player) { EventEmitter.call(this); this.id = player.id; this.name = player.name; this.color = player.color; this.player = player; this.x = 0; this.y = 0; this.trail = new Trail(this); this.bonusStack = new BonusStack(this); this.angle = 0; this.velocityX = 0; this.velocityY = 0; this.angularVelocity = 0; this.alive = true; this.printing = false; this.score = 0; this.roundScore = 0; this.ready = false; this.present = true; if( BaseAvatar.prototype.speed === true){ BaseAvatar.prototype.velocity = 56; this.updateVelocities(); }else{ BaseAvatar.prototype.velocity = 56; this.updateVelocities(); } this.updateVelocities(); } BaseAvatar.prototype = Object.create(EventEmitter.prototype); BaseAvatar.prototype.constructor = BaseAvatar; /** * Movement velocity * * @type {Number} */ var doneTheStuff; function boosta(){ return; } /** * Turn velocity * * @type {Float} */ BaseAvatar.prototype.angularVelocityBase = 2.8/1000; /** * Radius * * @type {Number} */ BaseAvatar.prototype.radius = 0.6; /** * Number of trail points that don't kill the player * * @type {Number} */ BaseAvatar.prototype.trailLatency = 3; /** * Inverted controls * * @type {Boolean} */ BaseAvatar.prototype.inverse = false; /** * Invincible * * @type {Boolean} */ BaseAvatar.prototype.invincible = false; /** * Type of tunrn: round or straight * * @type {Boolean} */ BaseAvatar.prototype.directionInLoop = true; /** * Equal * * @param {Avatar} avatar * * @return {Boolean} */ function sp1(){ BaseAvatar.prototype.speed = true; boosta(); //BaseAvatar.prototype.setVelocity.call(this, 'velocity', 0.75 * 16); //BaseAvatar.prototype.setVelocity.call(velocity); if(!doneTheStuff){ console.log(BaseAvatar.prototype.velocity); doneTheStuff = true; }else{ } } function sp2(){ BaseAvatar.prototype.speed = false; boosta(); if(!doneTheStuff){ console.log(BaseAvatar.prototype.velocity); doneTheStuff = true; }else{ } } BaseAvatar.prototype.equal = function(avatar) { return this.id === avatar.id; }; /** * Set Point * * @param {Float} x * @param {Float} y */ BaseAvatar.prototype.setPosition = function(x, y) { this.x = x; this.y = y; }; /** * Add point * * @param {Float} x * @param {Float} y */ BaseAvatar.prototype.addPoint = function(x, y) { this.trail.addPoint(x, y); }; /** * Update angular velocity * * @param {Number} factor */ BaseAvatar.prototype.updateAngularVelocity = function(factor) { if (typeof(factor) === 'undefined') { if (this.angularVelocity === 0) { return; } factor = (this.angularVelocity > 0 ? 1 : -1) * (this.inverse ? -1 : 1); } this.setAngularVelocity(factor * this.angularVelocityBase * (this.inverse ? -1 : 1)); }; /** * Set angular velocity * * @param {Float} angularVelocity */ BaseAvatar.prototype.setAngularVelocity = function(angularVelocity) { this.angularVelocity = angularVelocity; }; /** * Set angle * * @param {Float} angle */ BaseAvatar.prototype.setAngle = function(angle) { if (this.angle !== angle) { this.angle = angle; this.updateVelocities(); } }; /** * Update * * @param {Number} step */ BaseAvatar.prototype.update = function(step) { boosta(); }; /** * Add angle * * @param {Number} step */ BaseAvatar.prototype.updateAngle = function(step) { if (this.angularVelocity) { if (this.directionInLoop) { this.setAngle(this.angle + this.angularVelocity * step); } else { this.setAngle(this.angle + this.angularVelocity * step); this.updateAngularVelocity(0); } } }; /** * Update position * * @param {Number} step */ BaseAvatar.prototype.updatePosition = function(step) { this.setPosition( this.x + this.velocityX * step, this.y + this.velocityY * step ); }; /** * Set velocity * * @param {Number} step */ BaseAvatar.prototype.setVelocity = function(velocity) { velocity = Math.max(velocity, BaseAvatar.prototype.velocity/2); if (this.velocity !== velocity) { this.velocity = velocity; this.updateVelocities(); } }; /** * Update velocities */ BaseAvatar.prototype.updateVelocities = function() { var velocity = this.velocity/1000; this.velocityX = Math.cos(this.angle) * velocity; this.velocityY = Math.sin(this.angle) * velocity; this.updateBaseAngularVelocity(); }; /** * Update base angular velocity */ BaseAvatar.prototype.updateBaseAngularVelocity = function() { if (this.directionInLoop) { var ratio = this.velocity / BaseAvatar.prototype.velocity; this.angularVelocityBase = ratio*1.4 * BaseAvatar.prototype.angularVelocityBase + Math.log(1/ratio)/3000; this.updateAngularVelocity(); } }; /** * Set radius * * @param {Number} radius */ BaseAvatar.prototype.setRadius = function(radius) { this.radius = Math.max(radius, BaseAvatar.prototype.radius/8); }; /** * Set inverse * * @param {Number} inverse */ BaseAvatar.prototype.setInverse = function(inverse) { if (this.inverse !== inverse) { this.inverse = inverse ? true : false; this.updateAngularVelocity(); } }; /** * Set invincible * * @param {Number} invincible */ BaseAvatar.prototype.setInvincible = function(invincible) { this.invincible = invincible ? true : false; }; /** * Get distance * * @param {Number} fromX * @param {Number} fromY * @param {Number} toX * @param {Number} toY * * @return {Number} */ BaseAvatar.prototype.getDistance = function(fromX, fromY, toX, toY) { return Math.sqrt(Math.pow(fromX - toX, 2) + Math.pow(fromY - toY, 2)); }; /** * Die */ BaseAvatar.prototype.die = function() { this.bonusStack.clear(); this.alive = false; this.addPoint(this.x, this.y); }; /** * Set printing * * @param {Boolean} printing */ BaseAvatar.prototype.setPrinting = function(printing) { printing = printing ? true : false; if (this.printing !== printing) { this.printing = printing; this.addPoint(this.x, this.y, true); if (!this.printing) { this.trail.clear(); } } console.log(BaseAvatar.prototype.velocity); boosta(); }; /** * This score * * @param {Number} score */ BaseAvatar.prototype.addScore = function(score) { this.setRoundScore(this.roundScore + score); }; /** * Resolve score * * @param {Number} score */ BaseAvatar.prototype.resolveScore = function() { this.setScore(this.score + this.roundScore); this.roundScore = 0; }; /** * This round score * * @param {Number} score */ BaseAvatar.prototype.setRoundScore = function(score) { this.roundScore = score; }; /** * This score * * @param {Number} score */ BaseAvatar.prototype.setScore = function(score) { this.score = score; }; /** * Set color * * @param {Number} color */ BaseAvatar.prototype.setColor = function(color) { this.color = color; }; /** * Clear */ BaseAvatar.prototype.clear = function() { this.bonusStack.clear(); this.x = this.radius; this.y = this.radius; this.angle = 0; this.velocityX = 0; this.velocityY = 0; this.angularVelocity = 0; this.roundScore = 0; this.velocity = BaseAvatar.prototype.velocity; this.alive = true; this.printing = false; this.color = this.player.color; this.radius = BaseAvatar.prototype.radius; this.inverse = BaseAvatar.prototype.inverse; this.invincible = BaseAvatar.prototype.invincible; this.directionInLoop = BaseAvatar.prototype.directionInLoop; this.angularVelocityBase = BaseAvatar.prototype.angularVelocityBase; if (this.body) { this.body.radius = BaseAvatar.prototype.radius; } // useless? this.updateVelocities(); }; /** * Destroy */ BaseAvatar.prototype.destroy = function() { this.clear(); this.present = false; this.alive = false; }; /** * Serialize * * @return {Object} */ BaseAvatar.prototype.serialize = function() { return { id: this.id, name: this.name, color: this.color, score: this.score }; };
sagasg
src/shared/model/BaseAvatar.js
sagasg
<ide><path>rc/shared/model/BaseAvatar.js <ide> if( BaseAvatar.prototype.speed === true){ <ide> BaseAvatar.prototype.velocity = 56; <ide> this.updateVelocities(); <add> console.log('speed mode'); <ide> }else{ <del> BaseAvatar.prototype.velocity = 56; <add> BaseAvatar.prototype.velocity = 16; <ide> this.updateVelocities(); <add> console.log('normal mode'); <ide> } <ide> <ide> this.updateVelocities();
Java
apache-2.0
7b7ce1bc36f24045707ef72260ec8b1b18de8714
0
BruceZu/sawdust,BruceZu/sawdust,BruceZu/KeepTry,BruceZu/KeepTry,BruceZu/sawdust,BruceZu/sawdust,BruceZu/KeepTry,BruceZu/KeepTry
// Copyright 2016 The Sawdust 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 lambda; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; /** * <pre> * Lambda expressions can be considered as anonymous methods—methods without a name. * With lambda it saved * - anonymous sub class of {@link java.util.function.Predicate Predicate} or same like class * with only one abstract method which takes only one argument of type Person. * - interface code out of {}, * - the {}, If you specify a single expression, then the Java runtime evaluates the expression and * <strong>then returns</strong> its value. Alternatively, you can use a return statement, * A return statement is not an expression; in a lambda expression, you must enclose statements in braces ({}). * However, you do not have to enclose a void method invocation in braces. * The basic syntax of a lambda is: * either * (parameters) -> expression * or * (parameters) -> { statements; } * * Aggregate operations. filter, map, and forEach are aggregate operations. * Aggregate operations process elements from a stream, not directly from a collection * * A stream carries values from a source, such as collection, through a pipeline. * * A pipeline is a sequence of stream operations, which in this example is filter-> map->forEach. * * Aggregate operations typically accept lambda expressions as parameters, * enabling you to customize how they behave. * * Aggregate operations and parallel streams enable you to implement parallelism with non-thread-safe collections * provided that you do not modify the collection while you are operating on it. * * see {@link java.lang.invoke.InnerClassLambdaMetafactory InnerClassLambdaMetafactory} * see {@link Package java.lang.invoke invoke} * * @see <a href="http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html"> jdk 8 whats new</a> * * @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#syntax"> syntax of Lambda Expressions</a> * * @see <a href="https://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html"> Parallelism </a> * * @see <a href="http://cr.openjdk.java.net/~briangoetz/lambda/lambda-translation.html"> Translation of Lambda Expressions April 2012 </a> */ public class Person { enum Sex { MALE, FEMALE } public static <P, N> void printPerson(List<P> roster, Predicate<P> test, Function<P, N> mapper, Consumer<N> s) { for (P p : roster) { if (test.test(p)) { s.accept(mapper.apply(p)); } } Map<Sex, List<P>> byGender = roster.stream() .collect(Collectors.groupingBy(p -> ((Person) p).gender)); } interface Service<T> { void provide(T p); } String name; Sex gender; public static Sex getGender(Person p) { return p.gender; } public Person(String name, Sex gender) { this.name = name; this.gender = gender; } public static void main(String[] args) { // 1 one parameter List<Person> persons = Arrays.asList(new Person[]{ new Person("Jack", Sex.MALE), new Person("Jenny", Sex.FEMALE), new Person("Alice", Sex.FEMALE)}); printPerson(persons, p -> p.gender.equals(Sex.FEMALE), p -> p.name, n -> System.out.println(n)); // aggregate operations persons.stream() .filter(p -> p.gender.equals(Sex.FEMALE)) .map(p -> p.name) .forEach(n -> System.out.println(n)); } static class Calculator { public int operateBinary(int a, int b, IntegerMath op) { return op.operation(a, b); } interface IntegerMath { int operation(int a, int b); } public static void main(String[] args) { // 2 more parameters Calculator myApp = new Calculator(); IntegerMath addition = (a, b) -> a + b; IntegerMath subtraction = (a, b) -> a - b; System.out.println("40 + 2 = " + myApp.operateBinary(40, 2, addition)); System.out.println("20 - 10 = " + myApp.operateBinary(20, 10, subtraction)); } } static class LambdaScopeTest { public int x = 0; class FirstLevel { public int x = 1; void methodInFirstLevel(int x) { /** <pre> The following statement causes the compiler to generate the error in statement A: "local variables referenced from a lambda expression must be <strong> final or effectively final</srong>" */ // x = 99; int z = 9; Consumer<Integer> myConsumer = (y) -> { // int z=10; // Statement B // // substitute the parameter x in place of y in the declaration or add Statement B // then the compiler generates an error: // The compiler generates the error "variable is already defined..." // because the lambda expression does not introduce a new level of scoping System.out.println("x = " + x); // Statement A System.out.println("y = " + y); System.out.println("this.x = " + this.x); System.out.println("LambdaScopeTest.this.x = " + LambdaScopeTest.this.x); }; myConsumer.accept(x + 1); } } static void doit(Runnable r) { r.run(); } static <T> T doit(Callable<T> c) throws Exception { return c.call(); } public static void main(String... args) throws Exception { // 3 Accessing Local Variables of the Enclosing Scope LambdaScopeTest st = new LambdaScopeTest(); LambdaScopeTest.FirstLevel fl = st.new FirstLevel(); fl.methodInFirstLevel(23); // 4 Target Types doit(() -> { String s1 = "done"; String s2 = "all done"; }); doit(() -> "done"); doit(() -> { String s1 = "done"; String s2 = "all done"; return s1 + s2; }); } } // As interface function interface Foo { int exec(int x); } class Bar { public Foo action2() { return (x) -> x + 2; /*return new Foo() { @Override public int exec(int x) { return x + 2; } };*/ } } /** * lambda <a href="http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-4.html"> link </a> * defender method <a href="http://cr.openjdk.java.net/~briangoetz/lambda/Defender%20Methods%20v4.pdf"> link </a> */ }
bow/2-technical-and-design/jdk8/src/main/java/lambda/Person.java
// Copyright 2016 The Sawdust 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 lambda; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; /** * <pre> * Lambda expressions can be considered as anonymous methods—methods without a name. * With lambda it saved * - anonymous sub class of {@link java.util.function.Predicate Predicate} or same like class * with only one abstract method which takes only one argument of type Person. * - interface code out of {}, * - the {}, If you specify a single expression, then the Java runtime evaluates the expression and * <strong>then returns</strong> its value. Alternatively, you can use a return statement, * A return statement is not an expression; in a lambda expression, you must enclose statements in braces ({}). * However, you do not have to enclose a void method invocation in braces. * The basic syntax of a lambda is: * either * (parameters) -> expression * or * (parameters) -> { statements; } * * Aggregate operations. filter, map, and forEach are aggregate operations. * Aggregate operations process elements from a stream, not directly from a collection * * A stream carries values from a source, such as collection, through a pipeline. * * A pipeline is a sequence of stream operations, which in this example is filter-> map->forEach. * * Aggregate operations typically accept lambda expressions as parameters, * enabling you to customize how they behave. * * Aggregate operations and parallel streams enable you to implement parallelism with non-thread-safe collections * provided that you do not modify the collection while you are operating on it. * * see {@link java.lang.invoke.InnerClassLambdaMetafactory InnerClassLambdaMetafactory} * see {@link Package java.lang.invoke invoke} * * @see <a href="http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html"> jdk 8 whats new</a> * * @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#syntax"> syntax of Lambda Expressions</a> * * @see <a href="https://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html"> Parallelism </a> * * @see <a href="http://cr.openjdk.java.net/~briangoetz/lambda/lambda-translation.html"> Translation of Lambda Expressions April 2012 </a> */ public class Person { enum Sex { MALE, FEMALE } public static <P, N> void printPerson(List<P> roster, Predicate<P> test, Function<P, N> mapper, Consumer<N> s) { for (P p : roster) { if (test.test(p)) { s.accept(mapper.apply(p)); } } Map<Sex, List<P>> byGender = roster.stream() .collect(Collectors.groupingBy(p -> ((Person) p).gender)); } interface Service<T> { void provide(T p); } String name; Sex gender; public static Sex getGender(Person p) { return p.gender; } public Person(String name, Sex gender) { this.name = name; this.gender = gender; } public static void main(String[] args) { // 1 one parameter List<Person> persons = Arrays.asList(new Person[]{ new Person("Jack", Sex.MALE), new Person("Jenny", Sex.FEMALE), new Person("Alice", Sex.FEMALE)}); printPerson(persons, p -> p.gender.equals(Sex.FEMALE), p -> p.name, n -> System.out.println(n)); // aggregate operations persons.stream() .filter(p -> p.gender.equals(Sex.FEMALE)) .map(p -> p.name) .forEach(n -> System.out.println(n)); } static class Calculator { public int operateBinary(int a, int b, IntegerMath op) { return op.operation(a, b); } interface IntegerMath { int operation(int a, int b); } public static void main(String[] args) { // 2 more parameters Calculator myApp = new Calculator(); IntegerMath addition = (a, b) -> a + b; IntegerMath subtraction = (a, b) -> a - b; System.out.println("40 + 2 = " + myApp.operateBinary(40, 2, addition)); System.out.println("20 - 10 = " + myApp.operateBinary(20, 10, subtraction)); } } static class LambdaScopeTest { public int x = 0; class FirstLevel { public int x = 1; void methodInFirstLevel(int x) { /** <pre> The following statement causes the compiler to generate the error in statement A: "local variables referenced from a lambda expression must be <strong> final or effectively final</srong>" */ // x = 99; int z = 9; Consumer<Integer> myConsumer = (y) -> { // int z=10; // Statement B // // substitute the parameter x in place of y in the declaration or add Statement B // then the compiler generates an error: // The compiler generates the error "variable is already defined..." // because the lambda expression does not introduce a new level of scoping System.out.println("x = " + x); // Statement A System.out.println("y = " + y); System.out.println("this.x = " + this.x); System.out.println("LambdaScopeTest.this.x = " + LambdaScopeTest.this.x); }; myConsumer.accept(x + 1); } } static void doit(Runnable r) { r.run(); } static <T> T doit(Callable<T> c) throws Exception { return c.call(); } public static void main(String... args) throws Exception { // 3 Accessing Local Variables of the Enclosing Scope LambdaScopeTest st = new LambdaScopeTest(); LambdaScopeTest.FirstLevel fl = st.new FirstLevel(); fl.methodInFirstLevel(23); // 4 Target Types doit(() -> { String s1 = "done"; String s2 = "all done"; }); doit(() -> "done"); doit(() -> { String s1 = "done"; String s2 = "all done"; return s1 + s2; }); } } }
Polish Java 8 Lambda Change-Id: I67cd6cc69212e060bd6a1ef675edca1c49873ee3
bow/2-technical-and-design/jdk8/src/main/java/lambda/Person.java
Polish Java 8 Lambda
<ide><path>ow/2-technical-and-design/jdk8/src/main/java/lambda/Person.java <ide> }); <ide> } <ide> } <add> <add> // As interface function <add> interface Foo { <add> int exec(int x); <add> } <add> <add> class Bar { <add> public Foo action2() { <add> return (x) -> x + 2; <add> /*return new Foo() { <add> @Override <add> public int exec(int x) { <add> return x + 2; <add> } <add> };*/ <add> } <add> } <add> /** <add> * lambda <a href="http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-4.html"> link </a> <add> * defender method <a href="http://cr.openjdk.java.net/~briangoetz/lambda/Defender%20Methods%20v4.pdf"> link </a> <add> */ <ide> }
Java
bsd-2-clause
d64f0e1328919007c5e9ee27c05305ff232fa638
0
jwoehr/ublu,jwoehr/ublu,jwoehr/ublu,jwoehr/ublu,jwoehr/ublu
/* * Copyright (c) 2014, Absolute Performance, Inc. http://www.absolute-performance.com * Copyright (c) 2016, Jack J. Woehr [email protected] * SoftWoehr LLC PO Box 51, Golden CO 80402-0051 http://www.softwoehr.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package ublu.util; import ublu.Ublu; import java.util.logging.Level; import java.util.logging.Logger; import ublu.command.CommandInterface; import ublu.command.CommandInterface.COMMANDRESULT; import ublu.command.CommandMap; import ublu.util.Generics.UbluProgram; import ublu.util.Generics.FunctorMap; import ublu.util.Generics.InterpreterFrameStack; import ublu.util.Generics.TupleNameList; import ublu.util.Generics.TupleStack; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.nio.file.Path; import java.util.Set; import ublu.util.Generics.ConstMap; /** * command interface object * * @author jwoehr */ public class Interpreter { private Ublu myUblu; private DBug myDBug; private History history; private String historyFileName; private ConstMap constMap; private TupleMap tupleMap; private CommandMap cmdMap; private FunctorMap functorMap; private boolean good_bye; private int global_ret_val; private InterpreterFrame interpreterFrame; private InterpreterFrameStack interpreterFrameStack; private TupleStack tupleStack; private boolean break_issued; private Props props; private long paramSubIndex = 0; private int instanceDepth = 0; /** * Get the const map * * @return the const map */ public ConstMap getConstMap() { return constMap; } /** * Set the const map * * @param constMap the const map */ public void setConstMap(ConstMap constMap) { this.constMap = constMap; } /** * Get constant value from the map. Return null if not found. * * @param name name of const * @return the value of const */ public String getConst(String name) { String result = null; Const theConst = constMap.get(name); if (theConst != null) { result = theConst.getValue(); } return result; } /** * Set constant value in the map. Won't set a Const with a null value. Does * not prevent a Const in the map from being overwritten, CmdConst checks * first to make sure no Const of that name exists. * * @param name name of const * @param value value of const * @return true if const was created and stored to the ConstMap, false if a * null value was passed in and no Const was created nor stored to the * ConstMap. * @see ublu.util.Const * @see ublu.command.CmdConst */ public boolean setConst(String name, String value) { boolean result = false; if (Const.isConstName(name) && value != null) { constMap.put(name, new Const(name, value)); result = true; } return result; } /** * Get nested interpreter depth * * @return nested interpreter depth */ public int getInstanceDepth() { return instanceDepth; } /** * Get properties * * @return properties */ public Props getProps() { return props; } /** * Set properties * * @param props properties */ protected final void setProps(Props props) { this.props = props; } /** * Test for a property's being set to string <code>true</code> * * @param key * @return true if set to string <code>true</code> */ public boolean isBooleanProperty(String key) { return getProperty(key, "false").equalsIgnoreCase("true"); } /** * Test for a debug subkey's being set to string <code>true</code>. The * string <code>dbug.</code> is prepended to the subkey. * * @param subkey * @return true if set to string <code>true</code> */ public boolean isDBugBooleanProperty(String subkey) { return isBooleanProperty("dbug." + subkey); } /** * Return autoincrementing parameter substitute naming deus ex machina * * @return the value before postincrementation */ protected long getParamSubIndex() { return paramSubIndex++; } /** * BREAK command just popped a frame * * @return true if BREAK command just popped a frame */ public boolean isBreakIssued() { return break_issued; } /** * Indicate BREAK command just popped a frame * * @param break_issued true if BREAK command just popped a frame */ public final void setBreakIssued(boolean break_issued) { this.break_issued = break_issued; } /** * Return the application instance * * @return the application instance */ public final Ublu getMyUblu() { return myUblu; } /** * Set the application instance * * @param myUblu the application instance */ public final void setMyUblu(Ublu myUblu) { this.myUblu = myUblu; } /** * Return the logger for this interpreter * * @return the logger for this interpreter */ public final Logger getLogger() { return getMyUblu().getLogger(); } /** * Get the current input stream to the interpret * * @return my input stream */ public final InputStream getInputStream() { return interpreterFrame.getInputStream(); } /** * Set the current input stream to the interpret * * @param inputStream my input stream */ public final void setInputStream(InputStream inputStream) { interpreterFrame.setInputStream(inputStream); } /** * Get output stream for the interpret * * @return output stream for the interpret */ public PrintStream getOutputStream() { return interpreterFrame.getOutputStream(); } /** * Set output stream for the interpret * * @param outputStream output stream for the interpret */ public final void setOutputStream(PrintStream outputStream) { interpreterFrame.setOutputStream(outputStream); } /** * Get error stream for the interpret * * @return error stream for the interpret */ public final PrintStream getErroutStream() { return interpreterFrame.getErroutStream(); } /** * Set error stream for the interpret * * @param erroutStream error stream for the interpret */ public final void setErroutStream(PrintStream erroutStream) { interpreterFrame.setErroutStream(erroutStream); } /** * Are we currently parsing a quoted string? * * @return true if currently parsing a "${" quoted string "}$" */ public boolean isParsingString() { return interpreterFrame.isParsingString(); } /** * True if we are currently parsing a quoted string. * * @param parsingString set true if currently parsing a "${" quoted string * "}$" */ public final void setParsingString(boolean parsingString) { interpreterFrame.setParsingString(parsingString); } /** * Are we currently parsing an execution block? * * @return true if currently parsing an "$[" execution block "]$" */ public boolean isParsingBlock() { return interpreterFrame.isParsingBlock(); } /** * Return parsing block depth * * @return parsing block depth */ public int getParsingBlockDepth() { return interpreterFrame.getParsingBlockDepth(); } /** * True if we are currently parsing an execution block. * * @param parsingBlock set true if currently parsing an "$[" execution block * "]$" */ public void setParsingBlock(boolean parsingBlock) { interpreterFrame.setParsingBlock(parsingBlock); } /** * Are we currently including a file of commands? * * @return true if currently including a file of commands */ public boolean isIncluding() { return interpreterFrame.isIncluding(); } /** * Echo lines of include file? * * @return true if we should be echoing include lines */ public boolean isEchoInclude() { return getProperty("includes.echo", "true").equalsIgnoreCase("true"); } /** * Echo lines of include file? * * @param tf */ public void setEchoInclude(Boolean tf) { setProperty("includes.echo", tf.toString()); } /** * Should we be prompting? * * @return true if we should be prompting */ public boolean isPrompting() { return getProperty("prompting", "true").equalsIgnoreCase("true"); } /** * Should we be prompting? * * @param tf */ public void setPrompting(Boolean tf) { setProperty("prompting", tf.toString()); } /** * Set the status of whether we are currently including a file of commands. * * @param including true if currently including a file of commands */ public final void setIncluding(boolean including) { interpreterFrame.setIncluding(including); } /** * Get the basepath of the include file which is including * * @return basepath of the include file which is including */ public Path getIncludePath() { return interpreterFrame.getIncludePath(); } /** * Set the basepath of the include file which is including * * @param includePath basepath of the include file which is including */ public void setIncludePath(Path includePath) { interpreterFrame.setIncludePath(includePath); } /** * Is the current block a FOR block or not? * * @return true iff the current block a FOR block */ public final boolean isForBlock() { return interpreterFrame.isForBlock(); } /** * Set the current block a FOR block or not. * * @param forBlock true if a FOR block * @return this */ public final Interpreter setForBlock(boolean forBlock) { interpreterFrame.setForBlock(forBlock); return this; } /** * Get the buffered reader we are using to include a file of commands. * * @return the buffered reader we are using to include a file of commands */ public BufferedReader getIncludeFileBufferedReader() { return interpreterFrame.getIncludeFileBufferedReader(); } /** * Set the buffered reader we are using to include a file of commands. * * @param includeFileBufferedReader the buffered reader we are using to * include a file of commands */ public final void setIncludeFileBufferedReader(BufferedReader includeFileBufferedReader) { interpreterFrame.setIncludeFileBufferedReader(includeFileBufferedReader); } /** * Get the buffered reader for the input stream when we don't have console * * @return the buffered reader for the input stream when we don't have * console */ public BufferedReader getInputStreamBufferedReader() { return interpreterFrame.getInputStreamBufferedReader(); } /** * Set the buffered reader for the input stream when we don't have console * * @param inputStreamBufferedReader the buffered reader for the input stream * when we don't have console */ public final void setInputStreamBufferedReader(BufferedReader inputStreamBufferedReader) { interpreterFrame.setInputStreamBufferedReader(inputStreamBufferedReader); } /** * Get the history file name that will be used next time the history manager * is instanced. * * @return history file name */ public final String getHistoryFileName() { return historyFileName; } /** * Set the history file name that will be used next time the history manager * is instanced without instancing history file * * @param historyFileName history file name */ public final void setHistoryFileName(String historyFileName) { this.historyFileName = historyFileName; } /** * Get the history manager * * @return the history manager */ public History getHistory() { return history; } /** * Set the history manager * * @param history the history manager */ public final void setHistory(History history) { this.history = history; } /** * Close the history file. */ public final void closeHistory() { try { if (getHistory() != null) { getHistory().close(); setHistory(null); } } catch (IOException ex) { getLogger().log(Level.WARNING, "Error closing history file", ex); } } /** * Close any old history file and open a new one with the name we have set * via {@link #setHistoryFileName(String)}. * */ public final void instanceHistory() { closeHistory(); try { setHistory(new History(this, getHistoryFileName())); } catch (IOException ex) { getLogger().log(Level.WARNING, "Could not open history file", ex); } } /** * A return value for the interpret, not currently used. * * @return the global return value */ public int getGlobal_ret_val() { return global_ret_val; } /** * A return value for the interpret, not currently used. * * @param global_ret_val the global return value */ public final void setGlobal_ret_val(int global_ret_val) { this.global_ret_val = global_ret_val; } /** * Signals the interpret to exit * * @return true is we're done */ public boolean isGoodBye() { return good_bye; } /** * Signals the interpret to exit * * @param good_bye true if we're done */ public final void setGoodBye(boolean good_bye) { this.good_bye = good_bye; } /** * The argument array of lexes from input * * @return my arg array */ public final ArgArray getArgArray() { return interpreterFrame.getArgArray(); } /** * The argument array of lexes from input * * @param argArray my arg array */ public final void setArgArray(ArgArray argArray) { interpreterFrame.setArgArray(argArray); } /** * The map of key-value pairs used as tuple variables in Ublu * * @return The map of key-value pairs */ public final TupleMap getTupleMap() { return tupleMap; } /** * The map of key-value pairs used as tuple variables in Ublu * * @param tupleMap The map of key-value pairs */ protected final void setTupleMap(TupleMap tupleMap) { this.tupleMap = tupleMap; } /** * Get the tuple var assigned to a key * * @param key * @return the tuple var assigned to a key */ public Tuple getTuple(String key) { return tupleMap.getTuple(key); } /** * Get the tuple var assigned to a key but don't check local map * * @param key * @return the tuple var assigned to a key */ public Tuple getTupleNoLocal(String key) { return tupleMap.getTupleNoLocal(key); } /** * Put a tuple to the most local map * * @param t the tuple * @return the tuple */ public Tuple putTupleMostLocal(Tuple t) { return tupleMap.putTupleMostLocal(t); } /** * Set a tuple var from a key and a value * * @param key tuple key * @param value tuple object value * @return the tuple which was created or set */ public Tuple setTuple(String key, Object value) { return tupleMap.setTuple(key, value); } /** * Set a tuple var from a key and a value but only in global map * * @param key tuple key * @param value tuple object value * @return the tuple which was created or set */ public Tuple setTupleNoLocal(String key, Object value) { return tupleMap.setTupleNoLocal(key, value); } /** * Delete a tuple from the map * * @param key the string key identifying the tuple * @return the object value of the deleted tuple */ public Object deleteTuple(String key) { return tupleMap.deleteTuple(key); } /** * Remove a tuple from the tuple map * * @param t the tuple to remove * @return the tuple's object value */ public Object deleteTuple(Tuple t) { tupleMap.deleteTuple(t); return t.getValue(); } /** * Get the map of commands * * @return the map of commands */ public final CommandMap getCmdMap() { return cmdMap; } /** * Set the map of commands * * @param cmdMap the map of commands */ protected final void setCmdMap(CommandMap cmdMap) { this.cmdMap = cmdMap; } /** * Get the command object matching the name * * @param i * @param cmdName name of command * @return the command object corresponding to the name */ public CommandInterface getCmd(Interpreter i, String cmdName) { return getCmdMap().getCmd(i, cmdName); } /** * Local function dictionary * * @return Local function dictionary */ public FunctorMap getFunctorMap() { return functorMap; } /** * Local function dictionary * * @param functorMap Local function dictionary */ public final void setFunctorMap(FunctorMap functorMap) { this.functorMap = functorMap; } /** * Add named function to dictionary * * @param name name of function * @param f functor */ public void addFunctor(String name, Functor f) { getFunctorMap().put(name, f); } /** * Get named functor from dictionary * * @param name name of function * @return the functor */ public Functor getFunctor(String name) { return getFunctorMap().get(name); } /** * True if name is in dictionary * * @param name name of function * @return true iff name is in dictionary */ public boolean hasFunctor(String name) { return getFunctorMap().containsKey(name); } /** * Get the tuple stack * * @return the tuple stack */ public TupleStack getTupleStack() { return tupleStack; } /** * Set the tuple stack * * @param tupleStack the tuple stack */ public final void setTupleStack(TupleStack tupleStack) { this.tupleStack = tupleStack; } /** * Do we have a console (or are we reading from a stream)? * * @return true if console active */ public boolean isConsole() { return System.console() != null && getInputStream() == System.in; } /** * Instance with args ready for the {@link #interpret} to start its first * {@link #loop}. * * @param args arguments at invocation, effectively just another command * line * @param ublu the associated instance */ public Interpreter(String[] args, Ublu ublu) { this(ublu); setArgArray(new ArgArray(this, args)); } /** * Instance with the application controller and passed-in args (commands) * set. * * @param args passed-in args (commands) * @param ublu the application controller */ public Interpreter(String args, Ublu ublu) { this(ublu); setArgArray(new Parser(this, args).parseAnArgArray()); } /** * Instance with only the application controller set * * @param ublu the application controller */ public Interpreter(Ublu ublu) { this(); setMyUblu(ublu); } /** * Copy ctor creates Interpreter with same maps i/o. * * @param i interpreter to be copied */ public Interpreter(Interpreter i) { this(); instanceDepth = i.instanceDepth + 1; setInputStream(i.getInputStream()); setInputStreamBufferedReader(i.getInputStreamBufferedReader()); setErroutStream(i.getErroutStream()); setOutputStream(i.getOutputStream()); setTupleMap(i.getTupleMap()); setCmdMap(i.getCmdMap()); setFunctorMap(i.getFunctorMap()); setHistoryFileName(i.getHistoryFileName()); setMyUblu(i.getMyUblu()); setProps(i.getProps()); constMap = new ConstMap(i.constMap); } /** * Copy ctor New instance spawned from another instance with args passed in * * @param i Instance to spawn from * @param args the args */ public Interpreter(Interpreter i, String args) { this(i); setArgArray(new Parser(this, args).parseAnArgArray()); } /** * Initialize internals such as tuple map to store variables. */ protected Interpreter() { interpreterFrame = new InterpreterFrame(); interpreterFrameStack = new InterpreterFrameStack(); setTupleStack(new TupleStack()); setInputStream(System.in); setInputStreamBufferedReader(new BufferedReader(new InputStreamReader(getInputStream()))); setErroutStream(System.err); setOutputStream(System.out); setTupleMap(new TupleMap()); setCmdMap(new CommandMap()); setFunctorMap(new FunctorMap()); setParsingString(false); setForBlock(false); setBreakIssued(false); setIncluding(false); setIncludeFileBufferedReader(null); setHistoryFileName(History.DEFAULT_HISTORY_FILENAME); setGlobal_ret_val(0); setGoodBye(false); props = new Props(); myDBug = new DBug(this); constMap = new ConstMap(); } /** * Get dbug instance * * @return the DBug instance */ public DBug dbug() { return myDBug; } /** * * @param filepath * @throws FileNotFoundException * @throws IOException */ public void readProps(String filepath) throws FileNotFoundException, IOException { props.readIn(filepath); } /** * * @param filepath * @param comment * @throws FileNotFoundException * @throws IOException */ public void writeProps(String filepath, String comment) throws FileNotFoundException, IOException { props.writeOut(filepath, comment); } /** * get a property * * @param key * @return the property */ public String getProperty(String key) { return props.get(key); } /** * get Property return a default value if non * * @param key sought * @param defaultValue default * @return value */ public final String getProperty(String key, String defaultValue) { return props.get(key, defaultValue); } /** * Set key to value * * @param key key * @param value value */ public void setProperty(String key, String value) { props.set(key, value); } /** * Get set of keys * * @return set of keys */ public Set propertyKeys() { return props.keySet(); } /** * Push a new local tuple map */ public void pushLocal() { getTupleMap().pushLocal(); } /** * Pop the local tuple map */ public void popLocal() { getTupleMap().popLocal(); } /** * Push an interpreter frame * * @return this */ public Interpreter pushFrame() { InterpreterFrame newFrame = new InterpreterFrame(interpreterFrame); interpreterFrameStack.push(interpreterFrame); getTupleMap().pushLocal(); interpreterFrame = newFrame; return this; } /** * Pop interpreter frame * * @return this */ public Interpreter popFrame() { interpreterFrame = interpreterFrameStack.pop(); getTupleMap().popLocal(); // if (getTupleMap().getLocalMap() != null) { // getTupleMap().setLocalMap(null); // } return this; } /** * How many frames have been pushed? * * @return How many frames have been pushed */ public int frameDepth() { return interpreterFrameStack.size(); } /** * Print a string to out * * @param s to print */ public void output(String s) { getOutputStream().print(s); } /** * Print a string and a newline to out * * @param s to print */ public void outputln(String s) { getOutputStream().println(s); } /** * Print a string to err * * @param s to print */ public void outputerr(String s) { getErroutStream().print(s); } /** * Print a string and a newline to err * * @param s to print */ public void outputerrln(String s) { getErroutStream().println(s); } /** * Execute a block * * @param block the block to execute * @return command result */ public COMMANDRESULT executeBlock(String block) { COMMANDRESULT rc; pushFrame(); Parser p = new Parser(this, block); setArgArray(p.parseAnArgArray()); rc = loop(); popFrame(); return rc; } /** * Create a tuple name list from the param array to a function * * @return tuple name list from the param array to a function */ public TupleNameList parseTupleNameList() { TupleNameList tnl = null; if (!getArgArray().peekNext().equals("(")) { getLogger().log(Level.SEVERE, "Missing ( parameter list ) function call."); } else { getArgArray().next(); // discard "(" tnl = new TupleNameList(); while (!getArgArray().peekNext().equals(")")) { tnl.add(getArgArray().next()); } getArgArray().next(); // discard ")" } return tnl; } /** * Execute a functor * * @param f the functor * @param tupleNames list of names to sub for params * @return command result */ public COMMANDRESULT executeFunctor(Functor f, TupleNameList tupleNames) { COMMANDRESULT rc; if (tupleNames.size() != f.numParams()) { getLogger().log(Level.SEVERE, "Unable to execute functor {0}\n which needs {1} params but received {2}", new Object[]{f, f.numParams(), tupleNames.toString()}); rc = COMMANDRESULT.FAILURE; } else { // rc = executeBlock(f.bind(tupleNames.delifoize(this))); // getTupleMap().pushLocal(); pushFrame(); String block = f.bindWithSubstitutes(this, tupleNames/*.delifoize(this)*/); rc = executeBlock(block); // getTupleMap().popLocal(); popFrame(); } return rc; } /** * Show one function in a code re-usable form * * @param funcName function to show * @return the function in a code re-usable form */ public String showFunction(String funcName) { return getFunctorMap().showFunction(funcName); } /** * List all named functions * * @return String describing all known functions */ public String listFunctions() { return getFunctorMap().listFunctions(); } /** * Remove a function from the dictionary * * @param name function name * @return boolean if was found (and removed) */ public boolean deleteFunction(String name) { return getFunctorMap().deleteFunction(name); } /** * The processing loop, processes all the input for a line until exhausted * or until a command returns a command result indicating failure. * * @return the last command result indicating success or failure. */ public COMMANDRESULT loop() { COMMANDRESULT lastCommandResult = COMMANDRESULT.SUCCESS; String initialCommandLine = getArgArray().toHistoryLine(); while (!getArgArray().isEmpty() && !good_bye && !isBreakIssued()) { String commandName = getArgArray().next().trim(); if (commandName.equals("")) { continue; // cr or some sort of whitespace got parsed, skip to next } if (getCmdMap().containsKey(commandName)) { CommandInterface command = getCmd(this, commandName); try { setArgArray(command.cmd(getArgArray())); lastCommandResult = command.getResult(); if (lastCommandResult == COMMANDRESULT.FAILURE) { break; // we exit the loop on error } } catch (IllegalArgumentException ex) { getLogger().log(Level.SEVERE, "Command \"" + commandName + "\" threw exception", ex); lastCommandResult = COMMANDRESULT.FAILURE; break; } catch (java.lang.RuntimeException ex) { /* java.net.UnknownHostException lands here, as well as */ /* com.ibm.as400.access.ExtendedIllegalArgumentException */ getLogger().log(Level.SEVERE, "Command \"" + commandName + "\" threw exception", ex); lastCommandResult = COMMANDRESULT.FAILURE; break; } } else if (getFunctorMap().containsKey(commandName)) { try { TupleNameList tnl = parseTupleNameList(); if (tnl != null) { lastCommandResult = executeFunctor(getFunctor(commandName), tnl); if (lastCommandResult == COMMANDRESULT.FAILURE) { break; } } else { getLogger().log(Level.SEVERE, "Found function {0} but could not execute it", commandName); lastCommandResult = COMMANDRESULT.FAILURE; break; } } catch (java.lang.RuntimeException ex) { getLogger().log(Level.SEVERE, "Function \"" + commandName + "\" threw exception", ex); lastCommandResult = COMMANDRESULT.FAILURE; break; } } else { getLogger().log(Level.SEVERE, "Command \"{0}\" not found.", commandName); lastCommandResult = COMMANDRESULT.FAILURE; break; } } if (!isIncluding() && !initialCommandLine.isEmpty()) { if (getHistory() != null) { try { getHistory().writeLine(initialCommandLine); } catch (IOException ex) { getLogger().log(Level.WARNING, "Couldn't write to history file " + getHistory().getHistoryFileName(), ex); } } } setGlobal_ret_val(lastCommandResult.ordinal()); return lastCommandResult; } /** * Include a program already parsed into lines * * @param api400prog an instance of a an array of lines to be treated as a * program * @return the command result */ public COMMANDRESULT include(UbluProgram api400prog) { setIncluding(true); COMMANDRESULT commandResult = COMMANDRESULT.SUCCESS; for (String line : api400prog) { if (isEchoInclude()) { getErroutStream().println(":: " + line); } if (!line.isEmpty()) { ArgArray aa = new Parser(this, line).parseAnArgArray(); setArgArray(aa); commandResult = loop(); if (commandResult == COMMANDRESULT.FAILURE) { break; } } } setIncluding(false); return commandResult; } /** * Read in a text file and execute as commands * * @param filepath Path to the file of commands * @return last command result * @throws FileNotFoundException * @throws IOException */ public COMMANDRESULT include(Path filepath) throws FileNotFoundException, IOException { pushFrame(); Path currentIncludePath = getIncludePath(); if (currentIncludePath != null) { filepath = currentIncludePath.resolve(filepath.normalize()); } setIncludePath(filepath.getParent()); setIncluding(true); COMMANDRESULT commandResult = COMMANDRESULT.SUCCESS; File file = filepath.normalize().toFile(); try (FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader)) { setIncludeFileBufferedReader(bufferedReader); while (getIncludeFileBufferedReader().ready()) { String input = getIncludeFileBufferedReader().readLine(); if (isEchoInclude()) { getErroutStream().println(":: " + input); } if (!input.isEmpty()) { ArgArray aa = new Parser(this, input).parseAnArgArray(); setArgArray(aa); commandResult = loop(); if (commandResult == COMMANDRESULT.FAILURE) { break; } } } } setIncludeFileBufferedReader(null); setIncluding(false); popFrame(); return commandResult; } /** * Read a line, parse its whitespace-separated lexes into an * {@link ublu.util.ArgArray}. * * @return the {@link ublu.util.ArgArray} thus parsed */ public ArgArray readAndParse() { String input = null; ArgArray aa = new ArgArray(this); if (isIncluding()) { try { if (getIncludeFileBufferedReader() != null) { if (getIncludeFileBufferedReader().ready()) { input = getIncludeFileBufferedReader().readLine(); if (isParsingString() || isParsingBlock()) { if (isPrompting()) { outputerrln(input); } } } } else { setIncluding(false); input = ""; // so we won't exit on file failure because input == null; } } catch (IOException ex) { getLogger().log(Level.SEVERE, "IO error reading included file", ex); } } else if (isConsole()) { input = System.console().readLine(); } else { // we're reading from the input stream try { input = getInputStreamBufferedReader().readLine(); } catch (IOException ex) { getLogger().log(Level.SEVERE, "Error reading interpreter input from input stream", ex); } } if (input != null) { input = input.trim(); aa = new Parser(this, input).parseAnArgArray(); } else { setGoodBye(true); } setArgArray(aa); return getArgArray(); } /** * interactive loop until bye * * @return a global return value from the interpret loop */ public int interpret() { while (!isGoodBye()) { prompt(); readAndParse(); loop(); if (isGoodBye() && isConsole() && instanceDepth == 0) { outputerrln("Goodbye!"); } } return getGlobal_ret_val(); } /** * Prompt the user for input. Usually just a <tt>&gt;</tt> sign, but when * parsing a multiline <tt>${ quoted string }$</tt> an intermediate * continuation prompt of <tt>${</tt> */ public void prompt() { if (isPrompting()) { StringBuilder sb = new StringBuilder(instanceDepth == 0 ? "" : Integer.toString(instanceDepth)).append("> "); String thePrompt = sb.toString(); if (isParsingString()) { thePrompt = "(${) "; } if (isParsingBlock()) { sb = new StringBuilder().append('('); for (int i = 0; i < getParsingBlockDepth(); i++) { sb.append("$["); } sb.append(") "); thePrompt = sb.toString(); } if (isConsole()) { outputerr(thePrompt); } } } }
src/ublu/util/Interpreter.java
/* * Copyright (c) 2014, Absolute Performance, Inc. http://www.absolute-performance.com * Copyright (c) 2016, Jack J. Woehr [email protected] * SoftWoehr LLC PO Box 51, Golden CO 80402-0051 http://www.softwoehr.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package ublu.util; import ublu.Ublu; import java.util.logging.Level; import java.util.logging.Logger; import ublu.command.CommandInterface; import ublu.command.CommandInterface.COMMANDRESULT; import ublu.command.CommandMap; import ublu.util.Generics.UbluProgram; import ublu.util.Generics.FunctorMap; import ublu.util.Generics.InterpreterFrameStack; import ublu.util.Generics.TupleNameList; import ublu.util.Generics.TupleStack; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.nio.file.Path; import java.util.Set; import ublu.util.Generics.ConstMap; /** * command interface object * * @author jwoehr */ public class Interpreter { private Ublu myUblu; private DBug myDBug; private History history; private String historyFileName; private ConstMap constMap; private TupleMap tupleMap; private CommandMap cmdMap; private FunctorMap functorMap; private boolean good_bye; private int global_ret_val; private InterpreterFrame interpreterFrame; private InterpreterFrameStack interpreterFrameStack; private TupleStack tupleStack; private boolean break_issued; private Props props; private long paramSubIndex = 0; private int instanceDepth = 0; /** * Get the const map * * @return the const map */ public ConstMap getConstMap() { return constMap; } /** * Get constant value from the map. Return null if not found. * * @param name name of const * @return the value of const */ public String getConst(String name) { String result = null; Const theConst = constMap.get(name); if (theConst != null) { result = theConst.getValue(); } return result; } /** * Set constant value in the map. Won't set a Const with a null value. Does * not prevent a Const in the map from being overwritten, CmdConst checks * first to make sure no Const of that name exists. * * @param name name of const * @param value value of const * @return true if const was created and stored to the ConstMap, false if a * null value was passed in and no Const was created nor stored to the * ConstMap. * @see ublu.util.Const * @see ublu.command.CmdConst */ public boolean setConst(String name, String value) { boolean result = false; if (Const.isConstName(name) && value != null) { constMap.put(name, new Const(name, value)); result = true; } return result; } /** * Get nested interpreter depth * * @return nested interpreter depth */ public int getInstanceDepth() { return instanceDepth; } /** * Get properties * * @return properties */ public Props getProps() { return props; } /** * Set properties * * @param props properties */ protected final void setProps(Props props) { this.props = props; } /** * Test for a property's being set to string <code>true</code> * * @param key * @return true if set to string <code>true</code> */ public boolean isBooleanProperty(String key) { return getProperty(key, "false").equalsIgnoreCase("true"); } /** * Test for a debug subkey's being set to string <code>true</code>. The * string <code>dbug.</code> is prepended to the subkey. * * @param subkey * @return true if set to string <code>true</code> */ public boolean isDBugBooleanProperty(String subkey) { return isBooleanProperty("dbug." + subkey); } /** * Return autoincrementing parameter substitute naming deus ex machina * * @return the value before postincrementation */ protected long getParamSubIndex() { return paramSubIndex++; } /** * BREAK command just popped a frame * * @return true if BREAK command just popped a frame */ public boolean isBreakIssued() { return break_issued; } /** * Indicate BREAK command just popped a frame * * @param break_issued true if BREAK command just popped a frame */ public final void setBreakIssued(boolean break_issued) { this.break_issued = break_issued; } /** * Return the application instance * * @return the application instance */ public final Ublu getMyUblu() { return myUblu; } /** * Set the application instance * * @param myUblu the application instance */ public final void setMyUblu(Ublu myUblu) { this.myUblu = myUblu; } /** * Return the logger for this interpreter * * @return the logger for this interpreter */ public final Logger getLogger() { return getMyUblu().getLogger(); } /** * Get the current input stream to the interpret * * @return my input stream */ public final InputStream getInputStream() { return interpreterFrame.getInputStream(); } /** * Set the current input stream to the interpret * * @param inputStream my input stream */ public final void setInputStream(InputStream inputStream) { interpreterFrame.setInputStream(inputStream); } /** * Get output stream for the interpret * * @return output stream for the interpret */ public PrintStream getOutputStream() { return interpreterFrame.getOutputStream(); } /** * Set output stream for the interpret * * @param outputStream output stream for the interpret */ public final void setOutputStream(PrintStream outputStream) { interpreterFrame.setOutputStream(outputStream); } /** * Get error stream for the interpret * * @return error stream for the interpret */ public final PrintStream getErroutStream() { return interpreterFrame.getErroutStream(); } /** * Set error stream for the interpret * * @param erroutStream error stream for the interpret */ public final void setErroutStream(PrintStream erroutStream) { interpreterFrame.setErroutStream(erroutStream); } /** * Are we currently parsing a quoted string? * * @return true if currently parsing a "${" quoted string "}$" */ public boolean isParsingString() { return interpreterFrame.isParsingString(); } /** * True if we are currently parsing a quoted string. * * @param parsingString set true if currently parsing a "${" quoted string * "}$" */ public final void setParsingString(boolean parsingString) { interpreterFrame.setParsingString(parsingString); } /** * Are we currently parsing an execution block? * * @return true if currently parsing an "$[" execution block "]$" */ public boolean isParsingBlock() { return interpreterFrame.isParsingBlock(); } /** * Return parsing block depth * * @return parsing block depth */ public int getParsingBlockDepth() { return interpreterFrame.getParsingBlockDepth(); } /** * True if we are currently parsing an execution block. * * @param parsingBlock set true if currently parsing an "$[" execution block * "]$" */ public void setParsingBlock(boolean parsingBlock) { interpreterFrame.setParsingBlock(parsingBlock); } /** * Are we currently including a file of commands? * * @return true if currently including a file of commands */ public boolean isIncluding() { return interpreterFrame.isIncluding(); } /** * Echo lines of include file? * * @return true if we should be echoing include lines */ public boolean isEchoInclude() { return getProperty("includes.echo", "true").equalsIgnoreCase("true"); } /** * Echo lines of include file? * * @param tf */ public void setEchoInclude(Boolean tf) { setProperty("includes.echo", tf.toString()); } /** * Should we be prompting? * * @return true if we should be prompting */ public boolean isPrompting() { return getProperty("prompting", "true").equalsIgnoreCase("true"); } /** * Should we be prompting? * * @param tf */ public void setPrompting(Boolean tf) { setProperty("prompting", tf.toString()); } /** * Set the status of whether we are currently including a file of commands. * * @param including true if currently including a file of commands */ public final void setIncluding(boolean including) { interpreterFrame.setIncluding(including); } /** * Get the basepath of the include file which is including * * @return basepath of the include file which is including */ public Path getIncludePath() { return interpreterFrame.getIncludePath(); } /** * Set the basepath of the include file which is including * * @param includePath basepath of the include file which is including */ public void setIncludePath(Path includePath) { interpreterFrame.setIncludePath(includePath); } /** * Is the current block a FOR block or not? * * @return true iff the current block a FOR block */ public final boolean isForBlock() { return interpreterFrame.isForBlock(); } /** * Set the current block a FOR block or not. * * @param forBlock true if a FOR block * @return this */ public final Interpreter setForBlock(boolean forBlock) { interpreterFrame.setForBlock(forBlock); return this; } /** * Get the buffered reader we are using to include a file of commands. * * @return the buffered reader we are using to include a file of commands */ public BufferedReader getIncludeFileBufferedReader() { return interpreterFrame.getIncludeFileBufferedReader(); } /** * Set the buffered reader we are using to include a file of commands. * * @param includeFileBufferedReader the buffered reader we are using to * include a file of commands */ public final void setIncludeFileBufferedReader(BufferedReader includeFileBufferedReader) { interpreterFrame.setIncludeFileBufferedReader(includeFileBufferedReader); } /** * Get the buffered reader for the input stream when we don't have console * * @return the buffered reader for the input stream when we don't have * console */ public BufferedReader getInputStreamBufferedReader() { return interpreterFrame.getInputStreamBufferedReader(); } /** * Set the buffered reader for the input stream when we don't have console * * @param inputStreamBufferedReader the buffered reader for the input stream * when we don't have console */ public final void setInputStreamBufferedReader(BufferedReader inputStreamBufferedReader) { interpreterFrame.setInputStreamBufferedReader(inputStreamBufferedReader); } /** * Get the history file name that will be used next time the history manager * is instanced. * * @return history file name */ public final String getHistoryFileName() { return historyFileName; } /** * Set the history file name that will be used next time the history manager * is instanced without instancing history file * * @param historyFileName history file name */ public final void setHistoryFileName(String historyFileName) { this.historyFileName = historyFileName; } /** * Get the history manager * * @return the history manager */ public History getHistory() { return history; } /** * Set the history manager * * @param history the history manager */ public final void setHistory(History history) { this.history = history; } /** * Close the history file. */ public final void closeHistory() { try { if (getHistory() != null) { getHistory().close(); setHistory(null); } } catch (IOException ex) { getLogger().log(Level.WARNING, "Error closing history file", ex); } } /** * Close any old history file and open a new one with the name we have set * via {@link #setHistoryFileName(String)}. * */ public final void instanceHistory() { closeHistory(); try { setHistory(new History(this, getHistoryFileName())); } catch (IOException ex) { getLogger().log(Level.WARNING, "Could not open history file", ex); } } /** * A return value for the interpret, not currently used. * * @return the global return value */ public int getGlobal_ret_val() { return global_ret_val; } /** * A return value for the interpret, not currently used. * * @param global_ret_val the global return value */ public final void setGlobal_ret_val(int global_ret_val) { this.global_ret_val = global_ret_val; } /** * Signals the interpret to exit * * @return true is we're done */ public boolean isGoodBye() { return good_bye; } /** * Signals the interpret to exit * * @param good_bye true if we're done */ public final void setGoodBye(boolean good_bye) { this.good_bye = good_bye; } /** * The argument array of lexes from input * * @return my arg array */ public final ArgArray getArgArray() { return interpreterFrame.getArgArray(); } /** * The argument array of lexes from input * * @param argArray my arg array */ public final void setArgArray(ArgArray argArray) { interpreterFrame.setArgArray(argArray); } /** * The map of key-value pairs used as tuple variables in Ublu * * @return The map of key-value pairs */ public final TupleMap getTupleMap() { return tupleMap; } /** * The map of key-value pairs used as tuple variables in Ublu * * @param tupleMap The map of key-value pairs */ protected final void setTupleMap(TupleMap tupleMap) { this.tupleMap = tupleMap; } /** * Get the tuple var assigned to a key * * @param key * @return the tuple var assigned to a key */ public Tuple getTuple(String key) { return tupleMap.getTuple(key); } /** * Get the tuple var assigned to a key but don't check local map * * @param key * @return the tuple var assigned to a key */ public Tuple getTupleNoLocal(String key) { return tupleMap.getTupleNoLocal(key); } /** * Put a tuple to the most local map * * @param t the tuple * @return the tuple */ public Tuple putTupleMostLocal(Tuple t) { return tupleMap.putTupleMostLocal(t); } /** * Set a tuple var from a key and a value * * @param key tuple key * @param value tuple object value * @return the tuple which was created or set */ public Tuple setTuple(String key, Object value) { return tupleMap.setTuple(key, value); } /** * Set a tuple var from a key and a value but only in global map * * @param key tuple key * @param value tuple object value * @return the tuple which was created or set */ public Tuple setTupleNoLocal(String key, Object value) { return tupleMap.setTupleNoLocal(key, value); } /** * Delete a tuple from the map * * @param key the string key identifying the tuple * @return the object value of the deleted tuple */ public Object deleteTuple(String key) { return tupleMap.deleteTuple(key); } /** * Remove a tuple from the tuple map * * @param t the tuple to remove * @return the tuple's object value */ public Object deleteTuple(Tuple t) { tupleMap.deleteTuple(t); return t.getValue(); } /** * Get the map of commands * * @return the map of commands */ public final CommandMap getCmdMap() { return cmdMap; } /** * Set the map of commands * * @param cmdMap the map of commands */ protected final void setCmdMap(CommandMap cmdMap) { this.cmdMap = cmdMap; } /** * Get the command object matching the name * * @param i * @param cmdName name of command * @return the command object corresponding to the name */ public CommandInterface getCmd(Interpreter i, String cmdName) { return getCmdMap().getCmd(i, cmdName); } /** * Local function dictionary * * @return Local function dictionary */ public FunctorMap getFunctorMap() { return functorMap; } /** * Local function dictionary * * @param functorMap Local function dictionary */ public final void setFunctorMap(FunctorMap functorMap) { this.functorMap = functorMap; } /** * Add named function to dictionary * * @param name name of function * @param f functor */ public void addFunctor(String name, Functor f) { getFunctorMap().put(name, f); } /** * Get named functor from dictionary * * @param name name of function * @return the functor */ public Functor getFunctor(String name) { return getFunctorMap().get(name); } /** * True if name is in dictionary * * @param name name of function * @return true iff name is in dictionary */ public boolean hasFunctor(String name) { return getFunctorMap().containsKey(name); } /** * Get the tuple stack * * @return the tuple stack */ public TupleStack getTupleStack() { return tupleStack; } /** * Set the tuple stack * * @param tupleStack the tuple stack */ public final void setTupleStack(TupleStack tupleStack) { this.tupleStack = tupleStack; } /** * Do we have a console (or are we reading from a stream)? * * @return true if console active */ public boolean isConsole() { return System.console() != null && getInputStream() == System.in; } /** * Instance with args ready for the {@link #interpret} to start its first * {@link #loop}. * * @param args arguments at invocation, effectively just another command * line * @param ublu the associated instance */ public Interpreter(String[] args, Ublu ublu) { this(ublu); setArgArray(new ArgArray(this, args)); } /** * Instance with the application controller and passed-in args (commands) * set. * * @param args passed-in args (commands) * @param ublu the application controller */ public Interpreter(String args, Ublu ublu) { this(ublu); setArgArray(new Parser(this, args).parseAnArgArray()); } /** * Instance with only the application controller set * * @param ublu the application controller */ public Interpreter(Ublu ublu) { this(); setMyUblu(ublu); } /** * Copy ctor creates Interpreter with same maps i/o. * * @param i interpreter to be copied */ public Interpreter(Interpreter i) { this(); instanceDepth = i.instanceDepth + 1; setInputStream(i.getInputStream()); setInputStreamBufferedReader(i.getInputStreamBufferedReader()); setErroutStream(i.getErroutStream()); setOutputStream(i.getOutputStream()); setTupleMap(i.getTupleMap()); setCmdMap(i.getCmdMap()); setFunctorMap(i.getFunctorMap()); setHistoryFileName(i.getHistoryFileName()); setMyUblu(i.getMyUblu()); setProps(i.getProps()); constMap = new ConstMap(i.constMap); } /** * Copy ctor New instance spawned from another instance with args passed in * * @param i Instance to spawn from * @param args the args */ public Interpreter(Interpreter i, String args) { this(i); setArgArray(new Parser(this, args).parseAnArgArray()); } /** * Initialize internals such as tuple map to store variables. */ protected Interpreter() { interpreterFrame = new InterpreterFrame(); interpreterFrameStack = new InterpreterFrameStack(); setTupleStack(new TupleStack()); setInputStream(System.in); setInputStreamBufferedReader(new BufferedReader(new InputStreamReader(getInputStream()))); setErroutStream(System.err); setOutputStream(System.out); setTupleMap(new TupleMap()); setCmdMap(new CommandMap()); setFunctorMap(new FunctorMap()); setParsingString(false); setForBlock(false); setBreakIssued(false); setIncluding(false); setIncludeFileBufferedReader(null); setHistoryFileName(History.DEFAULT_HISTORY_FILENAME); setGlobal_ret_val(0); setGoodBye(false); props = new Props(); myDBug = new DBug(this); constMap = new ConstMap(); } /** * Get dbug instance * * @return the DBug instance */ public DBug dbug() { return myDBug; } /** * * @param filepath * @throws FileNotFoundException * @throws IOException */ public void readProps(String filepath) throws FileNotFoundException, IOException { props.readIn(filepath); } /** * * @param filepath * @param comment * @throws FileNotFoundException * @throws IOException */ public void writeProps(String filepath, String comment) throws FileNotFoundException, IOException { props.writeOut(filepath, comment); } /** * get a property * * @param key * @return the property */ public String getProperty(String key) { return props.get(key); } /** * get Property return a default value if non * * @param key sought * @param defaultValue default * @return value */ public final String getProperty(String key, String defaultValue) { return props.get(key, defaultValue); } /** * Set key to value * * @param key key * @param value value */ public void setProperty(String key, String value) { props.set(key, value); } /** * Get set of keys * * @return set of keys */ public Set propertyKeys() { return props.keySet(); } /** * Push a new local tuple map */ public void pushLocal() { getTupleMap().pushLocal(); } /** * Pop the local tuple map */ public void popLocal() { getTupleMap().popLocal(); } /** * Push an interpreter frame * * @return this */ public Interpreter pushFrame() { InterpreterFrame newFrame = new InterpreterFrame(interpreterFrame); interpreterFrameStack.push(interpreterFrame); getTupleMap().pushLocal(); interpreterFrame = newFrame; return this; } /** * Pop interpreter frame * * @return this */ public Interpreter popFrame() { interpreterFrame = interpreterFrameStack.pop(); getTupleMap().popLocal(); // if (getTupleMap().getLocalMap() != null) { // getTupleMap().setLocalMap(null); // } return this; } /** * How many frames have been pushed? * * @return How many frames have been pushed */ public int frameDepth() { return interpreterFrameStack.size(); } /** * Print a string to out * * @param s to print */ public void output(String s) { getOutputStream().print(s); } /** * Print a string and a newline to out * * @param s to print */ public void outputln(String s) { getOutputStream().println(s); } /** * Print a string to err * * @param s to print */ public void outputerr(String s) { getErroutStream().print(s); } /** * Print a string and a newline to err * * @param s to print */ public void outputerrln(String s) { getErroutStream().println(s); } /** * Execute a block * * @param block the block to execute * @return command result */ public COMMANDRESULT executeBlock(String block) { COMMANDRESULT rc; pushFrame(); Parser p = new Parser(this, block); setArgArray(p.parseAnArgArray()); rc = loop(); popFrame(); return rc; } /** * Create a tuple name list from the param array to a function * * @return tuple name list from the param array to a function */ public TupleNameList parseTupleNameList() { TupleNameList tnl = null; if (!getArgArray().peekNext().equals("(")) { getLogger().log(Level.SEVERE, "Missing ( parameter list ) function call."); } else { getArgArray().next(); // discard "(" tnl = new TupleNameList(); while (!getArgArray().peekNext().equals(")")) { tnl.add(getArgArray().next()); } getArgArray().next(); // discard ")" } return tnl; } /** * Execute a functor * * @param f the functor * @param tupleNames list of names to sub for params * @return command result */ public COMMANDRESULT executeFunctor(Functor f, TupleNameList tupleNames) { COMMANDRESULT rc; if (tupleNames.size() != f.numParams()) { getLogger().log(Level.SEVERE, "Unable to execute functor {0}\n which needs {1} params but received {2}", new Object[]{f, f.numParams(), tupleNames.toString()}); rc = COMMANDRESULT.FAILURE; } else { // rc = executeBlock(f.bind(tupleNames.delifoize(this))); // getTupleMap().pushLocal(); pushFrame(); String block = f.bindWithSubstitutes(this, tupleNames/*.delifoize(this)*/); rc = executeBlock(block); // getTupleMap().popLocal(); popFrame(); } return rc; } /** * Show one function in a code re-usable form * * @param funcName function to show * @return the function in a code re-usable form */ public String showFunction(String funcName) { return getFunctorMap().showFunction(funcName); } /** * List all named functions * * @return String describing all known functions */ public String listFunctions() { return getFunctorMap().listFunctions(); } /** * Remove a function from the dictionary * * @param name function name * @return boolean if was found (and removed) */ public boolean deleteFunction(String name) { return getFunctorMap().deleteFunction(name); } /** * The processing loop, processes all the input for a line until exhausted * or until a command returns a command result indicating failure. * * @return the last command result indicating success or failure. */ public COMMANDRESULT loop() { COMMANDRESULT lastCommandResult = COMMANDRESULT.SUCCESS; String initialCommandLine = getArgArray().toHistoryLine(); while (!getArgArray().isEmpty() && !good_bye && !isBreakIssued()) { String commandName = getArgArray().next().trim(); if (commandName.equals("")) { continue; // cr or some sort of whitespace got parsed, skip to next } if (getCmdMap().containsKey(commandName)) { CommandInterface command = getCmd(this, commandName); try { setArgArray(command.cmd(getArgArray())); lastCommandResult = command.getResult(); if (lastCommandResult == COMMANDRESULT.FAILURE) { break; // we exit the loop on error } } catch (IllegalArgumentException ex) { getLogger().log(Level.SEVERE, "Command \"" + commandName + "\" threw exception", ex); lastCommandResult = COMMANDRESULT.FAILURE; break; } catch (java.lang.RuntimeException ex) { /* java.net.UnknownHostException lands here, as well as */ /* com.ibm.as400.access.ExtendedIllegalArgumentException */ getLogger().log(Level.SEVERE, "Command \"" + commandName + "\" threw exception", ex); lastCommandResult = COMMANDRESULT.FAILURE; break; } } else if (getFunctorMap().containsKey(commandName)) { try { TupleNameList tnl = parseTupleNameList(); if (tnl != null) { lastCommandResult = executeFunctor(getFunctor(commandName), tnl); if (lastCommandResult == COMMANDRESULT.FAILURE) { break; } } else { getLogger().log(Level.SEVERE, "Found function {0} but could not execute it", commandName); lastCommandResult = COMMANDRESULT.FAILURE; break; } } catch (java.lang.RuntimeException ex) { getLogger().log(Level.SEVERE, "Function \"" + commandName + "\" threw exception", ex); lastCommandResult = COMMANDRESULT.FAILURE; break; } } else { getLogger().log(Level.SEVERE, "Command \"{0}\" not found.", commandName); lastCommandResult = COMMANDRESULT.FAILURE; break; } } if (!isIncluding() && !initialCommandLine.isEmpty()) { if (getHistory() != null) { try { getHistory().writeLine(initialCommandLine); } catch (IOException ex) { getLogger().log(Level.WARNING, "Couldn't write to history file " + getHistory().getHistoryFileName(), ex); } } } setGlobal_ret_val(lastCommandResult.ordinal()); return lastCommandResult; } /** * Include a program already parsed into lines * * @param api400prog an instance of a an array of lines to be treated as a * program * @return the command result */ public COMMANDRESULT include(UbluProgram api400prog) { setIncluding(true); COMMANDRESULT commandResult = COMMANDRESULT.SUCCESS; for (String line : api400prog) { if (isEchoInclude()) { getErroutStream().println(":: " + line); } if (!line.isEmpty()) { ArgArray aa = new Parser(this, line).parseAnArgArray(); setArgArray(aa); commandResult = loop(); if (commandResult == COMMANDRESULT.FAILURE) { break; } } } setIncluding(false); return commandResult; } /** * Read in a text file and execute as commands * * @param filepath Path to the file of commands * @return last command result * @throws FileNotFoundException * @throws IOException */ public COMMANDRESULT include(Path filepath) throws FileNotFoundException, IOException { pushFrame(); Path currentIncludePath = getIncludePath(); if (currentIncludePath != null) { filepath = currentIncludePath.resolve(filepath.normalize()); } setIncludePath(filepath.getParent()); setIncluding(true); COMMANDRESULT commandResult = COMMANDRESULT.SUCCESS; File file = filepath.normalize().toFile(); try (FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader)) { setIncludeFileBufferedReader(bufferedReader); while (getIncludeFileBufferedReader().ready()) { String input = getIncludeFileBufferedReader().readLine(); if (isEchoInclude()) { getErroutStream().println(":: " + input); } if (!input.isEmpty()) { ArgArray aa = new Parser(this, input).parseAnArgArray(); setArgArray(aa); commandResult = loop(); if (commandResult == COMMANDRESULT.FAILURE) { break; } } } } setIncludeFileBufferedReader(null); setIncluding(false); popFrame(); return commandResult; } /** * Read a line, parse its whitespace-separated lexes into an * {@link ublu.util.ArgArray}. * * @return the {@link ublu.util.ArgArray} thus parsed */ public ArgArray readAndParse() { String input = null; ArgArray aa = new ArgArray(this); if (isIncluding()) { try { if (getIncludeFileBufferedReader() != null) { if (getIncludeFileBufferedReader().ready()) { input = getIncludeFileBufferedReader().readLine(); if (isParsingString() || isParsingBlock()) { if (isPrompting()) { outputerrln(input); } } } } else { setIncluding(false); input = ""; // so we won't exit on file failure because input == null; } } catch (IOException ex) { getLogger().log(Level.SEVERE, "IO error reading included file", ex); } } else if (isConsole()) { input = System.console().readLine(); } else { // we're reading from the input stream try { input = getInputStreamBufferedReader().readLine(); } catch (IOException ex) { getLogger().log(Level.SEVERE, "Error reading interpreter input from input stream", ex); } } if (input != null) { input = input.trim(); aa = new Parser(this, input).parseAnArgArray(); } else { setGoodBye(true); } setArgArray(aa); return getArgArray(); } /** * interactive loop until bye * * @return a global return value from the interpret loop */ public int interpret() { while (!isGoodBye()) { prompt(); readAndParse(); loop(); if (isGoodBye() && isConsole() && instanceDepth == 0) { outputerrln("Goodbye!"); } } return getGlobal_ret_val(); } /** * Prompt the user for input. Usually just a <tt>&gt;</tt> sign, but when * parsing a multiline <tt>${ quoted string }$</tt> an intermediate * continuation prompt of <tt>${</tt> */ public void prompt() { if (isPrompting()) { StringBuilder sb = new StringBuilder(instanceDepth == 0 ? "" : Integer.toString(instanceDepth)).append("> "); String thePrompt = sb.toString(); if (isParsingString()) { thePrompt = "(${) "; } if (isParsingBlock()) { sb = new StringBuilder().append('('); for (int i = 0; i < getParsingBlockDepth(); i++) { sb.append("$["); } sb.append(") "); thePrompt = sb.toString(); } if (isConsole()) { outputerr(thePrompt); } } } }
save and restore const map
src/ublu/util/Interpreter.java
save and restore const map
<ide><path>rc/ublu/util/Interpreter.java <ide> */ <ide> public ConstMap getConstMap() { <ide> return constMap; <add> } <add> <add> /** <add> * Set the const map <add> * <add> * @param constMap the const map <add> */ <add> public void setConstMap(ConstMap constMap) { <add> this.constMap = constMap; <ide> } <ide> <ide> /**
Java
apache-2.0
015fdd74b401b57e2f78d75c0f8f36844f8fa4bb
0
retomerz/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,jagguli/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,supersven/intellij-community,fitermay/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,apixandru/intellij-community,semonte/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,caot/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,vladmm/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,apixandru/intellij-community,robovm/robovm-studio,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,holmes/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,semonte/intellij-community,slisson/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,FHannes/intellij-community,holmes/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,semonte/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,izonder/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,holmes/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,caot/intellij-community,izonder/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,apixandru/intellij-community,vladmm/intellij-community,allotria/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,izonder/intellij-community,slisson/intellij-community,petteyg/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,signed/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,da1z/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,supersven/intellij-community,kdwink/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,allotria/intellij-community,signed/intellij-community,signed/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,supersven/intellij-community,ibinti/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,retomerz/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,jagguli/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,signed/intellij-community,da1z/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,izonder/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,jagguli/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,clumsy/intellij-community,allotria/intellij-community,diorcety/intellij-community,dslomov/intellij-community,supersven/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,samthor/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,samthor/intellij-community,diorcety/intellij-community,ryano144/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,asedunov/intellij-community,dslomov/intellij-community,retomerz/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,supersven/intellij-community,apixandru/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,caot/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,fnouama/intellij-community,FHannes/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,semonte/intellij-community,FHannes/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,diorcety/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,signed/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,adedayo/intellij-community,allotria/intellij-community,jagguli/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,allotria/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,apixandru/intellij-community,blademainer/intellij-community,ryano144/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,caot/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,hurricup/intellij-community,diorcety/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,izonder/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,petteyg/intellij-community,supersven/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,kool79/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,da1z/intellij-community,caot/intellij-community,dslomov/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,caot/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,jagguli/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,caot/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,samthor/intellij-community,caot/intellij-community,slisson/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,samthor/intellij-community,blademainer/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,diorcety/intellij-community,ibinti/intellij-community,petteyg/intellij-community,apixandru/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,clumsy/intellij-community,da1z/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,supersven/intellij-community,tmpgit/intellij-community,semonte/intellij-community,dslomov/intellij-community,xfournet/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,asedunov/intellij-community,kool79/intellij-community,amith01994/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,slisson/intellij-community,slisson/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,apixandru/intellij-community,slisson/intellij-community,ryano144/intellij-community,amith01994/intellij-community,ibinti/intellij-community,slisson/intellij-community,fnouama/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,slisson/intellij-community,clumsy/intellij-community,clumsy/intellij-community,amith01994/intellij-community,kool79/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,tmpgit/intellij-community,da1z/intellij-community,signed/intellij-community,nicolargo/intellij-community,da1z/intellij-community,fnouama/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,slisson/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,caot/intellij-community,dslomov/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,amith01994/intellij-community,ryano144/intellij-community,asedunov/intellij-community,xfournet/intellij-community,amith01994/intellij-community,semonte/intellij-community,youdonghai/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,supersven/intellij-community,Distrotech/intellij-community,kool79/intellij-community,supersven/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,ryano144/intellij-community,kool79/intellij-community,orekyuu/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,signed/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,samthor/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,slisson/intellij-community,da1z/intellij-community,fnouama/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,izonder/intellij-community,amith01994/intellij-community,adedayo/intellij-community,xfournet/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,caot/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,robovm/robovm-studio,supersven/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,slisson/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,akosyakov/intellij-community,semonte/intellij-community,semonte/intellij-community,nicolargo/intellij-community,allotria/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,petteyg/intellij-community,petteyg/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,vladmm/intellij-community,supersven/intellij-community,allotria/intellij-community,da1z/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,adedayo/intellij-community
/* * Copyright 2000-2014 JetBrains s.r.o. * * 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.intellij.profile.codeInspection.ui; import com.intellij.CommonBundle; import com.intellij.codeHighlighting.HighlightDisplayLevel; import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInsight.daemon.impl.HighlightInfoType; import com.intellij.codeInsight.daemon.impl.SeverityRegistrar; import com.intellij.codeInsight.daemon.impl.SeverityUtil; import com.intellij.codeInsight.hint.HintUtil; import com.intellij.codeInspection.InspectionProfile; import com.intellij.codeInspection.InspectionsBundle; import com.intellij.codeInspection.ModifiableModel; import com.intellij.codeInspection.ex.*; import com.intellij.icons.AllIcons; import com.intellij.ide.CommonActionsManager; import com.intellij.ide.DefaultTreeExpander; import com.intellij.ide.TreeExpander; import com.intellij.ide.ui.search.SearchUtil; import com.intellij.ide.ui.search.SearchableOptionsRegistrar; import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.Splitter; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.profile.ApplicationProfileManager; import com.intellij.profile.DefaultProjectProfileManager; import com.intellij.profile.ProfileManager; import com.intellij.profile.codeInspection.InspectionProfileManager; import com.intellij.profile.codeInspection.InspectionProfileManagerImpl; import com.intellij.profile.codeInspection.InspectionProjectProfileManager; import com.intellij.profile.codeInspection.SeverityProvider; import com.intellij.profile.codeInspection.ui.filter.InspectionFilterAction; import com.intellij.profile.codeInspection.ui.filter.InspectionsFilter; import com.intellij.profile.codeInspection.ui.inspectionsTree.InspectionConfigTreeNode; import com.intellij.profile.codeInspection.ui.inspectionsTree.InspectionsConfigTreeComparator; import com.intellij.profile.codeInspection.ui.inspectionsTree.InspectionsConfigTreeRenderer; import com.intellij.profile.codeInspection.ui.inspectionsTree.InspectionsConfigTreeTable; import com.intellij.profile.codeInspection.ui.table.ScopesAndSeveritiesTable; import com.intellij.psi.search.scope.packageSet.NamedScope; import com.intellij.ui.*; import com.intellij.ui.components.JBLabel; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.Alarm; import com.intellij.util.Function; import com.intellij.util.config.StorageAccessors; import com.intellij.util.containers.*; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; import com.intellij.xml.util.XmlStringUtil; import gnu.trove.THashSet; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.io.IOException; import java.io.StringReader; import java.util.*; import java.util.HashSet; import java.util.List; /** * User: anna * Date: 31-May-2006 */ public class SingleInspectionProfilePanel extends JPanel { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.ex.InspectionToolsPanel"); @NonNls private static final String INSPECTION_FILTER_HISTORY = "INSPECTION_FILTER_HISTORY"; private static final String UNDER_CONSTRUCTION = InspectionsBundle.message("inspection.tool.description.under.construction.text"); private final List<ToolDescriptors> myInitialToolDescriptors = new ArrayList<ToolDescriptors>(); private InspectionProfileImpl mySelectedProfile; private JEditorPane myBrowser; private JPanel myOptionsPanel; private JPanel myInspectionProfilePanel = null; private FilterComponent myProfileFilter; private final InspectionsFilter myInspectionsFilter = new InspectionsFilter() { @Override protected void filterChanged() { filterTree(myProfileFilter.getFilter()); } }; private final InspectionConfigTreeNode myRoot = new InspectionConfigTreeNode(InspectionsBundle.message("inspection.root.node.title")); private final Alarm myAlarm = new Alarm(); private boolean myModified = false; private InspectionsConfigTreeTable myTreeTable; private TreeExpander myTreeExpander; @NotNull private String myInitialProfile; @NonNls private static final String EMPTY_HTML = "<html><body></body></html>"; private boolean myIsInRestore = false; @NonNls private static final String VERTICAL_DIVIDER_PROPORTION = "VERTICAL_DIVIDER_PROPORTION"; @NonNls private static final String HORIZONTAL_DIVIDER_PROPORTION = "HORIZONTAL_DIVIDER_PROPORTION"; private final StorageAccessors myProperties = StorageAccessors.createGlobal("SingleInspectionProfilePanel"); private boolean myShareProfile; private final InspectionProjectProfileManager myProjectProfileManager; private Splitter myRightSplitter; private Splitter myMainSplitter; private String[] myInitialScopesOrder; public SingleInspectionProfilePanel(@NotNull InspectionProjectProfileManager projectProfileManager, @NotNull String inspectionProfileName, @NotNull ModifiableModel profile) { super(new BorderLayout()); myProjectProfileManager = projectProfileManager; mySelectedProfile = (InspectionProfileImpl)profile; myInitialProfile = inspectionProfileName; myShareProfile = profile.getProfileManager() == projectProfileManager; } private static VisibleTreeState getExpandedNodes(InspectionProfileImpl profile) { if (profile.getProfileManager() instanceof ApplicationProfileManager) { return AppInspectionProfilesVisibleTreeState.getInstance().getVisibleTreeState(profile); } else { DefaultProjectProfileManager projectProfileManager = (DefaultProjectProfileManager)profile.getProfileManager(); return ProjectInspectionProfilesVisibleTreeState.getInstance(projectProfileManager.getProject()).getVisibleTreeState(profile); } } private void initUI() { myInspectionProfilePanel = createInspectionProfileSettingsPanel(); add(myInspectionProfilePanel, BorderLayout.CENTER); UserActivityWatcher userActivityWatcher = new UserActivityWatcher(); userActivityWatcher.addUserActivityListener(new UserActivityListener() { @Override public void stateChanged() { //invoke after all other listeners SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (mySelectedProfile == null) return; //panel was disposed updateProperSettingsForSelection(); wereToolSettingsModified(); } }); } }); userActivityWatcher.register(myOptionsPanel); updateSelectedProfileState(); reset(); } private void updateSelectedProfileState() { if (mySelectedProfile == null) return; restoreTreeState(); repaintTableData(); updateSelection(); } public void updateSelection() { if (myTreeTable != null) { final TreePath selectionPath = myTreeTable.getTree().getSelectionPath(); if (selectionPath != null) { TreeUtil.selectNode(myTreeTable.getTree(), (TreeNode) selectionPath.getLastPathComponent()); final int rowForPath = myTreeTable.getTree().getRowForPath(selectionPath); TableUtil.selectRows(myTreeTable, new int[]{rowForPath}); scrollToCenter(); } } } private void wereToolSettingsModified() { for (final ToolDescriptors toolDescriptor : myInitialToolDescriptors) { Descriptor desc = toolDescriptor.getDefaultDescriptor(); if (wereToolSettingsModified(desc)) return; List<Descriptor> descriptors = toolDescriptor.getNonDefaultDescriptors(); for (Descriptor descriptor : descriptors) { if (wereToolSettingsModified(descriptor)) return; } } myModified = false; } private boolean wereToolSettingsModified(Descriptor descriptor) { InspectionToolWrapper toolWrapper = descriptor.getToolWrapper(); if (!mySelectedProfile.isToolEnabled(descriptor.getKey(), descriptor.getScope(), myProjectProfileManager.getProject())) { return false; } Element oldConfig = descriptor.getConfig(); if (oldConfig == null) return false; Element newConfig = Descriptor.createConfigElement(toolWrapper); if (!JDOMUtil.areElementsEqual(oldConfig, newConfig)) { myAlarm.cancelAllRequests(); myAlarm.addRequest(new Runnable() { @Override public void run() { myTreeTable.repaint(); } }, 300); myModified = true; return true; } return false; } private void updateProperSettingsForSelection() { final TreePath selectionPath = myTreeTable.getTree().getSelectionPath(); if (selectionPath != null) { InspectionConfigTreeNode node = (InspectionConfigTreeNode)selectionPath.getLastPathComponent(); final Descriptor descriptor = node.getDefaultDescriptor(); if (descriptor != null) { final boolean properSetting = mySelectedProfile.isProperSetting(descriptor.getKey().toString()); if (node.isProperSetting() != properSetting) { myAlarm.cancelAllRequests(); myAlarm.addRequest(new Runnable() { @Override public void run() { myTreeTable.repaint(); } }, 300); node.dropCache(); updateUpHierarchy(node, (InspectionConfigTreeNode)node.getParent()); } } } } private void initToolStates() { final InspectionProfileImpl profile = mySelectedProfile; if (profile == null) return; myInitialToolDescriptors.clear(); final Project project = myProjectProfileManager.getProject(); for (final ScopeToolState state : profile.getDefaultStates(myProjectProfileManager.getProject())) { if (!accept(state.getTool())) continue; myInitialToolDescriptors.add(ToolDescriptors.fromScopeToolState(state, profile, project)); } myInitialScopesOrder = mySelectedProfile.getScopesOrder(); } protected boolean accept(InspectionToolWrapper entry) { return entry.getDefaultLevel() != HighlightDisplayLevel.NON_SWITCHABLE_ERROR; } private void postProcessModification() { wereToolSettingsModified(); //resetup configs for (ScopeToolState state : mySelectedProfile.getAllTools(myProjectProfileManager.getProject())) { state.resetConfigPanel(); } fillTreeData(myProfileFilter.getFilter(), true); repaintTableData(); updateOptionsAndDescriptionPanel(myTreeTable.getTree().getSelectionPaths()); } @Nullable public static ModifiableModel createNewProfile(final int initValue, ModifiableModel selectedProfile, JPanel parent, String profileName, Set<String> existingProfileNames, @NotNull Project project) { profileName = Messages.showInputDialog(parent, profileName, "Create New Inspection Profile", Messages.getQuestionIcon()); if (profileName == null) return null; final ProfileManager profileManager = selectedProfile.getProfileManager(); if (existingProfileNames.contains(profileName)) { Messages.showErrorDialog(InspectionsBundle.message("inspection.unable.to.create.profile.message", profileName), InspectionsBundle.message("inspection.unable.to.create.profile.dialog.title")); return null; } InspectionProfileImpl inspectionProfile = new InspectionProfileImpl(profileName, InspectionToolRegistrar.getInstance(), profileManager); if (initValue == -1) { inspectionProfile.initInspectionTools(project); ModifiableModel profileModifiableModel = inspectionProfile.getModifiableModel(); final InspectionToolWrapper[] profileEntries = profileModifiableModel.getInspectionTools(null); for (InspectionToolWrapper toolWrapper : profileEntries) { profileModifiableModel.disableTool(toolWrapper.getShortName(), null, project); } profileModifiableModel.setLocal(true); profileModifiableModel.setModified(true); return profileModifiableModel; } else if (initValue == 0) { inspectionProfile.copyFrom(selectedProfile); inspectionProfile.setName(profileName); inspectionProfile.initInspectionTools(project); inspectionProfile.setModified(true); return inspectionProfile; } return null; } public void setFilter(String filter) { myProfileFilter.setFilter(filter); } private void filterTree(@Nullable String filter) { if (myTreeTable != null) { getExpandedNodes(mySelectedProfile).saveVisibleState(myTreeTable.getTree()); fillTreeData(filter, true); reloadModel(); restoreTreeState(); if (myTreeTable.getTree().getSelectionPath() == null) { TreeUtil.selectFirstNode(myTreeTable.getTree()); } } } private void filterTree() { filterTree(myProfileFilter != null ? myProfileFilter.getFilter() : null); } private void reloadModel() { try { myIsInRestore = true; ((DefaultTreeModel)myTreeTable.getTree().getModel()).reload(); } finally { myIsInRestore = false; } } private void restoreTreeState() { try { myIsInRestore = true; getExpandedNodes(mySelectedProfile).restoreVisibleState(myTreeTable.getTree()); } finally { myIsInRestore = false; } } private ActionToolbar createTreeToolbarPanel() { final CommonActionsManager actionManager = CommonActionsManager.getInstance(); DefaultActionGroup actions = new DefaultActionGroup(); actions.add(new InspectionFilterAction(mySelectedProfile, myInspectionsFilter)); actions.addSeparator(); actions.add(actionManager.createExpandAllAction(myTreeExpander, myTreeTable)); actions.add(actionManager.createCollapseAllAction(myTreeExpander, myTreeTable)); actions.add(new AnAction("Reset to Empty", "Reset to empty", AllIcons.Actions.Reset_to_empty){ @Override public void update(AnActionEvent e) { e.getPresentation().setEnabled(mySelectedProfile != null && mySelectedProfile.isExecutable(myProjectProfileManager.getProject())); } @Override public void actionPerformed(AnActionEvent e) { mySelectedProfile.resetToEmpty(e.getProject()); postProcessModification(); } }); actions.add(new AdvancedSettingsAction(myProjectProfileManager.getProject(), myRoot) { @Override protected InspectionProfileImpl getInspectionProfile() { return mySelectedProfile; } @Override protected void postProcessModification() { SingleInspectionProfilePanel.this.postProcessModification(); } }); final ActionToolbar actionToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, actions, true); actionToolbar.setTargetComponent(this); return actionToolbar; } private void repaintTableData() { if (myTreeTable != null) { getExpandedNodes(mySelectedProfile).saveVisibleState(myTreeTable.getTree()); reloadModel(); restoreTreeState(); } } public void selectInspectionTool(String name) { final InspectionConfigTreeNode node = findNodeByKey(name, myRoot); if (node != null) { TreeUtil.selectNode(myTreeTable.getTree(), node); final int rowForPath = myTreeTable.getTree().getRowForPath(new TreePath(node.getPath())); TableUtil.selectRows(myTreeTable, new int[]{rowForPath}); scrollToCenter(); } } private void scrollToCenter() { ListSelectionModel selectionModel = myTreeTable.getSelectionModel(); int maxSelectionIndex = selectionModel.getMaxSelectionIndex(); final int maxColumnSelectionIndex = Math.max(0, myTreeTable.getColumnModel().getSelectionModel().getMinSelectionIndex()); Rectangle maxCellRect = myTreeTable.getCellRect(maxSelectionIndex, maxColumnSelectionIndex, false); final Point selectPoint = maxCellRect.getLocation(); final int allHeight = myTreeTable.getVisibleRect().height; myTreeTable.scrollRectToVisible(new Rectangle(new Point(0, Math.max(0, selectPoint.y - allHeight / 2)), new Dimension(0, allHeight))); } @Nullable private static InspectionConfigTreeNode findNodeByKey(String name, InspectionConfigTreeNode root) { for (int i = 0; i < root.getChildCount(); i++) { final InspectionConfigTreeNode child = (InspectionConfigTreeNode)root.getChildAt(i); final Descriptor descriptor = child.getDefaultDescriptor(); if (descriptor != null) { if (descriptor.getKey().toString().equals(name)) { return child; } } else { final InspectionConfigTreeNode node = findNodeByKey(name, child); if (node != null) return node; } } return null; } private JScrollPane initTreeScrollPane() { fillTreeData(null, true); final InspectionsConfigTreeRenderer renderer = new InspectionsConfigTreeRenderer(){ @Override protected String getFilter() { return myProfileFilter != null ? myProfileFilter.getFilter() : null; } }; myTreeTable = new InspectionsConfigTreeTable(new InspectionsConfigTreeTable.InspectionsConfigTreeTableSettings(myRoot, myProjectProfileManager.getProject()) { @Override protected void onChanged(final InspectionConfigTreeNode node) { updateOptionsAndDescriptionPanel(); updateUpHierarchy(node, (InspectionConfigTreeNode)node.getParent()); } @Override public InspectionProfileImpl getInspectionProfile() { return mySelectedProfile; } }); myTreeTable.setTreeCellRenderer(renderer); myTreeTable.setRootVisible(false); UIUtil.setLineStyleAngled(myTreeTable.getTree()); TreeUtil.installActions(myTreeTable.getTree()); myTreeTable.getTree().addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { if (myTreeTable.getTree().getSelectionPaths() != null) { updateOptionsAndDescriptionPanel(myTreeTable.getTree().getSelectionPaths()); } else { initOptionsAndDescriptionPanel(); } if (!myIsInRestore) { InspectionProfileImpl selected = mySelectedProfile; if (selected != null) { InspectionProfileImpl baseProfile = (InspectionProfileImpl)selected.getParentProfile(); if (baseProfile != null) { getExpandedNodes(baseProfile).setSelectionPaths(myTreeTable.getTree().getSelectionPaths()); } getExpandedNodes(selected).setSelectionPaths(myTreeTable.getTree().getSelectionPaths()); } } } }); myTreeTable.addMouseListener(new PopupHandler() { @Override public void invokePopup(Component comp, int x, int y) { final int[] selectionRows = myTreeTable.getTree().getSelectionRows(); if (selectionRows != null && myTreeTable.getTree().getPathForLocation(x, y) != null && Arrays.binarySearch(selectionRows, myTreeTable.getTree().getRowForLocation(x, y)) > -1) { compoundPopup().show(comp, x, y); } } }); new TreeSpeedSearch(myTreeTable.getTree(), new Convertor<TreePath, String>() { @Override public String convert(TreePath o) { final InspectionConfigTreeNode node = (InspectionConfigTreeNode)o.getLastPathComponent(); final Descriptor descriptor = node.getDefaultDescriptor(); return descriptor != null ? InspectionsConfigTreeComparator.getDisplayTextToSort(descriptor.getText()) : InspectionsConfigTreeComparator .getDisplayTextToSort(node.getGroupName()); } }); final JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myTreeTable); myTreeTable.getTree().setShowsRootHandles(true); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); TreeUtil.collapseAll(myTreeTable.getTree(), 1); myTreeTable.getTree().addTreeExpansionListener(new TreeExpansionListener() { @Override public void treeCollapsed(TreeExpansionEvent event) { InspectionProfileImpl selected = mySelectedProfile; final InspectionConfigTreeNode node = (InspectionConfigTreeNode)event.getPath().getLastPathComponent(); final InspectionProfileImpl parentProfile = (InspectionProfileImpl)selected.getParentProfile(); if (parentProfile != null) { getExpandedNodes(parentProfile).saveVisibleState(myTreeTable.getTree()); } getExpandedNodes(selected).saveVisibleState(myTreeTable.getTree()); } @Override public void treeExpanded(TreeExpansionEvent event) { InspectionProfileImpl selected = mySelectedProfile; if (selected != null) { final InspectionConfigTreeNode node = (InspectionConfigTreeNode)event.getPath().getLastPathComponent(); final InspectionProfileImpl parentProfile = (InspectionProfileImpl)selected.getParentProfile(); if (parentProfile != null) { getExpandedNodes(parentProfile).expandNode(node); } getExpandedNodes(selected).expandNode(node); } } }); myTreeExpander = new DefaultTreeExpander(myTreeTable.getTree()) { @Override public boolean canExpand() { return myTreeTable.isShowing(); } @Override public boolean canCollapse() { return myTreeTable.isShowing(); } }; myProfileFilter = new MyFilterComponent(); return scrollPane; } private JPopupMenu compoundPopup() { final DefaultActionGroup group = new DefaultActionGroup(); final SeverityRegistrar severityRegistrar = ((SeverityProvider)mySelectedProfile.getProfileManager()).getOwnSeverityRegistrar(); TreeSet<HighlightSeverity> severities = new TreeSet<HighlightSeverity>(severityRegistrar); severities.add(HighlightSeverity.ERROR); severities.add(HighlightSeverity.WARNING); severities.add(HighlightSeverity.WEAK_WARNING); final Collection<SeverityRegistrar.SeverityBasedTextAttributes> infoTypes = SeverityUtil.getRegisteredHighlightingInfoTypes(severityRegistrar); for (SeverityRegistrar.SeverityBasedTextAttributes info : infoTypes) { severities.add(info.getSeverity()); } for (HighlightSeverity severity : severities) { final HighlightDisplayLevel level = HighlightDisplayLevel.find(severity); group.add(new AnAction(renderSeverity(severity), renderSeverity(severity), level.getIcon()) { @Override public void actionPerformed(AnActionEvent e) { setNewHighlightingLevel(level); } }); } group.add(Separator.getInstance()); ActionPopupMenu menu = ActionManager.getInstance().createActionPopupMenu(ActionPlaces.UNKNOWN, group); return menu.getComponent(); } public static String renderSeverity(HighlightSeverity severity) { return StringUtil.capitalizeWords(severity.getName().toLowerCase(), true); } private static void updateUpHierarchy(final InspectionConfigTreeNode node, final InspectionConfigTreeNode parent) { if (parent != null) { parent.dropCache(); updateUpHierarchy(parent, (InspectionConfigTreeNode)parent.getParent()); } } private static boolean isDescriptorAccepted(Descriptor descriptor, @NonNls String filter, final boolean forceInclude, final List<Set<String>> keySetList, final Set<String> quoted) { filter = filter.toLowerCase(); if (StringUtil.containsIgnoreCase(descriptor.getText(), filter)) { return true; } final String[] groupPath = descriptor.getGroup(); for (String group : groupPath) { if (StringUtil.containsIgnoreCase(group, filter)) { return true; } } for (String stripped : quoted) { if (StringUtil.containsIgnoreCase(descriptor.getText(),stripped)) { return true; } for (String group : groupPath) { if (StringUtil.containsIgnoreCase(group,stripped)) { return true; } } final String description = descriptor.getToolWrapper().loadDescription(); if (description != null && StringUtil.containsIgnoreCase(description.toLowerCase(), stripped)) { if (!forceInclude) return true; } else if (forceInclude) return false; } for (Set<String> keySet : keySetList) { if (keySet.contains(descriptor.getKey().toString())) { if (!forceInclude) { return true; } } else { if (forceInclude) { return false; } } } return forceInclude; } private void fillTreeData(@Nullable String filter, boolean forceInclude) { if (mySelectedProfile == null) return; myRoot.removeAllChildren(); myRoot.dropCache(); List<Set<String>> keySetList = new ArrayList<Set<String>>(); final Set<String> quoted = new HashSet<String>(); if (filter != null && !filter.isEmpty()) { keySetList.addAll(SearchUtil.findKeys(filter, quoted)); } Project project = myProjectProfileManager.getProject(); final boolean emptyFilter = myInspectionsFilter.isEmptyFilter(); for (ToolDescriptors toolDescriptors : myInitialToolDescriptors) { final Descriptor descriptor = toolDescriptors.getDefaultDescriptor(); if (filter != null && !filter.isEmpty() && !isDescriptorAccepted(descriptor, filter, forceInclude, keySetList, quoted)) { continue; } if (!emptyFilter && !myInspectionsFilter.matches(mySelectedProfile.getTools(toolDescriptors.getDefaultDescriptor().getKey().toString(), project))) { continue; } final InspectionConfigTreeNode node = new InspectionConfigTreeNode(toolDescriptors); getGroupNode(myRoot, toolDescriptors.getDefaultDescriptor().getGroup()).add(node); myRoot.dropCache(); } if (filter != null && forceInclude && myRoot.getChildCount() == 0) { final Set<String> filters = SearchableOptionsRegistrar.getInstance().getProcessedWords(filter); if (filters.size() > 1 || !quoted.isEmpty()) { fillTreeData(filter, false); } } TreeUtil.sort(myRoot, new InspectionsConfigTreeComparator()); } private void updateOptionsAndDescriptionPanel(final TreePath... paths) { if (mySelectedProfile == null || paths == null || paths.length == 0) { return; } final TreePath path = paths[0]; if (path == null) return; final List<InspectionConfigTreeNode> nodes = InspectionsAggregationUtil.getInspectionsNodes(paths); if (!nodes.isEmpty()) { final InspectionConfigTreeNode singleNode = paths.length == 1 && ((InspectionConfigTreeNode)paths[0].getLastPathComponent()).getDefaultDescriptor() != null ? ContainerUtil.getFirstItem(nodes) : null; if (singleNode != null && singleNode.getDefaultDescriptor().loadDescription() != null) { // need this in order to correctly load plugin-supplied descriptions final Descriptor defaultDescriptor = singleNode.getDefaultDescriptor(); final String description = defaultDescriptor.loadDescription(); try { final HintHint hintHint = new HintHint(myBrowser, new Point(0, 0)); hintHint.setFont(myBrowser.getFont()); myBrowser .read(new StringReader(SearchUtil.markup(HintUtil.prepareHintText(description, hintHint), myProfileFilter.getFilter())), null); } catch (IOException e2) { try { //noinspection HardCodedStringLiteral myBrowser.read(new StringReader(XmlStringUtil.wrapInHtml("<b>" + UNDER_CONSTRUCTION + "</b>")), null); } catch (IOException e1) { //Can't be } } catch (Throwable t) { LOG.error("Failed to load description for: " + defaultDescriptor.getToolWrapper().getTool().getClass() + "; description: " + description, t); } } else { try { myBrowser.read(new StringReader("<html><body>Multiple inspections are selected. You can edit them as a single inspection.</body></html>"), null); } catch (IOException e1) { //Can't be } } myOptionsPanel.removeAll(); final Project project = myProjectProfileManager.getProject(); final JPanel severityPanel = new JPanel(new GridBagLayout()); final double severityPanelWeightY; final JPanel configPanelAnchor = new JPanel(new GridLayout()); final Set<String> scopesNames = new THashSet<String>(); for (final InspectionConfigTreeNode node : nodes) { final List<ScopeToolState> nonDefaultTools = mySelectedProfile.getNonDefaultTools(node.getDefaultDescriptor().getKey().toString(), project); for (final ScopeToolState tool : nonDefaultTools) { scopesNames.add(tool.getScopeName()); } } if (scopesNames.isEmpty()) { final LevelChooserAction severityLevelChooser = new LevelChooserAction(mySelectedProfile) { @Override protected void onChosen(final HighlightSeverity severity) { final HighlightDisplayLevel level = HighlightDisplayLevel.find(severity); for (final InspectionConfigTreeNode node : nodes) { final HighlightDisplayKey key = node.getDefaultDescriptor().getKey(); final NamedScope scope = node.getDefaultDescriptor().getScope(); final boolean toUpdate = mySelectedProfile.getErrorLevel(key, scope, project) != level; mySelectedProfile.setErrorLevel(key, level, null, project); if (toUpdate) node.dropCache(); } } }; final HighlightSeverity severity = ScopesAndSeveritiesTable.getSeverity(ContainerUtil.map(nodes, new Function<InspectionConfigTreeNode, ScopeToolState>() { @Override public ScopeToolState fun(InspectionConfigTreeNode node) { return node.getDefaultDescriptor().getState(); } })); severityLevelChooser.setChosen(severity); final ScopesChooser scopesChooser = new ScopesChooser(ContainerUtil.map(nodes, new Function<InspectionConfigTreeNode, Descriptor>() { @Override public Descriptor fun(final InspectionConfigTreeNode node) { return node.getDefaultDescriptor(); } }), mySelectedProfile, project, null) { @Override protected void onScopesOrderChanged() { myTreeTable.getTree().updateUI(); updateOptionsAndDescriptionPanel(); } @Override protected void onScopeAdded() { updateOptionsAndDescriptionPanel(); } }; severityPanel.add(new JLabel(InspectionsBundle.message("inspection.severity")), new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(10, 0, 10, 10), 0, 0)); severityPanel.add(severityLevelChooser.createCustomComponent(severityLevelChooser.getTemplatePresentation()), new GridBagConstraints(1, 0, 1, 1, 1.0, 0, GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(10, 0, 10, 0), 0, 0)); severityPanel.add(scopesChooser.createCustomComponent(scopesChooser.getTemplatePresentation()), new GridBagConstraints(2, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(10, 0, 10, 0), 0, 0)); severityPanelWeightY = 0.0; if (singleNode != null) { setConfigPanel(configPanelAnchor, mySelectedProfile.getToolDefaultState(singleNode.getDefaultDescriptor().getKey().toString(), project)); } } else { if (singleNode != null) { for (final Descriptor descriptor : singleNode.getDescriptors().getNonDefaultDescriptors()) { descriptor.loadConfig(); } } final JTable scopesAndScopesAndSeveritiesTable = new ScopesAndSeveritiesTable(new ScopesAndSeveritiesTable.TableSettings(nodes, mySelectedProfile, myTreeTable, project) { @Override protected void onScopeChosen(@NotNull final ScopeToolState state) { setConfigPanel(configPanelAnchor, state); configPanelAnchor.revalidate(); configPanelAnchor.repaint(); } @Override protected void onSettingsChanged() { myTreeTable.getTree().updateUI(); } @Override protected void onScopeAdded() { updateOptionsAndDescriptionPanel(); } @Override protected void onScopesOrderChanged() { myTreeTable.getTree().updateUI(); updateOptionsAndDescriptionPanel(); } @Override protected void onScopeRemoved(final int scopesCount) { if (scopesCount == 1) { updateOptionsAndDescriptionPanel(); } } }); final ToolbarDecorator wrappedTable = ToolbarDecorator.createDecorator(scopesAndScopesAndSeveritiesTable).disableUpDownActions(); final JPanel panel = wrappedTable.createPanel(); panel.setMinimumSize(new Dimension(getMinimumSize().width, 3 * scopesAndScopesAndSeveritiesTable.getRowHeight())); severityPanel.add(new JBLabel("Scopes & Severities"), new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 0, 2, 10), 0, 0)); severityPanel.add(new JBLabel("Add scope to change its settings", UIUtil.ComponentStyle.SMALL), new GridBagConstraints(1, 0, 1, 1, 1.0, 0, GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(5, 0, 2, 0), 0, 0)); severityPanel.add(panel, new GridBagConstraints(0, 1, 2, 1, 0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); severityPanelWeightY = 0.3; } myOptionsPanel.add(severityPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, severityPanelWeightY, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); if (configPanelAnchor.getComponentCount() != 0) { configPanelAnchor.setBorder(IdeBorderFactory.createTitledBorder("Options", false, new Insets(0, 0, 0, 0))); } if (configPanelAnchor.getComponentCount() != 0 || scopesNames.isEmpty()) { myOptionsPanel.add(configPanelAnchor, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); } myOptionsPanel.revalidate(); GuiUtils.enableChildren(myOptionsPanel, isThoughOneNodeEnabled(nodes)); } else { initOptionsAndDescriptionPanel(); } myOptionsPanel.repaint(); } private boolean isThoughOneNodeEnabled(final List<InspectionConfigTreeNode> nodes) { final Project project = myProjectProfileManager.getProject(); for (final InspectionConfigTreeNode node : nodes) { final String toolId = node.getDefaultDescriptor().getKey().toString(); if (mySelectedProfile.getTools(toolId, project).isEnabled()) { return true; } } return false; } private void updateOptionsAndDescriptionPanel() { final TreePath[] paths = myTreeTable.getTree().getSelectionPaths(); if (paths != null) { updateOptionsAndDescriptionPanel(paths); } else { initOptionsAndDescriptionPanel(); } } private void initOptionsAndDescriptionPanel() { myOptionsPanel.removeAll(); try { myBrowser.read(new StringReader(EMPTY_HTML), null); } catch (IOException e1) { //Can't be } myOptionsPanel.validate(); myOptionsPanel.repaint(); } private static void setConfigPanel(final JPanel configPanelAnchor, final ScopeToolState state) { configPanelAnchor.removeAll(); final JComponent additionalConfigPanel = state.getAdditionalConfigPanel(); if (additionalConfigPanel != null) { configPanelAnchor.add(ScrollPaneFactory.createScrollPane(additionalConfigPanel, SideBorder.NONE)); } } private static InspectionConfigTreeNode getGroupNode(InspectionConfigTreeNode root, String[] groupPath) { InspectionConfigTreeNode currentRoot = root; for (final String group : groupPath) { currentRoot = getGroupNode(currentRoot, group); } return currentRoot; } private static InspectionConfigTreeNode getGroupNode(InspectionConfigTreeNode root, String group) { final int childCount = root.getChildCount(); for (int i = 0; i < childCount; i++) { InspectionConfigTreeNode child = (InspectionConfigTreeNode)root.getChildAt(i); if (group.equals(child.getUserObject())) { return child; } } InspectionConfigTreeNode child = new InspectionConfigTreeNode(group); root.add(child); return child; } public boolean setSelectedProfileModified(boolean modified) { mySelectedProfile.setModified(modified); return modified; } ModifiableModel getSelectedProfile() { return mySelectedProfile; } private void setSelectedProfile(final ModifiableModel modifiableModel) { if (mySelectedProfile == modifiableModel) return; mySelectedProfile = (InspectionProfileImpl)modifiableModel; if (mySelectedProfile != null) { myInitialProfile = mySelectedProfile.getName(); } initToolStates(); filterTree(); } @Override public Dimension getPreferredSize() { return new Dimension(700, 500); } public void disposeUI() { if (myInspectionProfilePanel == null) { return; } myProperties.setFloat(VERTICAL_DIVIDER_PROPORTION, myMainSplitter.getProportion()); myProperties.setFloat(HORIZONTAL_DIVIDER_PROPORTION, myRightSplitter.getProportion()); myAlarm.cancelAllRequests(); myProfileFilter.dispose(); if (mySelectedProfile != null) { for (ScopeToolState state : mySelectedProfile.getAllTools(myProjectProfileManager.getProject())) { state.resetConfigPanel(); } } mySelectedProfile = null; } private JPanel createInspectionProfileSettingsPanel() { myBrowser = new JEditorPane(UIUtil.HTML_MIME, EMPTY_HTML); myBrowser.setEditable(false); myBrowser.setBorder(IdeBorderFactory.createEmptyBorder(5, 5, 5, 5)); myBrowser.addHyperlinkListener(new BrowserHyperlinkListener()); initToolStates(); fillTreeData(myProfileFilter != null ? myProfileFilter.getFilter() : null, true); JPanel descriptionPanel = new JPanel(new BorderLayout()); descriptionPanel.setBorder(IdeBorderFactory.createTitledBorder(InspectionsBundle.message("inspection.description.title"), false, new Insets(13, 0, 0, 0))); descriptionPanel.add(ScrollPaneFactory.createScrollPane(myBrowser), BorderLayout.CENTER); myRightSplitter = new Splitter(true); myRightSplitter.setFirstComponent(descriptionPanel); myRightSplitter.setProportion(myProperties.getFloat(HORIZONTAL_DIVIDER_PROPORTION, 0.5f)); myOptionsPanel = new JPanel(new GridBagLayout()); initOptionsAndDescriptionPanel(); myRightSplitter.setSecondComponent(myOptionsPanel); myRightSplitter.setHonorComponentsMinimumSize(true); final JPanel treePanel = new JPanel(new BorderLayout()); final JScrollPane tree = initTreeScrollPane(); treePanel.add(tree, BorderLayout.CENTER); final JPanel northPanel = new JPanel(new GridBagLayout()); northPanel.setBorder(IdeBorderFactory.createEmptyBorder(2, 0, 2, 0)); northPanel.add(myProfileFilter, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.BASELINE_TRAILING, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); northPanel.add(createTreeToolbarPanel().getComponent(), new GridBagConstraints(1, 0, 1, 1, 0.5, 1, GridBagConstraints.BASELINE_LEADING, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); treePanel.add(northPanel, BorderLayout.NORTH); myMainSplitter = new Splitter(false); myMainSplitter.setFirstComponent(treePanel); myMainSplitter.setSecondComponent(myRightSplitter); myMainSplitter.setHonorComponentsMinimumSize(false); myMainSplitter.setProportion(myProperties.getFloat(VERTICAL_DIVIDER_PROPORTION, 0.5f)); final JPanel panel = new JPanel(new BorderLayout()); panel.add(myMainSplitter, BorderLayout.CENTER); return panel; } public boolean isModified() { if (myModified) return true; if (mySelectedProfile.isChanged()) return true; if (myShareProfile != (mySelectedProfile.getProfileManager() == myProjectProfileManager)) return true; if (!Comparing.strEqual(myInitialProfile, mySelectedProfile.getName())) return true; if (!Comparing.equal(myInitialScopesOrder, mySelectedProfile.getScopesOrder())) return true; if (descriptorsAreChanged()) { return true; } return false; } public void reset() { myModified = false; setSelectedProfile(mySelectedProfile); final String filter = myProfileFilter.getFilter(); myProfileFilter.reset(); myProfileFilter.setSelectedItem(filter); myShareProfile = mySelectedProfile.getProfileManager() == myProjectProfileManager; } public void apply() throws ConfigurationException { final boolean modified = isModified(); if (!modified) { return; } final ModifiableModel selectedProfile = getSelectedProfile(); final ProfileManager profileManager = myShareProfile ? myProjectProfileManager : InspectionProfileManager.getInstance(); selectedProfile.setLocal(!myShareProfile); if (selectedProfile.getProfileManager() != profileManager) { if (selectedProfile.getProfileManager().getProfile(selectedProfile.getName(), false) != null) { selectedProfile.getProfileManager().deleteProfile(selectedProfile.getName()); } copyUsedSeveritiesIfUndefined(selectedProfile, profileManager); selectedProfile.setProfileManager(profileManager); } final InspectionProfile parentProfile = selectedProfile.getParentProfile(); if (((InspectionProfileManagerImpl)InspectionProfileManager.getInstance()).getSchemesManager().isShared(selectedProfile)) { if (descriptorsAreChanged()) { throw new ConfigurationException("Shared profile cannot be modified. Please do \"Save As...\" first."); } } try { selectedProfile.commit(); } catch (IOException e) { throw new ConfigurationException(e.getMessage()); } setSelectedProfile(parentProfile.getModifiableModel()); setSelectedProfileModified(false); myModified = false; } private static void copyUsedSeveritiesIfUndefined(final ModifiableModel selectedProfile, final ProfileManager profileManager) { final SeverityRegistrar registrar = ((SeverityProvider)profileManager).getSeverityRegistrar(); final Set<HighlightSeverity> severities = ((InspectionProfileImpl)selectedProfile).getUsedSeverities(); for (Iterator<HighlightSeverity> iterator = severities.iterator(); iterator.hasNext();) { HighlightSeverity severity = iterator.next(); if (registrar.isSeverityValid(severity.getName())) { iterator.remove(); } } if (!severities.isEmpty()) { final SeverityRegistrar oppositeRegister = ((SeverityProvider)selectedProfile.getProfileManager()).getSeverityRegistrar(); for (HighlightSeverity severity : severities) { final TextAttributesKey attributesKey = TextAttributesKey.find(severity.getName()); final TextAttributes textAttributes = oppositeRegister.getTextAttributesBySeverity(severity); LOG.assertTrue(textAttributes != null, severity); HighlightInfoType.HighlightInfoTypeImpl info = new HighlightInfoType.HighlightInfoTypeImpl(severity, attributesKey); registrar.registerSeverity(new SeverityRegistrar.SeverityBasedTextAttributes(textAttributes.clone(), info), textAttributes.getErrorStripeColor()); } } } private boolean descriptorsAreChanged() { for (ToolDescriptors toolDescriptors : myInitialToolDescriptors) { Descriptor desc = toolDescriptors.getDefaultDescriptor(); Project project = myProjectProfileManager.getProject(); if (mySelectedProfile.isToolEnabled(desc.getKey(), null, project) != desc.isEnabled()){ return true; } if (mySelectedProfile.getErrorLevel(desc.getKey(), desc.getScope(), project) != desc.getLevel()) { return true; } final List<Descriptor> descriptors = toolDescriptors.getNonDefaultDescriptors(); for (Descriptor descriptor : descriptors) { if (mySelectedProfile.isToolEnabled(descriptor.getKey(), descriptor.getScope(), project) != descriptor.isEnabled()) { return true; } if (mySelectedProfile.getErrorLevel(descriptor.getKey(), descriptor.getScope(), project) != descriptor.getLevel()) { return true; } } final List<ScopeToolState> tools = mySelectedProfile.getNonDefaultTools(desc.getKey().toString(), project); if (tools.size() != descriptors.size()) { return true; } for (int i = 0; i < tools.size(); i++) { final ScopeToolState pair = tools.get(i); if (!Comparing.equal(pair.getScope(project), descriptors.get(i).getScope())) { return true; } } } return false; } public boolean isProfileShared() { return myShareProfile; } public void setProfileShared(boolean profileShared) { myShareProfile = profileShared; } @Override public void setVisible(boolean aFlag) { if (aFlag && myInspectionProfilePanel == null) { initUI(); } super.setVisible(aFlag); } private void setNewHighlightingLevel(@NotNull HighlightDisplayLevel level) { final int[] rows = myTreeTable.getTree().getSelectionRows(); final boolean showOptionsAndDescriptorPanels = rows != null && rows.length == 1; for (int i = 0; rows != null && i < rows.length; i++) { final InspectionConfigTreeNode node = (InspectionConfigTreeNode)myTreeTable.getTree().getPathForRow(rows[i]).getLastPathComponent(); final InspectionConfigTreeNode parent = (InspectionConfigTreeNode)node.getParent(); final Object userObject = node.getUserObject(); if (userObject instanceof ToolDescriptors && (node.getScopeName() != null || node.isLeaf())) { updateErrorLevel(node, showOptionsAndDescriptorPanels, level); updateUpHierarchy(node, parent); } else { updateErrorLevelUpInHierarchy(level, showOptionsAndDescriptorPanels, node); updateUpHierarchy(node, parent); } } if (rows != null) { updateOptionsAndDescriptionPanel(myTreeTable.getTree().getSelectionPaths()); } else { initOptionsAndDescriptionPanel(); } repaintTableData(); } private void updateErrorLevelUpInHierarchy(@NotNull HighlightDisplayLevel level, boolean showOptionsAndDescriptorPanels, InspectionConfigTreeNode node) { node.dropCache(); for (int j = 0; j < node.getChildCount(); j++) { final InspectionConfigTreeNode child = (InspectionConfigTreeNode)node.getChildAt(j); final Object userObject = child.getUserObject(); if (userObject instanceof ToolDescriptors && (child.getScopeName() != null || child.isLeaf())) { updateErrorLevel(child, showOptionsAndDescriptorPanels, level); } else { updateErrorLevelUpInHierarchy(level, showOptionsAndDescriptorPanels, child); } } } private void updateErrorLevel(final InspectionConfigTreeNode child, final boolean showOptionsAndDescriptorPanels, @NotNull HighlightDisplayLevel level) { final HighlightDisplayKey key = child.getDefaultDescriptor().getKey(); mySelectedProfile.setErrorLevel(key, level, null, myProjectProfileManager.getProject()); child.dropCache(); if (showOptionsAndDescriptorPanels) { updateOptionsAndDescriptionPanel(new TreePath(child.getPath())); } } public JComponent getTree() { return myTreeTable == null ? null : myTreeTable.getTree(); } private class MyFilterComponent extends FilterComponent { private MyFilterComponent() { super(INSPECTION_FILTER_HISTORY, 10); setHistory(Arrays.asList("\"New in 13\"")); } @Override public void filter() { filterTree(getFilter()); } @Override protected void onlineFilter() { if (mySelectedProfile == null) return; final String filter = getFilter(); getExpandedNodes(mySelectedProfile).saveVisibleState(myTreeTable.getTree()); fillTreeData(filter, true); reloadModel(); if (filter == null || filter.isEmpty()) { restoreTreeState(); } else { TreeUtil.expandAll(myTreeTable.getTree()); } } } }
platform/lang-impl/src/com/intellij/profile/codeInspection/ui/SingleInspectionProfilePanel.java
/* * Copyright 2000-2014 JetBrains s.r.o. * * 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.intellij.profile.codeInspection.ui; import com.intellij.CommonBundle; import com.intellij.codeHighlighting.HighlightDisplayLevel; import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInsight.daemon.impl.HighlightInfoType; import com.intellij.codeInsight.daemon.impl.SeverityRegistrar; import com.intellij.codeInsight.daemon.impl.SeverityUtil; import com.intellij.codeInsight.hint.HintUtil; import com.intellij.codeInspection.InspectionProfile; import com.intellij.codeInspection.InspectionsBundle; import com.intellij.codeInspection.ModifiableModel; import com.intellij.codeInspection.ex.*; import com.intellij.icons.AllIcons; import com.intellij.ide.CommonActionsManager; import com.intellij.ide.DefaultTreeExpander; import com.intellij.ide.TreeExpander; import com.intellij.ide.ui.search.SearchUtil; import com.intellij.ide.ui.search.SearchableOptionsRegistrar; import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.Splitter; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.profile.ApplicationProfileManager; import com.intellij.profile.DefaultProjectProfileManager; import com.intellij.profile.ProfileManager; import com.intellij.profile.codeInspection.InspectionProfileManager; import com.intellij.profile.codeInspection.InspectionProfileManagerImpl; import com.intellij.profile.codeInspection.InspectionProjectProfileManager; import com.intellij.profile.codeInspection.SeverityProvider; import com.intellij.profile.codeInspection.ui.filter.InspectionFilterAction; import com.intellij.profile.codeInspection.ui.filter.InspectionsFilter; import com.intellij.profile.codeInspection.ui.inspectionsTree.InspectionConfigTreeNode; import com.intellij.profile.codeInspection.ui.inspectionsTree.InspectionsConfigTreeComparator; import com.intellij.profile.codeInspection.ui.inspectionsTree.InspectionsConfigTreeRenderer; import com.intellij.profile.codeInspection.ui.inspectionsTree.InspectionsConfigTreeTable; import com.intellij.profile.codeInspection.ui.table.ScopesAndSeveritiesTable; import com.intellij.psi.search.scope.packageSet.NamedScope; import com.intellij.ui.*; import com.intellij.ui.components.JBLabel; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.Alarm; import com.intellij.util.Function; import com.intellij.util.config.StorageAccessors; import com.intellij.util.containers.*; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; import com.intellij.xml.util.XmlStringUtil; import gnu.trove.THashSet; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.io.IOException; import java.io.StringReader; import java.util.*; import java.util.HashSet; import java.util.List; /** * User: anna * Date: 31-May-2006 */ public class SingleInspectionProfilePanel extends JPanel { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.ex.InspectionToolsPanel"); @NonNls private static final String INSPECTION_FILTER_HISTORY = "INSPECTION_FILTER_HISTORY"; private static final String UNDER_CONSTRUCTION = InspectionsBundle.message("inspection.tool.description.under.construction.text"); private final List<ToolDescriptors> myInitialToolDescriptors = new ArrayList<ToolDescriptors>(); private InspectionProfileImpl mySelectedProfile; private JEditorPane myBrowser; private JPanel myOptionsPanel; private JPanel myInspectionProfilePanel = null; private FilterComponent myProfileFilter; private final InspectionsFilter myInspectionsFilter = new InspectionsFilter() { @Override protected void filterChanged() { filterTree(myProfileFilter.getFilter()); } }; private final InspectionConfigTreeNode myRoot = new InspectionConfigTreeNode(InspectionsBundle.message("inspection.root.node.title")); private final Alarm myAlarm = new Alarm(); private boolean myModified = false; private InspectionsConfigTreeTable myTreeTable; private TreeExpander myTreeExpander; @NotNull private String myInitialProfile; @NonNls private static final String EMPTY_HTML = "<html><body></body></html>"; private boolean myIsInRestore = false; @NonNls private static final String VERTICAL_DIVIDER_PROPORTION = "VERTICAL_DIVIDER_PROPORTION"; @NonNls private static final String HORIZONTAL_DIVIDER_PROPORTION = "HORIZONTAL_DIVIDER_PROPORTION"; private final StorageAccessors myProperties = StorageAccessors.createGlobal("SingleInspectionProfilePanel"); private boolean myShareProfile; private final InspectionProjectProfileManager myProjectProfileManager; private Splitter myRightSplitter; private Splitter myMainSplitter; private String[] myInitialScopesOrder; public SingleInspectionProfilePanel(@NotNull InspectionProjectProfileManager projectProfileManager, @NotNull String inspectionProfileName, @NotNull ModifiableModel profile) { super(new BorderLayout()); myProjectProfileManager = projectProfileManager; mySelectedProfile = (InspectionProfileImpl)profile; myInitialProfile = inspectionProfileName; myShareProfile = profile.getProfileManager() == projectProfileManager; } private static VisibleTreeState getExpandedNodes(InspectionProfileImpl profile) { if (profile.getProfileManager() instanceof ApplicationProfileManager) { return AppInspectionProfilesVisibleTreeState.getInstance().getVisibleTreeState(profile); } else { DefaultProjectProfileManager projectProfileManager = (DefaultProjectProfileManager)profile.getProfileManager(); return ProjectInspectionProfilesVisibleTreeState.getInstance(projectProfileManager.getProject()).getVisibleTreeState(profile); } } private void initUI() { myInspectionProfilePanel = createInspectionProfileSettingsPanel(); add(myInspectionProfilePanel, BorderLayout.CENTER); UserActivityWatcher userActivityWatcher = new UserActivityWatcher(); userActivityWatcher.addUserActivityListener(new UserActivityListener() { @Override public void stateChanged() { //invoke after all other listeners SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (mySelectedProfile == null) return; //panel was disposed updateProperSettingsForSelection(); wereToolSettingsModified(); } }); } }); userActivityWatcher.register(myOptionsPanel); updateSelectedProfileState(); reset(); } private void updateSelectedProfileState() { if (mySelectedProfile == null) return; restoreTreeState(); repaintTableData(); updateSelection(); } public void updateSelection() { if (myTreeTable != null) { final TreePath selectionPath = myTreeTable.getTree().getSelectionPath(); if (selectionPath != null) { TreeUtil.selectNode(myTreeTable.getTree(), (TreeNode) selectionPath.getLastPathComponent()); final int rowForPath = myTreeTable.getTree().getRowForPath(selectionPath); TableUtil.selectRows(myTreeTable, new int[]{rowForPath}); scrollToCenter(); } } } private void wereToolSettingsModified() { for (final ToolDescriptors toolDescriptor : myInitialToolDescriptors) { Descriptor desc = toolDescriptor.getDefaultDescriptor(); if (wereToolSettingsModified(desc)) return; List<Descriptor> descriptors = toolDescriptor.getNonDefaultDescriptors(); for (Descriptor descriptor : descriptors) { if (wereToolSettingsModified(descriptor)) return; } } myModified = false; } private boolean wereToolSettingsModified(Descriptor descriptor) { InspectionToolWrapper toolWrapper = descriptor.getToolWrapper(); if (!mySelectedProfile.isToolEnabled(descriptor.getKey(), descriptor.getScope(), myProjectProfileManager.getProject())) { return false; } Element oldConfig = descriptor.getConfig(); if (oldConfig == null) return false; Element newConfig = Descriptor.createConfigElement(toolWrapper); if (!JDOMUtil.areElementsEqual(oldConfig, newConfig)) { myAlarm.cancelAllRequests(); myAlarm.addRequest(new Runnable() { @Override public void run() { myTreeTable.repaint(); } }, 300); myModified = true; return true; } return false; } private void updateProperSettingsForSelection() { final TreePath selectionPath = myTreeTable.getTree().getSelectionPath(); if (selectionPath != null) { InspectionConfigTreeNode node = (InspectionConfigTreeNode)selectionPath.getLastPathComponent(); final Descriptor descriptor = node.getDefaultDescriptor(); if (descriptor != null) { final boolean properSetting = mySelectedProfile.isProperSetting(descriptor.getKey().toString()); if (node.isProperSetting() != properSetting) { myAlarm.cancelAllRequests(); myAlarm.addRequest(new Runnable() { @Override public void run() { myTreeTable.repaint(); } }, 300); node.dropCache(); updateUpHierarchy(node, (InspectionConfigTreeNode)node.getParent()); } } } } private void initToolStates() { final InspectionProfileImpl profile = mySelectedProfile; if (profile == null) return; myInitialToolDescriptors.clear(); final Project project = myProjectProfileManager.getProject(); for (final ScopeToolState state : profile.getDefaultStates(myProjectProfileManager.getProject())) { if (!accept(state.getTool())) continue; myInitialToolDescriptors.add(ToolDescriptors.fromScopeToolState(state, profile, project)); } myInitialScopesOrder = mySelectedProfile.getScopesOrder(); } protected boolean accept(InspectionToolWrapper entry) { return entry.getDefaultLevel() != HighlightDisplayLevel.NON_SWITCHABLE_ERROR; } private void postProcessModification() { wereToolSettingsModified(); //resetup configs for (ScopeToolState state : mySelectedProfile.getAllTools(myProjectProfileManager.getProject())) { state.resetConfigPanel(); } fillTreeData(myProfileFilter.getFilter(), true); repaintTableData(); updateOptionsAndDescriptionPanel(myTreeTable.getTree().getSelectionPaths()); } @Nullable public static ModifiableModel createNewProfile(final int initValue, ModifiableModel selectedProfile, JPanel parent, String profileName, Set<String> existingProfileNames, @NotNull Project project) { profileName = Messages.showInputDialog(parent, profileName, "Create New Inspection Profile", Messages.getQuestionIcon()); if (profileName == null) return null; final ProfileManager profileManager = selectedProfile.getProfileManager(); if (existingProfileNames.contains(profileName)) { Messages.showErrorDialog(InspectionsBundle.message("inspection.unable.to.create.profile.message", profileName), InspectionsBundle.message("inspection.unable.to.create.profile.dialog.title")); return null; } InspectionProfileImpl inspectionProfile = new InspectionProfileImpl(profileName, InspectionToolRegistrar.getInstance(), profileManager); if (initValue == -1) { inspectionProfile.initInspectionTools(project); ModifiableModel profileModifiableModel = inspectionProfile.getModifiableModel(); final InspectionToolWrapper[] profileEntries = profileModifiableModel.getInspectionTools(null); for (InspectionToolWrapper toolWrapper : profileEntries) { profileModifiableModel.disableTool(toolWrapper.getShortName(), null, project); } profileModifiableModel.setLocal(true); profileModifiableModel.setModified(true); return profileModifiableModel; } else if (initValue == 0) { inspectionProfile.copyFrom(selectedProfile); inspectionProfile.setName(profileName); inspectionProfile.initInspectionTools(project); inspectionProfile.setModified(true); return inspectionProfile; } return null; } public void setFilter(String filter) { myProfileFilter.setFilter(filter); } private void filterTree(@Nullable String filter) { if (myTreeTable != null) { getExpandedNodes(mySelectedProfile).saveVisibleState(myTreeTable.getTree()); fillTreeData(filter, true); reloadModel(); restoreTreeState(); if (myTreeTable.getTree().getSelectionPath() == null) { TreeUtil.selectFirstNode(myTreeTable.getTree()); } } } private void filterTree() { filterTree(myProfileFilter != null ? myProfileFilter.getFilter() : null); } private void reloadModel() { try { myIsInRestore = true; ((DefaultTreeModel)myTreeTable.getTree().getModel()).reload(); } finally { myIsInRestore = false; } } private void restoreTreeState() { try { myIsInRestore = true; getExpandedNodes(mySelectedProfile).restoreVisibleState(myTreeTable.getTree()); } finally { myIsInRestore = false; } } private ActionToolbar createTreeToolbarPanel() { final CommonActionsManager actionManager = CommonActionsManager.getInstance(); DefaultActionGroup actions = new DefaultActionGroup(); actions.add(new InspectionFilterAction(mySelectedProfile, myInspectionsFilter)); actions.addSeparator(); actions.add(actionManager.createExpandAllAction(myTreeExpander, myTreeTable)); actions.add(actionManager.createCollapseAllAction(myTreeExpander, myTreeTable)); actions.add(new AnAction("Reset to Empty", "Reset to empty", AllIcons.Actions.Reset_to_empty){ @Override public void update(AnActionEvent e) { e.getPresentation().setEnabled(mySelectedProfile != null && mySelectedProfile.isExecutable(myProjectProfileManager.getProject())); } @Override public void actionPerformed(AnActionEvent e) { mySelectedProfile.resetToEmpty(e.getProject()); postProcessModification(); } }); actions.add(new AdvancedSettingsAction(myProjectProfileManager.getProject(), myRoot) { @Override protected InspectionProfileImpl getInspectionProfile() { return mySelectedProfile; } @Override protected void postProcessModification() { SingleInspectionProfilePanel.this.postProcessModification(); } }); final ActionToolbar actionToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, actions, true); actionToolbar.setTargetComponent(this); return actionToolbar; } private void repaintTableData() { if (myTreeTable != null) { getExpandedNodes(mySelectedProfile).saveVisibleState(myTreeTable.getTree()); reloadModel(); restoreTreeState(); } } public void selectInspectionTool(String name) { final InspectionConfigTreeNode node = findNodeByKey(name, myRoot); if (node != null) { TreeUtil.selectNode(myTreeTable.getTree(), node); final int rowForPath = myTreeTable.getTree().getRowForPath(new TreePath(node.getPath())); TableUtil.selectRows(myTreeTable, new int[]{rowForPath}); scrollToCenter(); } } private void scrollToCenter() { ListSelectionModel selectionModel = myTreeTable.getSelectionModel(); int maxSelectionIndex = selectionModel.getMaxSelectionIndex(); final int maxColumnSelectionIndex = Math.max(0, myTreeTable.getColumnModel().getSelectionModel().getMinSelectionIndex()); Rectangle maxCellRect = myTreeTable.getCellRect(maxSelectionIndex, maxColumnSelectionIndex, false); final Point selectPoint = maxCellRect.getLocation(); final int allHeight = myTreeTable.getVisibleRect().height; myTreeTable.scrollRectToVisible(new Rectangle(new Point(0, Math.max(0, selectPoint.y - allHeight / 2)), new Dimension(0, allHeight))); } @Nullable private static InspectionConfigTreeNode findNodeByKey(String name, InspectionConfigTreeNode root) { for (int i = 0; i < root.getChildCount(); i++) { final InspectionConfigTreeNode child = (InspectionConfigTreeNode)root.getChildAt(i); final Descriptor descriptor = child.getDefaultDescriptor(); if (descriptor != null) { if (descriptor.getKey().toString().equals(name)) { return child; } } else { final InspectionConfigTreeNode node = findNodeByKey(name, child); if (node != null) return node; } } return null; } private JScrollPane initTreeScrollPane() { fillTreeData(null, true); final InspectionsConfigTreeRenderer renderer = new InspectionsConfigTreeRenderer(){ @Override protected String getFilter() { return myProfileFilter != null ? myProfileFilter.getFilter() : null; } }; myTreeTable = new InspectionsConfigTreeTable(new InspectionsConfigTreeTable.InspectionsConfigTreeTableSettings(myRoot, myProjectProfileManager.getProject()) { @Override protected void onChanged(final InspectionConfigTreeNode node) { updateOptionsAndDescriptionPanel(); updateUpHierarchy(node, (InspectionConfigTreeNode)node.getParent()); } @Override public InspectionProfileImpl getInspectionProfile() { return mySelectedProfile; } }); myTreeTable.setTreeCellRenderer(renderer); myTreeTable.setRootVisible(false); UIUtil.setLineStyleAngled(myTreeTable.getTree()); TreeUtil.installActions(myTreeTable.getTree()); myTreeTable.getTree().addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { if (myTreeTable.getTree().getSelectionPaths() != null) { updateOptionsAndDescriptionPanel(myTreeTable.getTree().getSelectionPaths()); } else { initOptionsAndDescriptionPanel(); } if (!myIsInRestore) { InspectionProfileImpl selected = mySelectedProfile; if (selected != null) { InspectionProfileImpl baseProfile = (InspectionProfileImpl)selected.getParentProfile(); if (baseProfile != null) { getExpandedNodes(baseProfile).setSelectionPaths(myTreeTable.getTree().getSelectionPaths()); } getExpandedNodes(selected).setSelectionPaths(myTreeTable.getTree().getSelectionPaths()); } } } }); myTreeTable.addMouseListener(new PopupHandler() { @Override public void invokePopup(Component comp, int x, int y) { final int[] selectionRows = myTreeTable.getTree().getSelectionRows(); if (selectionRows != null && myTreeTable.getTree().getPathForLocation(x, y) != null && Arrays.binarySearch(selectionRows, myTreeTable.getTree().getRowForLocation(x, y)) > -1) { compoundPopup().show(comp, x, y); } } }); new TreeSpeedSearch(myTreeTable.getTree(), new Convertor<TreePath, String>() { @Override public String convert(TreePath o) { final InspectionConfigTreeNode node = (InspectionConfigTreeNode)o.getLastPathComponent(); final Descriptor descriptor = node.getDefaultDescriptor(); return descriptor != null ? InspectionsConfigTreeComparator.getDisplayTextToSort(descriptor.getText()) : InspectionsConfigTreeComparator .getDisplayTextToSort(node.getGroupName()); } }); final JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myTreeTable); myTreeTable.getTree().setShowsRootHandles(true); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); TreeUtil.collapseAll(myTreeTable.getTree(), 1); myTreeTable.getTree().addTreeExpansionListener(new TreeExpansionListener() { @Override public void treeCollapsed(TreeExpansionEvent event) { InspectionProfileImpl selected = mySelectedProfile; final InspectionConfigTreeNode node = (InspectionConfigTreeNode)event.getPath().getLastPathComponent(); final InspectionProfileImpl parentProfile = (InspectionProfileImpl)selected.getParentProfile(); if (parentProfile != null) { getExpandedNodes(parentProfile).saveVisibleState(myTreeTable.getTree()); } getExpandedNodes(selected).saveVisibleState(myTreeTable.getTree()); } @Override public void treeExpanded(TreeExpansionEvent event) { InspectionProfileImpl selected = mySelectedProfile; if (selected != null) { final InspectionConfigTreeNode node = (InspectionConfigTreeNode)event.getPath().getLastPathComponent(); final InspectionProfileImpl parentProfile = (InspectionProfileImpl)selected.getParentProfile(); if (parentProfile != null) { getExpandedNodes(parentProfile).expandNode(node); } getExpandedNodes(selected).expandNode(node); } } }); myTreeExpander = new DefaultTreeExpander(myTreeTable.getTree()) { @Override public boolean canExpand() { return myTreeTable.isShowing(); } @Override public boolean canCollapse() { return myTreeTable.isShowing(); } }; myProfileFilter = new MyFilterComponent(); return scrollPane; } private JPopupMenu compoundPopup() { final DefaultActionGroup group = new DefaultActionGroup(); final SeverityRegistrar severityRegistrar = ((SeverityProvider)mySelectedProfile.getProfileManager()).getOwnSeverityRegistrar(); TreeSet<HighlightSeverity> severities = new TreeSet<HighlightSeverity>(severityRegistrar); severities.add(HighlightSeverity.ERROR); severities.add(HighlightSeverity.WARNING); severities.add(HighlightSeverity.WEAK_WARNING); final Collection<SeverityRegistrar.SeverityBasedTextAttributes> infoTypes = SeverityUtil.getRegisteredHighlightingInfoTypes(severityRegistrar); for (SeverityRegistrar.SeverityBasedTextAttributes info : infoTypes) { severities.add(info.getSeverity()); } for (HighlightSeverity severity : severities) { final HighlightDisplayLevel level = HighlightDisplayLevel.find(severity); group.add(new AnAction(renderSeverity(severity), renderSeverity(severity), level.getIcon()) { @Override public void actionPerformed(AnActionEvent e) { setNewHighlightingLevel(level); } }); } group.add(Separator.getInstance()); ActionPopupMenu menu = ActionManager.getInstance().createActionPopupMenu(ActionPlaces.UNKNOWN, group); return menu.getComponent(); } public static String renderSeverity(HighlightSeverity severity) { return StringUtil.capitalizeWords(severity.getName().toLowerCase(), true); } private static void updateUpHierarchy(final InspectionConfigTreeNode node, final InspectionConfigTreeNode parent) { if (parent != null) { parent.dropCache(); updateUpHierarchy(parent, (InspectionConfigTreeNode)parent.getParent()); } } private static boolean isDescriptorAccepted(Descriptor descriptor, @NonNls String filter, final boolean forceInclude, final List<Set<String>> keySetList, final Set<String> quoted) { filter = filter.toLowerCase(); if (StringUtil.containsIgnoreCase(descriptor.getText(), filter)) { return true; } final String[] groupPath = descriptor.getGroup(); for (String group : groupPath) { if (StringUtil.containsIgnoreCase(group, filter)) { return true; } } for (String stripped : quoted) { if (StringUtil.containsIgnoreCase(descriptor.getText(),stripped)) { return true; } for (String group : groupPath) { if (StringUtil.containsIgnoreCase(group,stripped)) { return true; } } final String description = descriptor.getToolWrapper().loadDescription(); if (description != null && StringUtil.containsIgnoreCase(description.toLowerCase(), stripped)) { if (!forceInclude) return true; } else if (forceInclude) return false; } for (Set<String> keySet : keySetList) { if (keySet.contains(descriptor.getKey().toString())) { if (!forceInclude) { return true; } } else { if (forceInclude) { return false; } } } return forceInclude; } private void fillTreeData(@Nullable String filter, boolean forceInclude) { if (mySelectedProfile == null) return; myRoot.removeAllChildren(); myRoot.dropCache(); List<Set<String>> keySetList = new ArrayList<Set<String>>(); final Set<String> quoted = new HashSet<String>(); if (filter != null && !filter.isEmpty()) { keySetList.addAll(SearchUtil.findKeys(filter, quoted)); } Project project = myProjectProfileManager.getProject(); final boolean emptyFilter = myInspectionsFilter.isEmptyFilter(); for (ToolDescriptors toolDescriptors : myInitialToolDescriptors) { final Descriptor descriptor = toolDescriptors.getDefaultDescriptor(); if (filter != null && !filter.isEmpty() && !isDescriptorAccepted(descriptor, filter, forceInclude, keySetList, quoted)) { continue; } if (!emptyFilter && !myInspectionsFilter.matches(mySelectedProfile.getTools(toolDescriptors.getDefaultDescriptor().getKey().toString(), project))) { continue; } final InspectionConfigTreeNode node = new InspectionConfigTreeNode(toolDescriptors); getGroupNode(myRoot, toolDescriptors.getDefaultDescriptor().getGroup()).add(node); myRoot.dropCache(); } if (filter != null && forceInclude && myRoot.getChildCount() == 0) { final Set<String> filters = SearchableOptionsRegistrar.getInstance().getProcessedWords(filter); if (filters.size() > 1 || !quoted.isEmpty()) { fillTreeData(filter, false); } } TreeUtil.sort(myRoot, new InspectionsConfigTreeComparator()); } private void updateOptionsAndDescriptionPanel(final TreePath... paths) { if (mySelectedProfile == null || paths == null || paths.length == 0) { return; } final TreePath path = paths[0]; if (path == null) return; final List<InspectionConfigTreeNode> nodes = InspectionsAggregationUtil.getInspectionsNodes(paths); if (!nodes.isEmpty()) { final InspectionConfigTreeNode singleNode = paths.length == 1 && ((InspectionConfigTreeNode)paths[0].getLastPathComponent()).getDefaultDescriptor() != null ? ContainerUtil.getFirstItem(nodes) : null; if (singleNode != null && singleNode.getDefaultDescriptor().loadDescription() != null) { // need this in order to correctly load plugin-supplied descriptions final Descriptor defaultDescriptor = singleNode.getDefaultDescriptor(); final String description = defaultDescriptor.loadDescription(); try { final HintHint hintHint = new HintHint(myBrowser, new Point(0, 0)); hintHint.setFont(myBrowser.getFont()); myBrowser .read(new StringReader(SearchUtil.markup(HintUtil.prepareHintText(description, hintHint), myProfileFilter.getFilter())), null); } catch (IOException e2) { try { //noinspection HardCodedStringLiteral myBrowser.read(new StringReader(XmlStringUtil.wrapInHtml("<b>" + UNDER_CONSTRUCTION + "</b>")), null); } catch (IOException e1) { //Can't be } } catch (Throwable t) { LOG.error("Failed to load description for: " + defaultDescriptor.getToolWrapper().getTool().getClass() + "; description: " + description, t); } } else { try { myBrowser.read(new StringReader("<html><body>Multiple inspections are selected. You can edit them as a single inspection.</body></html>"), null); } catch (IOException e1) { //Can't be } } myOptionsPanel.removeAll(); final Project project = myProjectProfileManager.getProject(); final JPanel severityPanel = new JPanel(new GridBagLayout()); final double severityPanelWeightY; final JPanel configPanelAnchor = new JPanel(new GridLayout()); final Set<String> scopesNames = new THashSet<String>(); for (final InspectionConfigTreeNode node : nodes) { final List<ScopeToolState> nonDefaultTools = mySelectedProfile.getNonDefaultTools(node.getDefaultDescriptor().getKey().toString(), project); for (final ScopeToolState tool : nonDefaultTools) { scopesNames.add(tool.getScopeName()); } } if (scopesNames.isEmpty()) { final LevelChooserAction severityLevelChooser = new LevelChooserAction(mySelectedProfile) { @Override protected void onChosen(final HighlightSeverity severity) { final HighlightDisplayLevel level = HighlightDisplayLevel.find(severity); for (final InspectionConfigTreeNode node : nodes) { final HighlightDisplayKey key = node.getDefaultDescriptor().getKey(); final NamedScope scope = node.getDefaultDescriptor().getScope(); final boolean toUpdate = mySelectedProfile.getErrorLevel(key, scope, project) != level; mySelectedProfile.setErrorLevel(key, level, null, project); if (toUpdate) node.dropCache(); } } }; final HighlightSeverity severity = ScopesAndSeveritiesTable.getSeverity(ContainerUtil.map(nodes, new Function<InspectionConfigTreeNode, ScopeToolState>() { @Override public ScopeToolState fun(InspectionConfigTreeNode node) { return node.getDefaultDescriptor().getState(); } })); severityLevelChooser.setChosen(severity); final ScopesChooser scopesChooser = new ScopesChooser(ContainerUtil.map(nodes, new Function<InspectionConfigTreeNode, Descriptor>() { @Override public Descriptor fun(final InspectionConfigTreeNode node) { return node.getDefaultDescriptor(); } }), mySelectedProfile, project, null) { @Override protected void onScopesOrderChanged() { myTreeTable.getTree().updateUI(); updateOptionsAndDescriptionPanel(); } @Override protected void onScopeAdded() { updateOptionsAndDescriptionPanel(); } }; severityPanel.add(new JLabel(InspectionsBundle.message("inspection.severity")), new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(10, 0, 10, 10), 0, 0)); severityPanel.add(severityLevelChooser.createCustomComponent(severityLevelChooser.getTemplatePresentation()), new GridBagConstraints(1, 0, 1, 1, 1.0, 0, GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(10, 0, 10, 0), 0, 0)); severityPanel.add(scopesChooser.createCustomComponent(scopesChooser.getTemplatePresentation()), new GridBagConstraints(2, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(10, 0, 10, 0), 0, 0)); severityPanelWeightY = 0.0; if (singleNode != null) { setConfigPanel(configPanelAnchor, mySelectedProfile.getToolDefaultState(singleNode.getDefaultDescriptor().getKey().toString(), project)); } } else { if (singleNode != null) { for (final Descriptor descriptor : singleNode.getDescriptors().getNonDefaultDescriptors()) { descriptor.loadConfig(); } } final JTable scopesAndScopesAndSeveritiesTable = new ScopesAndSeveritiesTable(new ScopesAndSeveritiesTable.TableSettings(nodes, mySelectedProfile, myTreeTable, project) { @Override protected void onScopeChosen(@NotNull final ScopeToolState state) { setConfigPanel(configPanelAnchor, state); configPanelAnchor.revalidate(); configPanelAnchor.repaint(); } @Override protected void onSettingsChanged() { myTreeTable.getTree().updateUI(); } @Override protected void onScopeAdded() { updateOptionsAndDescriptionPanel(); } @Override protected void onScopesOrderChanged() { myTreeTable.getTree().updateUI(); updateOptionsAndDescriptionPanel(); } @Override protected void onScopeRemoved(final int scopesCount) { if (scopesCount == 1) { updateOptionsAndDescriptionPanel(); } } }); final ToolbarDecorator wrappedTable = ToolbarDecorator.createDecorator(scopesAndScopesAndSeveritiesTable).disableUpDownActions(); final JPanel panel = wrappedTable.createPanel(); panel.setMinimumSize(new Dimension(getMinimumSize().width, 3 * scopesAndScopesAndSeveritiesTable.getRowHeight())); severityPanel.add(new JBLabel("Scopes & Severities"), new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 0, 2, 10), 0, 0)); severityPanel.add(new JBLabel("Add scope to change its settings", UIUtil.ComponentStyle.SMALL), new GridBagConstraints(1, 0, 1, 1, 1.0, 0, GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(5, 0, 2, 0), 0, 0)); severityPanel.add(panel, new GridBagConstraints(0, 1, 2, 1, 0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); severityPanelWeightY = 0.3; } myOptionsPanel.add(severityPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, severityPanelWeightY, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); if (configPanelAnchor.getComponentCount() != 0) { configPanelAnchor.setBorder(IdeBorderFactory.createTitledBorder("Options", false, new Insets(0, 0, 0, 0))); } if (configPanelAnchor.getComponentCount() != 0 || scopesNames.isEmpty()) { myOptionsPanel.add(configPanelAnchor, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); } myOptionsPanel.revalidate(); GuiUtils.enableChildren(myOptionsPanel, isThoughOneNodeEnabled(nodes)); } else { initOptionsAndDescriptionPanel(); } myOptionsPanel.repaint(); } private boolean isThoughOneNodeEnabled(final List<InspectionConfigTreeNode> nodes) { final Project project = myProjectProfileManager.getProject(); for (final InspectionConfigTreeNode node : nodes) { final String toolId = node.getDefaultDescriptor().getKey().toString(); if (mySelectedProfile.getTools(toolId, project).isEnabled()) { return true; } } return false; } private void updateOptionsAndDescriptionPanel() { final TreePath[] paths = myTreeTable.getTree().getSelectionPaths(); if (paths != null) { updateOptionsAndDescriptionPanel(paths); } else { initOptionsAndDescriptionPanel(); } } private void initOptionsAndDescriptionPanel() { myOptionsPanel.removeAll(); try { myBrowser.read(new StringReader(EMPTY_HTML), null); } catch (IOException e1) { //Can't be } myOptionsPanel.validate(); myOptionsPanel.repaint(); } private static void setConfigPanel(final JPanel configPanelAnchor, final ScopeToolState state) { configPanelAnchor.removeAll(); final JComponent additionalConfigPanel = state.getAdditionalConfigPanel(); if (additionalConfigPanel != null) { configPanelAnchor.add(ScrollPaneFactory.createScrollPane(additionalConfigPanel, SideBorder.NONE)); } } private static InspectionConfigTreeNode getGroupNode(InspectionConfigTreeNode root, String[] groupPath) { InspectionConfigTreeNode currentRoot = root; for (final String group : groupPath) { currentRoot = getGroupNode(currentRoot, group); } return currentRoot; } private static InspectionConfigTreeNode getGroupNode(InspectionConfigTreeNode root, String group) { final int childCount = root.getChildCount(); for (int i = 0; i < childCount; i++) { InspectionConfigTreeNode child = (InspectionConfigTreeNode)root.getChildAt(i); if (group.equals(child.getUserObject())) { return child; } } InspectionConfigTreeNode child = new InspectionConfigTreeNode(group); root.add(child); return child; } public boolean setSelectedProfileModified(boolean modified) { mySelectedProfile.setModified(modified); return modified; } ModifiableModel getSelectedProfile() { return mySelectedProfile; } private void setSelectedProfile(final ModifiableModel modifiableModel) { if (mySelectedProfile == modifiableModel) return; mySelectedProfile = (InspectionProfileImpl)modifiableModel; if (mySelectedProfile != null) { myInitialProfile = mySelectedProfile.getName(); } initToolStates(); filterTree(); } @Override public Dimension getPreferredSize() { return new Dimension(700, 500); } public void disposeUI() { if (myInspectionProfilePanel == null) { return; } myProperties.setFloat(VERTICAL_DIVIDER_PROPORTION, myMainSplitter.getProportion()); myProperties.setFloat(HORIZONTAL_DIVIDER_PROPORTION, myRightSplitter.getProportion()); myAlarm.cancelAllRequests(); myProfileFilter.dispose(); if (mySelectedProfile != null) { for (ScopeToolState state : mySelectedProfile.getAllTools(myProjectProfileManager.getProject())) { state.resetConfigPanel(); } } mySelectedProfile = null; } private JPanel createInspectionProfileSettingsPanel() { myBrowser = new JEditorPane(UIUtil.HTML_MIME, EMPTY_HTML); myBrowser.setEditable(false); myBrowser.setBorder(IdeBorderFactory.createEmptyBorder(5, 5, 5, 5)); myBrowser.addHyperlinkListener(new BrowserHyperlinkListener()); initToolStates(); fillTreeData(myProfileFilter != null ? myProfileFilter.getFilter() : null, true); JPanel descriptionPanel = new JPanel(new BorderLayout()); descriptionPanel.setBorder(IdeBorderFactory.createTitledBorder(InspectionsBundle.message("inspection.description.title"), false, new Insets(13, 0, 0, 0))); descriptionPanel.add(ScrollPaneFactory.createScrollPane(myBrowser), BorderLayout.CENTER); myRightSplitter = new Splitter(true); myRightSplitter.setFirstComponent(descriptionPanel); myRightSplitter.setProportion(myProperties.getFloat(HORIZONTAL_DIVIDER_PROPORTION, 0.5f)); myOptionsPanel = new JPanel(new GridBagLayout()); initOptionsAndDescriptionPanel(); myRightSplitter.setSecondComponent(myOptionsPanel); myRightSplitter.setHonorComponentsMinimumSize(true); final JPanel treePanel = new JPanel(new BorderLayout()); final JScrollPane tree = initTreeScrollPane(); treePanel.add(tree, BorderLayout.CENTER); final JPanel northPanel = new JPanel(new GridBagLayout()); northPanel.setBorder(IdeBorderFactory.createEmptyBorder(2, 0, 2, 0)); northPanel.add(myProfileFilter, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.BASELINE_TRAILING, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); northPanel.add(createTreeToolbarPanel().getComponent(), new GridBagConstraints(1, 0, 1, 1, 0.5, 1, GridBagConstraints.BASELINE_LEADING, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); treePanel.add(northPanel, BorderLayout.NORTH); myMainSplitter = new Splitter(false); myMainSplitter.setFirstComponent(treePanel); myMainSplitter.setSecondComponent(myRightSplitter); myMainSplitter.setHonorComponentsMinimumSize(false); myMainSplitter.setProportion(myProperties.getFloat(VERTICAL_DIVIDER_PROPORTION, 0.5f)); final JPanel panel = new JPanel(new BorderLayout()); panel.add(myMainSplitter, BorderLayout.CENTER); return panel; } public boolean isModified() { if (myModified) return true; if (mySelectedProfile.isChanged()) return true; if (myShareProfile != (mySelectedProfile.getProfileManager() == myProjectProfileManager)) return true; if (!Comparing.strEqual(myInitialProfile, mySelectedProfile.getName())) return true; if (!Comparing.equal(myInitialScopesOrder, mySelectedProfile.getScopesOrder())) return true; if (descriptorsAreChanged()) { return true; } return false; } public void reset() { myModified = false; setSelectedProfile(mySelectedProfile); final String filter = myProfileFilter.getFilter(); myProfileFilter.reset(); myProfileFilter.setSelectedItem(filter); myShareProfile = mySelectedProfile.getProfileManager() == myProjectProfileManager; } public void apply() throws ConfigurationException { final boolean modified = isModified(); if (!modified) { return; } final ModifiableModel selectedProfile = getSelectedProfile(); final ProfileManager profileManager = myShareProfile ? myProjectProfileManager : InspectionProfileManager.getInstance(); selectedProfile.setLocal(!myShareProfile); if (selectedProfile.getProfileManager() != profileManager) { if (selectedProfile.getProfileManager().getProfile(selectedProfile.getName(), false) != null) { selectedProfile.getProfileManager().deleteProfile(selectedProfile.getName()); } copyUsedSeveritiesIfUndefined(selectedProfile, profileManager); selectedProfile.setProfileManager(profileManager); } final InspectionProfile parentProfile = selectedProfile.getParentProfile(); if (((InspectionProfileManagerImpl)InspectionProfileManager.getInstance()).getSchemesManager().isShared(selectedProfile)) { if (descriptorsAreChanged()) { throw new ConfigurationException("Shared profile cannot be modified. Please do \"Save As...\" first."); } } try { selectedProfile.commit(); } catch (IOException e) { throw new ConfigurationException(e.getMessage()); } setSelectedProfile(parentProfile.getModifiableModel()); setSelectedProfileModified(false); myModified = false; } private static void copyUsedSeveritiesIfUndefined(final ModifiableModel selectedProfile, final ProfileManager profileManager) { final SeverityRegistrar registrar = ((SeverityProvider)profileManager).getSeverityRegistrar(); final Set<HighlightSeverity> severities = ((InspectionProfileImpl)selectedProfile).getUsedSeverities(); for (Iterator<HighlightSeverity> iterator = severities.iterator(); iterator.hasNext();) { HighlightSeverity severity = iterator.next(); if (registrar.isSeverityValid(severity.getName())) { iterator.remove(); } } if (!severities.isEmpty()) { final SeverityRegistrar oppositeRegister = ((SeverityProvider)selectedProfile.getProfileManager()).getSeverityRegistrar(); for (HighlightSeverity severity : severities) { final TextAttributesKey attributesKey = TextAttributesKey.find(severity.getName()); final TextAttributes textAttributes = oppositeRegister.getTextAttributesBySeverity(severity); LOG.assertTrue(textAttributes != null, severity); HighlightInfoType.HighlightInfoTypeImpl info = new HighlightInfoType.HighlightInfoTypeImpl(severity, attributesKey); registrar.registerSeverity(new SeverityRegistrar.SeverityBasedTextAttributes(textAttributes.clone(), info), textAttributes.getErrorStripeColor()); } } } private boolean descriptorsAreChanged() { for (ToolDescriptors toolDescriptors : myInitialToolDescriptors) { Descriptor desc = toolDescriptors.getDefaultDescriptor(); Project project = myProjectProfileManager.getProject(); if (mySelectedProfile.isToolEnabled(desc.getKey(), null, project) != desc.isEnabled()){ return true; } if (mySelectedProfile.getErrorLevel(desc.getKey(), desc.getScope(), project) != desc.getLevel()) { return true; } final List<Descriptor> descriptors = toolDescriptors.getNonDefaultDescriptors(); for (Descriptor descriptor : descriptors) { if (mySelectedProfile.isToolEnabled(descriptor.getKey(), descriptor.getScope(), project) != descriptor.isEnabled()) { return true; } if (mySelectedProfile.getErrorLevel(descriptor.getKey(), descriptor.getScope(), project) != descriptor.getLevel()) { return true; } } final List<ScopeToolState> tools = mySelectedProfile.getNonDefaultTools(desc.getKey().toString(), project); if (tools.size() != descriptors.size()) { return true; } for (int i = 0; i < tools.size(); i++) { final ScopeToolState pair = tools.get(i); if (!Comparing.equal(pair.getScope(project), descriptors.get(i).getScope())) { return true; } } } return false; } public boolean isProfileShared() { return myShareProfile; } public void setProfileShared(boolean profileShared) { myShareProfile = profileShared; } @Override public void setVisible(boolean aFlag) { if (aFlag && myInspectionProfilePanel == null) { initUI(); } super.setVisible(aFlag); } private void setNewHighlightingLevel(@NotNull HighlightDisplayLevel level) { final int[] rows = myTreeTable.getTree().getSelectionRows(); final boolean showOptionsAndDescriptorPanels = rows != null && rows.length == 1; for (int i = 0; rows != null && i < rows.length; i++) { final InspectionConfigTreeNode node = (InspectionConfigTreeNode)myTreeTable.getTree().getPathForRow(rows[i]).getLastPathComponent(); final InspectionConfigTreeNode parent = (InspectionConfigTreeNode)node.getParent(); final Object userObject = node.getUserObject(); if (userObject instanceof ToolDescriptors && (node.getScopeName() != null || node.isLeaf())) { updateErrorLevel(node, showOptionsAndDescriptorPanels, level); updateUpHierarchy(node, parent); } else { updateErrorLevelUpInHierarchy(level, showOptionsAndDescriptorPanels, node); updateUpHierarchy(node, parent); } } if (rows != null) { updateOptionsAndDescriptionPanel(myTreeTable.getTree().getSelectionPaths()); } else { initOptionsAndDescriptionPanel(); } repaintTableData(); } private void updateErrorLevelUpInHierarchy(@NotNull HighlightDisplayLevel level, boolean showOptionsAndDescriptorPanels, InspectionConfigTreeNode node) { node.dropCache(); for (int j = 0; j < node.getChildCount(); j++) { final InspectionConfigTreeNode child = (InspectionConfigTreeNode)node.getChildAt(j); final Object userObject = child.getUserObject(); if (userObject instanceof ToolDescriptors && (child.getScopeName() != null || child.isLeaf())) { updateErrorLevel(child, showOptionsAndDescriptorPanels, level); } else { updateErrorLevelUpInHierarchy(level, showOptionsAndDescriptorPanels, child); } } } private void updateErrorLevel(final InspectionConfigTreeNode child, final boolean showOptionsAndDescriptorPanels, @NotNull HighlightDisplayLevel level) { final HighlightDisplayKey key = child.getDefaultDescriptor().getKey(); mySelectedProfile.setErrorLevel(key, level, null, myProjectProfileManager.getProject()); child.dropCache(); if (showOptionsAndDescriptorPanels) { updateOptionsAndDescriptionPanel(new TreePath(child.getPath())); } } public JComponent getTree() { return myTreeTable.getTree(); } private class MyFilterComponent extends FilterComponent { private MyFilterComponent() { super(INSPECTION_FILTER_HISTORY, 10); setHistory(Arrays.asList("\"New in 13\"")); } @Override public void filter() { filterTree(getFilter()); } @Override protected void onlineFilter() { if (mySelectedProfile == null) return; final String filter = getFilter(); getExpandedNodes(mySelectedProfile).saveVisibleState(myTreeTable.getTree()); fillTreeData(filter, true); reloadModel(); if (filter == null || filter.isEmpty()) { restoreTreeState(); } else { TreeUtil.expandAll(myTreeTable.getTree()); } } } }
NPE in SingleInspectionProfilePanel#getTree() (table not initialized case)
platform/lang-impl/src/com/intellij/profile/codeInspection/ui/SingleInspectionProfilePanel.java
NPE in SingleInspectionProfilePanel#getTree() (table not initialized case)
<ide><path>latform/lang-impl/src/com/intellij/profile/codeInspection/ui/SingleInspectionProfilePanel.java <ide> } <ide> <ide> public JComponent getTree() { <del> return myTreeTable.getTree(); <add> return myTreeTable == null ? null : myTreeTable.getTree(); <ide> } <ide> <ide> private class MyFilterComponent extends FilterComponent {
JavaScript
agpl-3.0
103c8e8a62983c4d4bbf54c86230f4ff0b51bebe
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
13c7fa2a-2e63-11e5-9284-b827eb9e62be
helloWorld.js
13c278ac-2e63-11e5-9284-b827eb9e62be
13c7fa2a-2e63-11e5-9284-b827eb9e62be
helloWorld.js
13c7fa2a-2e63-11e5-9284-b827eb9e62be
<ide><path>elloWorld.js <del>13c278ac-2e63-11e5-9284-b827eb9e62be <add>13c7fa2a-2e63-11e5-9284-b827eb9e62be
Java
agpl-3.0
da4b6fea824ad5a82638a96ccc2772d8cd52148f
0
elki-project/elki,elki-project/elki,elki-project/elki
package de.lmu.ifi.dbs.distance; import java.util.regex.Pattern; /** * Abstract Distance Function provides some methods valid for any extending class. * * @author Arthur Zimek (<a href="mailto:[email protected]">[email protected]</a>) */ public abstract class AbstractDistanceFunction implements DistanceFunction { /** * A pattern to define the required input format. */ private Pattern pattern; /** * Provides an abstract DistanceFunction based on the given Pattern. * * @param pattern a pattern to define the required input format */ protected AbstractDistanceFunction(Pattern pattern) { this.pattern = pattern; } /** * @see de.lmu.ifi.dbs.distance.DistanceFunction#isInfiniteDistance(de.lmu.ifi.dbs.distance.Distance) */ public boolean isInfiniteDistance(Distance distance) { return distance.equals(infiniteDistance()); } /** * @see de.lmu.ifi.dbs.distance.DistanceFunction#isNullDistance(de.lmu.ifi.dbs.distance.Distance) */ public boolean isNullDistance(Distance distance) { return distance.equals(nullDistance()); } /** * @see de.lmu.ifi.dbs.distance.DistanceFunction#isUndefinedDistance(de.lmu.ifi.dbs.distance.Distance) */ public boolean isUndefinedDistance(Distance distance) { return distance.equals(undefinedDistance()); } /** * @see de.lmu.ifi.dbs.distance.DistanceFunction#requiredInputPattern() */ public String requiredInputPattern() { return this.pattern.pattern(); } /** * Returns true if the given pattern matches the defined pattern, false otherwise. * * @param pattern the pattern to be matched woth the defined pattern * @return true if the given pattern matches the defined pattern, false otherwise */ protected boolean matches(String pattern) { return this.pattern.matcher(pattern).matches(); } }
src/de/lmu/ifi/dbs/distance/AbstractDistanceFunction.java
package de.lmu.ifi.dbs.distance; import de.lmu.ifi.dbs.database.Database; import java.util.regex.Pattern; /** * Abstract Distance Function provides some methods valid for any extending class. * * @author Arthur Zimek (<a href="mailto:[email protected]">[email protected]</a>) */ public abstract class AbstractDistanceFunction implements DistanceFunction { /** * A pattern to define the required input format. */ private Pattern pattern; /** * Provides an abstract DistanceFunction based on the given Pattern. * * @param pattern a pattern to define the required input format */ protected AbstractDistanceFunction(Pattern pattern) { this.pattern = pattern; } /** * @see de.lmu.ifi.dbs.distance.DistanceFunction#isInfiniteDistance(de.lmu.ifi.dbs.distance.Distance) */ public boolean isInfiniteDistance(Distance distance) { return distance.equals(infiniteDistance()); } /** * @see de.lmu.ifi.dbs.distance.DistanceFunction#isNullDistance(de.lmu.ifi.dbs.distance.Distance) */ public boolean isNullDistance(Distance distance) { return distance.equals(nullDistance()); } /** * @see de.lmu.ifi.dbs.distance.DistanceFunction#isUndefinedDistance(de.lmu.ifi.dbs.distance.Distance) */ public boolean isUndefinedDistance(Distance distance) { return distance.equals(undefinedDistance()); } /** * @see de.lmu.ifi.dbs.distance.DistanceFunction#requiredInputPattern() */ public String requiredInputPattern() { return this.pattern.pattern(); } /** * Returns true if the given pattern matches the defined pattern, false otherwise. * * @param pattern the pattern to be matched woth the defined pattern * @return true if the given pattern matches the defined pattern, false otherwise */ protected boolean matches(String pattern) { return this.pattern.matcher(pattern).matches(); } }
cleared import statements
src/de/lmu/ifi/dbs/distance/AbstractDistanceFunction.java
cleared import statements
<ide><path>rc/de/lmu/ifi/dbs/distance/AbstractDistanceFunction.java <ide> package de.lmu.ifi.dbs.distance; <del> <del>import de.lmu.ifi.dbs.database.Database; <ide> <ide> import java.util.regex.Pattern; <ide>
Java
mit
40129eba89560f13fe9a3c8c824576277eece992
0
Clemens85/runningdinner,Clemens85/runningdinner,Clemens85/runningdinner,Clemens85/runningdinner,Clemens85/runningdinner
package org.runningdinner.frontend; import static org.assertj.core.api.Assertions.assertThat; import java.time.LocalDate; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.runningdinner.admin.RunningDinnerService; import org.runningdinner.admin.rest.BasicSettingsTO; import org.runningdinner.common.IssueKeys; import org.runningdinner.common.exception.DinnerNotFoundException; import org.runningdinner.common.exception.ValidationException; import org.runningdinner.core.RegistrationType; import org.runningdinner.core.RunningDinner; import org.runningdinner.frontend.rest.RegistrationDataV2TO; import org.runningdinner.participant.Participant; import org.runningdinner.participant.ParticipantAddress; import org.runningdinner.test.util.ApplicationTest; import org.runningdinner.test.util.TestHelperService; import org.runningdinner.test.util.TestUtil; import org.runningdinner.wizard.BasicDetailsTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ApplicationTest public class FrontendRunningDinnerTest { @Autowired private FrontendRunningDinnerService frontendRunningDinnerService; @Autowired private RunningDinnerService runningDinnerService; @Autowired private TestHelperService testHelperService; private LocalDate todayIn30Days; private RunningDinner runningDinner; private String publicDinnerId; @Before public void setUp() { todayIn30Days = LocalDate.now().plusDays(30); runningDinner = testHelperService.createPublicRunningDinner(todayIn30Days, 2); publicDinnerId = runningDinner.getPublicSettings().getPublicId(); } @Test public void testFindRunningDinnerByPublicId() { RunningDinner foundRunningDinner = frontendRunningDinnerService.findRunningDinnerByPublicId(runningDinner.getPublicSettings().getPublicId(), LocalDate.now()); assertThat(foundRunningDinner).isNotNull(); assertThat(foundRunningDinner.getPublicSettings().getPublicId()).isEqualTo(runningDinner.getPublicSettings().getPublicId()); } @Test(expected = DinnerNotFoundException.class) public void testFindRunningDinnerByPublicIdFailsForClosedRegistration() { BasicSettingsTO basicSettings = TestUtil.newBasicSettings(new BasicDetailsTO(runningDinner)); basicSettings.getBasicDetails().setRegistrationType(RegistrationType.CLOSED); runningDinnerService.updateBasicSettings(runningDinner.getAdminId(), basicSettings); frontendRunningDinnerService.findRunningDinnerByPublicId(runningDinner.getPublicSettings().getPublicId(), LocalDate.now()); } @Test public void testRegistrationValidationSuccessful() { RegistrationDataV2TO registrationData = TestUtil.createRegistrationData("Max Mustermann", "[email protected]", ParticipantAddress.parseFromCommaSeparatedString("Musterstraße 1, 47111 Musterstadt"), 6); RegistrationSummary result = frontendRunningDinnerService.performRegistration(publicDinnerId, registrationData, true); assertThat(result).isNotNull(); } @Test public void testRegistrationInvalidName() { RegistrationDataV2TO registrationData = TestUtil.createRegistrationData("Max Mustermann", "[email protected]", ParticipantAddress.parseFromCommaSeparatedString("Musterstraße 1, 47111 Musterstadt"), 6); registrationData.setFirstnamePart(null); registrationData.setLastname("Mustermann"); try { frontendRunningDinnerService.performRegistration(publicDinnerId, registrationData, true); Assert.fail("Expected ValidationException to be thrown"); } catch (IllegalArgumentException expectedEx) { // NOP // assertThat(expectedEx.getIssues().getIssues().get(0).getMessage()).isEqualTo(IssueKeys.FULLNAME_NOT_VALID); } } @Test public void testRegistrationInvalidRegistrationDate() { // set end of registration date back to day before yesterday LocalDate tomorrow = LocalDate.now().plusDays(1); runningDinner = testHelperService.createPublicRunningDinner(tomorrow, 2); RegistrationDataV2TO registrationData = TestUtil.createRegistrationData("Max Mustermann", "[email protected]", ParticipantAddress.parseFromCommaSeparatedString("Musterstraße 1, 47111 Musterstadt"), 6); try { frontendRunningDinnerService.performRegistration(runningDinner.getPublicSettings().getPublicId(), registrationData, true); Assert.fail("Expected ValidationException to be thrown"); } catch (ValidationException expectedEx) { assertThat(expectedEx.getIssues().getIssues().get(0).getMessage()).isEqualTo(IssueKeys.REGISTRATION_DATE_EXPIRED); } } @Test public void testRegistrationSuccess() { RegistrationDataV2TO registrationData = TestUtil.createRegistrationData("Max Mustermann", "[email protected]", ParticipantAddress.parseFromCommaSeparatedString("Musterstraße 1, 47111 Musterstadt"), 6); RegistrationSummary firstParticipant = frontendRunningDinnerService.performRegistration(publicDinnerId, registrationData, false); checkRegistrationSummary(firstParticipant, 1); registrationData = TestUtil.createRegistrationData("Maria Musterfrau", "[email protected]", ParticipantAddress.parseFromCommaSeparatedString("Musterweg 10, 47112 Musterstadt"), 2); RegistrationSummary secondParticipant = frontendRunningDinnerService.performRegistration(publicDinnerId, registrationData, false); checkRegistrationSummary(secondParticipant, 2); registrationData = TestUtil.createRegistrationData("Third Participant", "[email protected]", ParticipantAddress.parseFromCommaSeparatedString("Musterweg 10, 47112 Musterstadt"), 2); RegistrationSummary thirdParticipant = frontendRunningDinnerService.performRegistration(publicDinnerId, registrationData, false); checkRegistrationSummary(thirdParticipant, 3); } protected void checkRegistrationSummary(RegistrationSummary registrationSummary, int expectedParticipantNumber) { Participant participant = registrationSummary.getParticipant(); assertThat(participant).isNotNull(); assertThat(participant.getParticipantNumber()).isEqualTo(expectedParticipantNumber); assertThat(participant.isNew()).isFalse(); } @Test public void testDuplicatedRegistration() { RegistrationDataV2TO registrationData = TestUtil.createRegistrationData("Max Mustermann", "[email protected]", ParticipantAddress.parseFromCommaSeparatedString("Musterstraße 1, 47111 Musterstadt"), 6); RegistrationSummary firstParticipant = frontendRunningDinnerService.performRegistration(publicDinnerId, registrationData, false); checkRegistrationSummary(firstParticipant, 1); try { frontendRunningDinnerService.performRegistration(publicDinnerId, registrationData, false); Assert.fail("Expected ValidationException to be thrown"); } catch (ValidationException ex) { assertThat(ex.getIssues().getIssues().get(0).getMessage()).isEqualTo(IssueKeys.PARTICIPANT_ALREADY_REGISTERED); } } @Test public void testFindPublicRunningDinnersSimple() { LocalDate todayIn29Days = todayIn30Days.minusDays(1); List<RunningDinner> publicRunningDinners = frontendRunningDinnerService.findPublicRunningDinners(todayIn29Days); assertDinnerFound(publicRunningDinners); } @Test public void testFindPublicDinnersSeveral() { LocalDate now = LocalDate.now(); LocalDate todayIn35Days = now.plusDays(35); LocalDate todayIn40Days = now.plusDays(40); LocalDate todayIn41Days = now.plusDays(41); RunningDinner firstPublicDinner = testHelperService.createPublicRunningDinner(todayIn40Days, 3); RunningDinner secondPublicDinner = testHelperService.createPublicRunningDinner(todayIn41Days, 3); RunningDinner closedRunningDinner = testHelperService.createPublicRunningDinner(todayIn40Days, 3, RegistrationType.OPEN); List<RunningDinner> publicRunningDinners = frontendRunningDinnerService.findPublicRunningDinners(todayIn35Days); assertThat(publicRunningDinners).contains(firstPublicDinner, secondPublicDinner); assertThat(publicRunningDinners).doesNotContain(closedRunningDinner); } @Test public void cancelledDinnerNotFound() { LocalDate todayIn29Days = todayIn30Days.minusDays(1); List<RunningDinner> publicRunningDinners = frontendRunningDinnerService.findPublicRunningDinners(todayIn29Days); assertDinnerFound(publicRunningDinners); runningDinnerService.cancelRunningDinner(runningDinner.getAdminId(), todayIn29Days.atTime(10, 10)); publicRunningDinners = frontendRunningDinnerService.findPublicRunningDinners(todayIn29Days); assertDinnerNotFound(publicRunningDinners); } private void assertDinnerFound(List<RunningDinner> publicRunningDinners) { Set<String> publicIds = publicRunningDinners.stream().map(p -> p.getPublicSettings().getPublicId()).collect(Collectors.toSet()); assertThat(publicIds).contains(runningDinner.getPublicSettings().getPublicId()); } private void assertDinnerNotFound(List<RunningDinner> publicRunningDinners) { Set<String> publicIds = publicRunningDinners.stream().map(p -> p.getPublicSettings().getPublicId()).collect(Collectors.toSet()); assertThat(publicIds).doesNotContain(runningDinner.getPublicSettings().getPublicId()); } }
runningdinner-backend/src/test/java/org/runningdinner/frontend/FrontendRunningDinnerTest.java
package org.runningdinner.frontend; import static org.assertj.core.api.Assertions.assertThat; import java.time.LocalDate; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.runningdinner.admin.RunningDinnerService; import org.runningdinner.admin.rest.BasicSettingsTO; import org.runningdinner.common.IssueKeys; import org.runningdinner.common.exception.DinnerNotFoundException; import org.runningdinner.common.exception.ValidationException; import org.runningdinner.core.RegistrationType; import org.runningdinner.core.RunningDinner; import org.runningdinner.frontend.rest.RegistrationDataV2TO; import org.runningdinner.participant.Participant; import org.runningdinner.participant.ParticipantAddress; import org.runningdinner.test.util.ApplicationTest; import org.runningdinner.test.util.TestHelperService; import org.runningdinner.test.util.TestUtil; import org.runningdinner.wizard.BasicDetailsTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ApplicationTest public class FrontendRunningDinnerTest { @Autowired private FrontendRunningDinnerService frontendRunningDinnerService; @Autowired private RunningDinnerService runningDinnerService; @Autowired private TestHelperService testHelperService; private LocalDate todayIn30Days; private RunningDinner runningDinner; private String publicDinnerId; @Before public void setUp() { todayIn30Days = LocalDate.now().plusDays(30); runningDinner = testHelperService.createPublicRunningDinner(todayIn30Days, 2); publicDinnerId = runningDinner.getPublicSettings().getPublicId(); } @Test public void testFindRunningDinnerByPublicId() { RunningDinner foundRunningDinner = frontendRunningDinnerService.findRunningDinnerByPublicId(runningDinner.getPublicSettings().getPublicId(), LocalDate.now()); assertThat(foundRunningDinner).isNotNull(); assertThat(foundRunningDinner.getPublicSettings().getPublicId()).isEqualTo(runningDinner.getPublicSettings().getPublicId()); } @Test(expected = DinnerNotFoundException.class) public void testFindRunningDinnerByPublicIdFailsForClosedRegistration() { BasicSettingsTO basicSettings = TestUtil.newBasicSettings(new BasicDetailsTO(runningDinner)); basicSettings.getBasicDetails().setRegistrationType(RegistrationType.CLOSED); runningDinnerService.updateBasicSettings(runningDinner.getAdminId(), basicSettings); frontendRunningDinnerService.findRunningDinnerByPublicId(runningDinner.getPublicSettings().getPublicId(), LocalDate.now()); } @Test public void testRegistrationValidationSuccessful() { RegistrationDataV2TO registrationData = TestUtil.createRegistrationData("Max Mustermann", "[email protected]", ParticipantAddress.parseFromCommaSeparatedString("Musterstraße 1, 47111 Musterstadt"), 6); RegistrationSummary result = frontendRunningDinnerService.performRegistration(publicDinnerId, registrationData, true); assertThat(result).isNotNull(); } @Test public void testRegistrationInvalidName() { RegistrationDataV2TO registrationData = TestUtil.createRegistrationData("Mustermann", "[email protected]", ParticipantAddress.parseFromCommaSeparatedString("Musterstraße 1, 47111 Musterstadt"), 6); try { frontendRunningDinnerService.performRegistration(publicDinnerId, registrationData, true); Assert.fail("Expected ValidationException to be thrown"); } catch (ValidationException expectedEx) { assertThat(expectedEx.getIssues().getIssues().get(0).getMessage()).isEqualTo(IssueKeys.FULLNAME_NOT_VALID); } } @Test public void testRegistrationInvalidRegistrationDate() { // set end of registration date back to day before yesterday LocalDate tomorrow = LocalDate.now().plusDays(1); runningDinner = testHelperService.createPublicRunningDinner(tomorrow, 2); RegistrationDataV2TO registrationData = TestUtil.createRegistrationData("Max Mustermann", "[email protected]", ParticipantAddress.parseFromCommaSeparatedString("Musterstraße 1, 47111 Musterstadt"), 6); try { frontendRunningDinnerService.performRegistration(runningDinner.getPublicSettings().getPublicId(), registrationData, true); Assert.fail("Expected ValidationException to be thrown"); } catch (ValidationException expectedEx) { assertThat(expectedEx.getIssues().getIssues().get(0).getMessage()).isEqualTo(IssueKeys.REGISTRATION_DATE_EXPIRED); } } @Test public void testRegistrationSuccess() { RegistrationDataV2TO registrationData = TestUtil.createRegistrationData("Max Mustermann", "[email protected]", ParticipantAddress.parseFromCommaSeparatedString("Musterstraße 1, 47111 Musterstadt"), 6); RegistrationSummary firstParticipant = frontendRunningDinnerService.performRegistration(publicDinnerId, registrationData, false); checkRegistrationSummary(firstParticipant, 1); registrationData = TestUtil.createRegistrationData("Maria Musterfrau", "[email protected]", ParticipantAddress.parseFromCommaSeparatedString("Musterweg 10, 47112 Musterstadt"), 2); RegistrationSummary secondParticipant = frontendRunningDinnerService.performRegistration(publicDinnerId, registrationData, false); checkRegistrationSummary(secondParticipant, 2); registrationData = TestUtil.createRegistrationData("Third Participant", "[email protected]", ParticipantAddress.parseFromCommaSeparatedString("Musterweg 10, 47112 Musterstadt"), 2); RegistrationSummary thirdParticipant = frontendRunningDinnerService.performRegistration(publicDinnerId, registrationData, false); checkRegistrationSummary(thirdParticipant, 3); } protected void checkRegistrationSummary(RegistrationSummary registrationSummary, int expectedParticipantNumber) { Participant participant = registrationSummary.getParticipant(); assertThat(participant).isNotNull(); assertThat(participant.getParticipantNumber()).isEqualTo(expectedParticipantNumber); assertThat(participant.isNew()).isFalse(); } @Test public void testDuplicatedRegistration() { RegistrationDataV2TO registrationData = TestUtil.createRegistrationData("Max Mustermann", "[email protected]", ParticipantAddress.parseFromCommaSeparatedString("Musterstraße 1, 47111 Musterstadt"), 6); RegistrationSummary firstParticipant = frontendRunningDinnerService.performRegistration(publicDinnerId, registrationData, false); checkRegistrationSummary(firstParticipant, 1); try { frontendRunningDinnerService.performRegistration(publicDinnerId, registrationData, false); Assert.fail("Expected ValidationException to be thrown"); } catch (ValidationException ex) { assertThat(ex.getIssues().getIssues().get(0).getMessage()).isEqualTo(IssueKeys.PARTICIPANT_ALREADY_REGISTERED); } } @Test public void testFindPublicRunningDinnersSimple() { LocalDate todayIn29Days = todayIn30Days.minusDays(1); List<RunningDinner> publicRunningDinners = frontendRunningDinnerService.findPublicRunningDinners(todayIn29Days); assertDinnerFound(publicRunningDinners); } @Test public void testFindPublicDinnersSeveral() { LocalDate now = LocalDate.now(); LocalDate todayIn35Days = now.plusDays(35); LocalDate todayIn40Days = now.plusDays(40); LocalDate todayIn41Days = now.plusDays(41); RunningDinner firstPublicDinner = testHelperService.createPublicRunningDinner(todayIn40Days, 3); RunningDinner secondPublicDinner = testHelperService.createPublicRunningDinner(todayIn41Days, 3); RunningDinner closedRunningDinner = testHelperService.createPublicRunningDinner(todayIn40Days, 3, RegistrationType.OPEN); List<RunningDinner> publicRunningDinners = frontendRunningDinnerService.findPublicRunningDinners(todayIn35Days); assertThat(publicRunningDinners).contains(firstPublicDinner, secondPublicDinner); assertThat(publicRunningDinners).doesNotContain(closedRunningDinner); } @Test public void cancelledDinnerNotFound() { LocalDate todayIn29Days = todayIn30Days.minusDays(1); List<RunningDinner> publicRunningDinners = frontendRunningDinnerService.findPublicRunningDinners(todayIn29Days); assertDinnerFound(publicRunningDinners); runningDinnerService.cancelRunningDinner(runningDinner.getAdminId(), todayIn29Days.atTime(10, 10)); publicRunningDinners = frontendRunningDinnerService.findPublicRunningDinners(todayIn29Days); assertDinnerNotFound(publicRunningDinners); } private void assertDinnerFound(List<RunningDinner> publicRunningDinners) { Set<String> publicIds = publicRunningDinners.stream().map(p -> p.getPublicSettings().getPublicId()).collect(Collectors.toSet()); assertThat(publicIds).contains(runningDinner.getPublicSettings().getPublicId()); } private void assertDinnerNotFound(List<RunningDinner> publicRunningDinners) { Set<String> publicIds = publicRunningDinners.stream().map(p -> p.getPublicSettings().getPublicId()).collect(Collectors.toSet()); assertThat(publicIds).doesNotContain(runningDinner.getPublicSettings().getPublicId()); } }
Fixed test
runningdinner-backend/src/test/java/org/runningdinner/frontend/FrontendRunningDinnerTest.java
Fixed test
<ide><path>unningdinner-backend/src/test/java/org/runningdinner/frontend/FrontendRunningDinnerTest.java <ide> @Test <ide> public void testRegistrationInvalidName() { <ide> <del> RegistrationDataV2TO registrationData = TestUtil.createRegistrationData("Mustermann", "[email protected]", <add> RegistrationDataV2TO registrationData = TestUtil.createRegistrationData("Max Mustermann", "[email protected]", <ide> ParticipantAddress.parseFromCommaSeparatedString("Musterstraße 1, 47111 Musterstadt"), 6); <ide> <add> registrationData.setFirstnamePart(null); <add> registrationData.setLastname("Mustermann"); <add> <ide> try { <ide> frontendRunningDinnerService.performRegistration(publicDinnerId, registrationData, true); <ide> Assert.fail("Expected ValidationException to be thrown"); <del> } catch (ValidationException expectedEx) { <del> assertThat(expectedEx.getIssues().getIssues().get(0).getMessage()).isEqualTo(IssueKeys.FULLNAME_NOT_VALID); <add> } catch (IllegalArgumentException expectedEx) { <add> // NOP <add>// assertThat(expectedEx.getIssues().getIssues().get(0).getMessage()).isEqualTo(IssueKeys.FULLNAME_NOT_VALID); <ide> } <ide> } <ide>
Java
bsd-2-clause
373503752925c80f4ad22d110d91e11c8abb92c9
0
imagej/workflow-pipes,imagej/workflow-pipes
package imagej.workflowpipes.pipesentity; import java.io.Serializable; import java.text.ParseException; import java.util.ArrayList; import java.util.Iterator; import org.json.JSONObject; /* * Used to represent the conf JSON entity */ public class Conf implements Serializable { private Name name; private Type type; private Value value; /** * * @param name - Conf name * @param value - Conf value * @param type - Conf type */ public Conf( Name name, Value value, Type type ) { this.name = name; this.type = type; this.value = value; } public Type getType() { return type; } public Value getValue() { return value; } /** * returns true if conf's name matches inputName * @param name * @return */ public boolean isName( String inputName ) { if( inputName.equals( this.name.getValue() ) ) { return true; } return false; } /** * * @param confJSON - JSON input string used to create new Conf type */ public Conf( String name, JSONObject confJSON ) { this.name = new Name( name ); this.type = new Type( confJSON.getString("type") ); System.out.println("confJSON is " + confJSON); this.value = new Value( confJSON.getString("value") ); } /** * @returns the JSON Object representing this object */ public JSONObject getJSONObject() { //create a new object JSONObject json = new JSONObject(); //populate the value json.put("value", value.getValue() ); //poplutate the type json.put("type", type.getValue() ); JSONObject jsonOutput = new JSONObject(); jsonOutput.put( name.getValue(), json ); //return the object return jsonOutput; } public static ArrayList<Conf> getConfs( String string ) { ArrayList<Conf> confs = new ArrayList<Conf>(); //let class parse the input string JSONObject json = null; try { json = new JSONObject( string ); } catch (ParseException e) { e.printStackTrace(); } //use an iterator to find all the confs in the JSONObject Iterator i = json.keys(); while( i.hasNext() ) { JSONObject jsonConf; // get the name (key) value String name = (String) i.next(); // get the next conf as JSONObject jsonConf = json.getJSONObject( name ); //Create a conf object and add to the array confs.add( new Conf( name, jsonConf ) ); } return confs; } /** * returns the first conf found matching the string name * @param confName * @param confs * @return null if no match */ public static Conf getConf( String confName, ArrayList<Conf> confs ) { //for each conf in the array for(Conf conf:confs) { System.out.println("Conf :: getConf :: conf is " + conf.getJSONObject() ); //check to see if the name matches if( conf.isName(confName)) { //it matches so return this conf return conf; } } // no match - return null return null; } public static JSONObject getJSON(ArrayList<Conf> confs) { JSONObject json = new JSONObject(); // iterate over the confs for ( Conf conf : confs ) { JSONObject internalJSON = new JSONObject(); internalJSON.put( "value", conf.value.getValue() ); internalJSON.put( "type", conf.type.getValue() ); json.put( conf.name.getValue(), internalJSON ); } return json; } }
src/main/java/imagej/workflowpipes/pipesentity/Conf.java
package imagej.workflowpipes.pipesentity; import java.io.Serializable; import java.text.ParseException; import java.util.ArrayList; import java.util.Iterator; import org.json.JSONObject; /* * Used to represent the conf JSON entity */ public class Conf implements Serializable { private Name name; private Type type; private Value value; /** * * @param name - Conf name * @param value - Conf value * @param type - Conf type */ public Conf( Name name, Value value, Type type ) { this.name = name; this.type = type; this.value = value; } public Type getType() { return type; } public Value getValue() { return value; } /** * returns true if conf's name matches inputName * @param name * @return */ public boolean isName( String inputName ) { if( inputName.equals( this.name.getValue() ) ) { return true; } return false; } /** * * @param confJSON - JSON input string used to create new Conf type */ public Conf( String name, JSONObject confJSON ) { this.name = new Name( name ); this.type = new Type( confJSON.getString("type") ); this.value = new Value( confJSON.getString("value") ); } /** * @returns the JSON Object representing this object */ public JSONObject getJSONObject() { //create a new object JSONObject json = new JSONObject(); //populate the value json.put("value", value.getValue() ); //poplutate the type json.put("type", type.getValue() ); JSONObject jsonOutput = new JSONObject(); jsonOutput.put( name.getValue(), json ); //return the object return jsonOutput; } public static ArrayList<Conf> getConfs( String string ) { ArrayList<Conf> confs = new ArrayList<Conf>(); //let class parse the input string JSONObject json = null; try { json = new JSONObject( string ); } catch (ParseException e) { e.printStackTrace(); } //use an iterator to find all the confs in the JSONObject Iterator i = json.keys(); while( i.hasNext() ) { JSONObject jsonConf; // get the name (key) value String name = (String) i.next(); // get the next conf as JSONObject jsonConf = json.getJSONObject( name ); //Create a conf object and add to the array confs.add( new Conf( name, jsonConf ) ); } return confs; } /** * returns the first conf found matching the string name * @param confName * @param confs * @return null if no match */ public static Conf getConf( String confName, ArrayList<Conf> confs ) { //for each conf in the array for(Conf conf:confs) { System.out.println("Conf :: getConf :: conf is " + conf.getJSONObject() ); //check to see if the name matches if( conf.isName(confName)) { //it matches so return this conf return conf; } } // no match - return null return null; } public static JSONObject getJSON(ArrayList<Conf> confs) { JSONObject json = new JSONObject(); // iterate over the confs for ( Conf conf : confs ) { JSONObject internalJSON = new JSONObject(); internalJSON.put( "value", conf.value.getValue() ); internalJSON.put( "type", conf.type.getValue() ); json.put( conf.name.getValue(), internalJSON ); } return json; } }
Debugging. Whenever a plugin with text output is piped into a text field there is a problem. This prints out the JSON being evaluated. This used to be revision r2127.
src/main/java/imagej/workflowpipes/pipesentity/Conf.java
Debugging. Whenever a plugin with text output is piped into a text field there is a problem. This prints out the JSON being evaluated.
<ide><path>rc/main/java/imagej/workflowpipes/pipesentity/Conf.java <ide> { <ide> this.name = new Name( name ); <ide> this.type = new Type( confJSON.getString("type") ); <add> System.out.println("confJSON is " + confJSON); <ide> this.value = new Value( confJSON.getString("value") ); <ide> } <ide>
Java
apache-2.0
0bef1af00590c627982efc7bafa32e1867331a27
0
ok2c/httpclient,apache/httpcomponents-client,atlassian/httpclient,UlrichColby/httpcomponents-client,cmbntr/httpclient,cmbntr/httpclient,atlassian/httpclient
/* * ==================================================================== * 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.client.utils; import java.io.IOException; import java.net.URI; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.List; import java.util.Scanner; import org.apache.http.annotation.Immutable; import org.apache.http.entity.ContentType; import org.apache.http.Consts; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.message.BasicHeaderValueParser; import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.ParserCursor; import org.apache.http.protocol.HTTP; import org.apache.http.util.CharArrayBuffer; import org.apache.http.util.EntityUtils; /** * A collection of utilities for encoding URLs. * * @since 4.0 */ @Immutable public class URLEncodedUtils { public static final String CONTENT_TYPE = "application/x-www-form-urlencoded"; private static final String PARAMETER_SEPARATOR = "&"; private static final String NAME_VALUE_SEPARATOR = "="; /** * Returns a list of {@link NameValuePair NameValuePairs} as built from the * URI's query portion. For example, a URI of * http://example.org/path/to/file?a=1&b=2&c=3 would return a list of three * NameValuePairs, one for a=1, one for b=2, and one for c=3. * <p> * This is typically useful while parsing an HTTP PUT. * * @param uri * uri to parse * @param encoding * encoding to use while parsing the query */ public static List <NameValuePair> parse (final URI uri, final String encoding) { final String query = uri.getRawQuery(); if (query != null && query.length() > 0) { List<NameValuePair> result = new ArrayList<NameValuePair>(); Scanner scanner = new Scanner(query); parse(result, scanner, encoding); return result; } else { return Collections.emptyList(); } } /** * Returns a list of {@link NameValuePair NameValuePairs} as parsed from an * {@link HttpEntity}. The encoding is taken from the entity's * Content-Encoding header. * <p> * This is typically used while parsing an HTTP POST. * * @param entity * The entity to parse * @throws IOException * If there was an exception getting the entity's data. */ public static List <NameValuePair> parse ( final HttpEntity entity) throws IOException { ContentType contentType = ContentType.get(entity); if (contentType != null && contentType.getMimeType().equalsIgnoreCase(CONTENT_TYPE)) { String content = EntityUtils.toString(entity, Consts.ASCII); if (content != null && content.length() > 0) { Charset charset = contentType.getCharset(); if (charset == null) { charset = HTTP.DEF_CONTENT_CHARSET; } return parse(content, charset); } } return Collections.emptyList(); } /** * Returns true if the entity's Content-Type header is * <code>application/x-www-form-urlencoded</code>. */ public static boolean isEncoded (final HttpEntity entity) { Header h = entity.getContentType(); if (h != null) { HeaderElement[] elems = h.getElements(); if (elems.length > 0) { String contentType = elems[0].getName(); return contentType.equalsIgnoreCase(CONTENT_TYPE); } else { return false; } } else { return false; } } /** * Adds all parameters within the Scanner to the list of * <code>parameters</code>, as encoded by <code>encoding</code>. For * example, a scanner containing the string <code>a=1&b=2&c=3</code> would * add the {@link NameValuePair NameValuePairs} a=1, b=2, and c=3 to the * list of parameters. * * @param parameters * List to add parameters to. * @param scanner * Input that contains the parameters to parse. * @param charset * Encoding to use when decoding the parameters. */ public static void parse ( final List <NameValuePair> parameters, final Scanner scanner, final String charset) { scanner.useDelimiter(PARAMETER_SEPARATOR); while (scanner.hasNext()) { String name = null; String value = null; String token = scanner.next(); int i = token.indexOf(NAME_VALUE_SEPARATOR); if (i != -1) { name = decode(token.substring(0, i).trim(), charset); value = decode(token.substring(i + 1).trim(), charset); } else { name = decode(token.trim(), charset); } parameters.add(new BasicNameValuePair(name, value)); } } private static final char[] DELIM = new char[] { '&' }; /** * Returns a list of {@link NameValuePair NameValuePairs} as parsed from the given string * using the given character encoding. * * @param s * text to parse. * @param charset * Encoding to use when decoding the parameters. * * @since 4.2 */ public static List<NameValuePair> parse (final String s, final Charset charset) { if (s == null) { return Collections.emptyList(); } BasicHeaderValueParser parser = BasicHeaderValueParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(s.length()); buffer.append(s); ParserCursor cursor = new ParserCursor(0, buffer.length()); List<NameValuePair> list = new ArrayList<NameValuePair>(); while (!cursor.atEnd()) { NameValuePair nvp = parser.parseNameValuePair(buffer, cursor, DELIM); if (nvp.getName().length() > 0) { list.add(new BasicNameValuePair( decode(nvp.getName(), charset), decode(nvp.getValue(), charset))); } } return list; } /** * Returns a String that is suitable for use as an <code>application/x-www-form-urlencoded</code> * list of parameters in an HTTP PUT or HTTP POST. * * @param parameters The parameters to include. * @param encoding The encoding to use. */ public static String format ( final List <? extends NameValuePair> parameters, final String encoding) { final StringBuilder result = new StringBuilder(); for (final NameValuePair parameter : parameters) { final String encodedName = encode(parameter.getName(), encoding); final String encodedValue = encode(parameter.getValue(), encoding); if (result.length() > 0) { result.append(PARAMETER_SEPARATOR); } result.append(encodedName); if (encodedValue != null) { result.append(NAME_VALUE_SEPARATOR); result.append(encodedValue); } } return result.toString(); } /** * Returns a String that is suitable for use as an <code>application/x-www-form-urlencoded</code> * list of parameters in an HTTP PUT or HTTP POST. * * @param parameters The parameters to include. * @param charset The encoding to use. * * @since 4.2 */ public static String format ( final Iterable<? extends NameValuePair> parameters, final Charset charset) { final StringBuilder result = new StringBuilder(); for (final NameValuePair parameter : parameters) { final String encodedName = encode(parameter.getName(), charset); final String encodedValue = encode(parameter.getValue(), charset); if (result.length() > 0) { result.append(PARAMETER_SEPARATOR); } result.append(encodedName); if (encodedValue != null) { result.append(NAME_VALUE_SEPARATOR); result.append(encodedValue); } } return result.toString(); } /** Unreserved characters, i.e. alphanumeric, plus: _ - ! . ~ ' ( ) * */ private static final BitSet UNRESERVED = new BitSet(256); /** Punctuation characters: , ; : $ & + = */ private static final BitSet PUNCT = new BitSet(256); /** Characters which are safe to use, i.e. {@link #UNRESERVED} plus {@link #PUNCT}uation */ private static final BitSet SAFE = new BitSet(256); /** Characters which are safe to use in a path, i.e. {@link #UNRESERVED} plus {@link #PUNCT}uation plus / @ */ private static final BitSet PATHSAFE = new BitSet(256); static { // unreserved chars // alpha characters for (int i = 'a'; i <= 'z'; i++) { UNRESERVED.set(i); } for (int i = 'A'; i <= 'Z'; i++) { UNRESERVED.set(i); } // numeric characters for (int i = '0'; i <= '9'; i++) { UNRESERVED.set(i); } UNRESERVED.set('_'); UNRESERVED.set('-'); UNRESERVED.set('!'); UNRESERVED.set('.'); UNRESERVED.set('~'); UNRESERVED.set('\''); UNRESERVED.set('('); UNRESERVED.set(')'); UNRESERVED.set('*'); // punct chars PUNCT.set(','); PUNCT.set(';'); PUNCT.set(':'); PUNCT.set('$'); PUNCT.set('&'); PUNCT.set('+'); PUNCT.set('='); // URL path safe SAFE.or(UNRESERVED); SAFE.or(PUNCT); // URL path safe PATHSAFE.or(UNRESERVED); PATHSAFE.or(PUNCT); PATHSAFE.set('/'); PATHSAFE.set('@'); } private static final int RADIX = 16; private static String urlencode( final String content, final Charset charset, final BitSet safechars) { if (content == null) { return null; } StringBuilder buf = new StringBuilder(); ByteBuffer bb = charset.encode(content); while (bb.hasRemaining()) { int b = bb.get() & 0xff; if (safechars.get(b)) { buf.append((char) b); } else { buf.append("%"); char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, RADIX)); char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, RADIX)); buf.append(hex1); buf.append(hex2); } } return buf.toString(); } private static String urldecode( final String content, final Charset charset) { if (content == null) { return null; } ByteBuffer bb = ByteBuffer.allocate(content.length()); CharBuffer cb = CharBuffer.wrap(content); while (cb.hasRemaining()) { char c = cb.get(); if (c == '%' && cb.remaining() >= 2) { char uc = cb.get(); char lc = cb.get(); int u = Character.digit(uc, 16); int l = Character.digit(lc, 16); if (u != -1 && l != -1) { bb.put((byte) ((u << 4) + l)); } else { bb.put((byte) '%'); bb.put((byte) uc); bb.put((byte) lc); } } else { bb.put((byte) c); } } bb.flip(); return charset.decode(bb).toString(); } private static String decode (final String content, final String charset) { if (content == null) { return null; } return urldecode(content, charset != null ? Charset.forName(charset) : Consts.UTF_8); } private static String decode (final String content, final Charset charset) { if (content == null) { return null; } return urldecode(content, charset != null ? charset : Consts.UTF_8); } private static String encode(final String content, final String charset) { if (content == null) { return null; } return urlencode(content, charset != null ? Charset.forName(charset) : Consts.UTF_8, UNRESERVED); } private static String encode(final String content, final Charset charset) { if (content == null) { return null; } return urlencode(content, charset != null ? charset : Consts.UTF_8, UNRESERVED); } /** * Encode a String using the {@link #SAFE} set of characters. * * @param content the string to encode * @param charset the charset to use * @return the encoded string */ static String enc(final String content, final Charset charset) { return urlencode(content, charset, SAFE); } /** * Encode a String using the {@link #PATHSAFE} set of characters. * * @param content the string to encode * @param charset the charset to use * @return the encoded string */ static String encPath(final String content, final Charset charset) { return urlencode(content, charset, PATHSAFE); } }
httpclient/src/main/java/org/apache/http/client/utils/URLEncodedUtils.java
/* * ==================================================================== * 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.client.utils; import java.io.IOException; import java.net.URI; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.List; import java.util.Scanner; import org.apache.http.annotation.Immutable; import org.apache.http.entity.ContentType; import org.apache.http.Consts; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.message.BasicHeaderValueParser; import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.ParserCursor; import org.apache.http.protocol.HTTP; import org.apache.http.util.CharArrayBuffer; import org.apache.http.util.EntityUtils; /** * A collection of utilities for encoding URLs. * * @since 4.0 */ @Immutable public class URLEncodedUtils { public static final String CONTENT_TYPE = "application/x-www-form-urlencoded"; private static final String PARAMETER_SEPARATOR = "&"; private static final String NAME_VALUE_SEPARATOR = "="; /** * Returns a list of {@link NameValuePair NameValuePairs} as built from the * URI's query portion. For example, a URI of * http://example.org/path/to/file?a=1&b=2&c=3 would return a list of three * NameValuePairs, one for a=1, one for b=2, and one for c=3. * <p> * This is typically useful while parsing an HTTP PUT. * * @param uri * uri to parse * @param encoding * encoding to use while parsing the query */ public static List <NameValuePair> parse (final URI uri, final String encoding) { final String query = uri.getRawQuery(); if (query != null && query.length() > 0) { List<NameValuePair> result = new ArrayList<NameValuePair>(); Scanner scanner = new Scanner(query); parse(result, scanner, encoding); return result; } else { return Collections.emptyList(); } } /** * Returns a list of {@link NameValuePair NameValuePairs} as parsed from an * {@link HttpEntity}. The encoding is taken from the entity's * Content-Encoding header. * <p> * This is typically used while parsing an HTTP POST. * * @param entity * The entity to parse * @throws IOException * If there was an exception getting the entity's data. */ public static List <NameValuePair> parse ( final HttpEntity entity) throws IOException { ContentType contentType = ContentType.get(entity); if (contentType != null && contentType.getMimeType().equalsIgnoreCase(CONTENT_TYPE)) { String content = EntityUtils.toString(entity, Consts.ASCII); if (content != null && content.length() > 0) { Charset charset = contentType.getCharset(); if (charset == null) { charset = HTTP.DEF_CONTENT_CHARSET; } return parse(content, charset); } } return Collections.emptyList(); } /** * Returns true if the entity's Content-Type header is * <code>application/x-www-form-urlencoded</code>. */ public static boolean isEncoded (final HttpEntity entity) { Header h = entity.getContentType(); if (h != null) { HeaderElement[] elems = h.getElements(); if (elems.length > 0) { String contentType = elems[0].getName(); return contentType.equalsIgnoreCase(CONTENT_TYPE); } else { return false; } } else { return false; } } /** * Adds all parameters within the Scanner to the list of * <code>parameters</code>, as encoded by <code>encoding</code>. For * example, a scanner containing the string <code>a=1&b=2&c=3</code> would * add the {@link NameValuePair NameValuePairs} a=1, b=2, and c=3 to the * list of parameters. * * @param parameters * List to add parameters to. * @param scanner * Input that contains the parameters to parse. * @param charset * Encoding to use when decoding the parameters. */ public static void parse ( final List <NameValuePair> parameters, final Scanner scanner, final String charset) { scanner.useDelimiter(PARAMETER_SEPARATOR); while (scanner.hasNext()) { String name = null; String value = null; String token = scanner.next(); int i = token.indexOf(NAME_VALUE_SEPARATOR); if (i != -1) { name = decode(token.substring(0, i).trim(), charset); value = decode(token.substring(i + 1).trim(), charset); } else { name = decode(token.trim(), charset); } parameters.add(new BasicNameValuePair(name, value)); } } private static final char[] DELIM = new char[] { '&' }; /** * Returns a list of {@link NameValuePair NameValuePairs} as parsed from the given string * using the given character encoding. * * @param s * text to parse. * @param charset * Encoding to use when decoding the parameters. * * @since 4.2 */ public static List<NameValuePair> parse (final String s, final Charset charset) { if (s == null) { return Collections.emptyList(); } BasicHeaderValueParser parser = BasicHeaderValueParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(s.length()); buffer.append(s); ParserCursor cursor = new ParserCursor(0, buffer.length()); List<NameValuePair> list = new ArrayList<NameValuePair>(); while (!cursor.atEnd()) { NameValuePair nvp = parser.parseNameValuePair(buffer, cursor, DELIM); if (nvp.getName().length() > 0) { list.add(new BasicNameValuePair( decode(nvp.getName(), charset), decode(nvp.getValue(), charset))); } } return list; } /** * Returns a String that is suitable for use as an <code>application/x-www-form-urlencoded</code> * list of parameters in an HTTP PUT or HTTP POST. * * @param parameters The parameters to include. * @param encoding The encoding to use. */ public static String format ( final List <? extends NameValuePair> parameters, final String encoding) { final StringBuilder result = new StringBuilder(); for (final NameValuePair parameter : parameters) { final String encodedName = encode(parameter.getName(), encoding); final String encodedValue = encode(parameter.getValue(), encoding); if (result.length() > 0) { result.append(PARAMETER_SEPARATOR); } result.append(encodedName); if (encodedValue != null) { result.append(NAME_VALUE_SEPARATOR); result.append(encodedValue); } } return result.toString(); } /** * Returns a String that is suitable for use as an <code>application/x-www-form-urlencoded</code> * list of parameters in an HTTP PUT or HTTP POST. * * @param parameters The parameters to include. * @param charset The encoding to use. * * @since 4.2 */ public static String format ( final Iterable<? extends NameValuePair> parameters, final Charset charset) { final StringBuilder result = new StringBuilder(); for (final NameValuePair parameter : parameters) { final String encodedName = encode(parameter.getName(), charset); final String encodedValue = encode(parameter.getValue(), charset); if (result.length() > 0) { result.append(PARAMETER_SEPARATOR); } result.append(encodedName); if (encodedValue != null) { result.append(NAME_VALUE_SEPARATOR); result.append(encodedValue); } } return result.toString(); } private static final BitSet UNRESERVED = new BitSet(256); private static final BitSet PUNCT = new BitSet(256); private static final BitSet SAFE = new BitSet(256); private static final BitSet PATHSAFE = new BitSet(256); static { // unreserved chars // alpha characters for (int i = 'a'; i <= 'z'; i++) { UNRESERVED.set(i); } for (int i = 'A'; i <= 'Z'; i++) { UNRESERVED.set(i); } // numeric characters for (int i = '0'; i <= '9'; i++) { UNRESERVED.set(i); } UNRESERVED.set('_'); UNRESERVED.set('-'); UNRESERVED.set('!'); UNRESERVED.set('.'); UNRESERVED.set('~'); UNRESERVED.set('\''); UNRESERVED.set('('); UNRESERVED.set(')'); UNRESERVED.set('*'); // punct chars PUNCT.set(','); PUNCT.set(';'); PUNCT.set(':'); PUNCT.set('$'); PUNCT.set('&'); PUNCT.set('+'); PUNCT.set('='); // URL path safe SAFE.or(UNRESERVED); SAFE.or(PUNCT); // URL path safe PATHSAFE.or(UNRESERVED); PATHSAFE.or(PUNCT); PATHSAFE.set('/'); PATHSAFE.set('@'); } private static final int RADIX = 16; private static String urlencode( final String content, final Charset charset, final BitSet safechars) { if (content == null) { return null; } StringBuilder buf = new StringBuilder(); ByteBuffer bb = charset.encode(content); while (bb.hasRemaining()) { int b = bb.get() & 0xff; if (safechars.get(b)) { buf.append((char) b); } else { buf.append("%"); char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, RADIX)); char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, RADIX)); buf.append(hex1); buf.append(hex2); } } return buf.toString(); } private static String urldecode( final String content, final Charset charset) { if (content == null) { return null; } ByteBuffer bb = ByteBuffer.allocate(content.length()); CharBuffer cb = CharBuffer.wrap(content); while (cb.hasRemaining()) { char c = cb.get(); if (c == '%' && cb.remaining() >= 2) { char uc = cb.get(); char lc = cb.get(); int u = Character.digit(uc, 16); int l = Character.digit(lc, 16); if (u != -1 && l != -1) { bb.put((byte) ((u << 4) + l)); } else { bb.put((byte) '%'); bb.put((byte) uc); bb.put((byte) lc); } } else { bb.put((byte) c); } } bb.flip(); return charset.decode(bb).toString(); } private static String decode (final String content, final String charset) { if (content == null) { return null; } return urldecode(content, charset != null ? Charset.forName(charset) : Consts.UTF_8); } private static String decode (final String content, final Charset charset) { if (content == null) { return null; } return urldecode(content, charset != null ? charset : Consts.UTF_8); } private static String encode(final String content, final String charset) { if (content == null) { return null; } return urlencode(content, charset != null ? Charset.forName(charset) : Consts.UTF_8, UNRESERVED); } private static String encode(final String content, final Charset charset) { if (content == null) { return null; } return urlencode(content, charset != null ? charset : Consts.UTF_8, UNRESERVED); } static String enc(final String content, final Charset charset) { return urlencode(content, charset, SAFE); } static String encPath(final String content, final Charset charset) { return urlencode(content, charset, PATHSAFE); } }
Javadoc git-svn-id: 897293da6115b9493049ecf64199cf2f9a0ac287@1353368 13f79535-47bb-0310-9956-ffa450edef68
httpclient/src/main/java/org/apache/http/client/utils/URLEncodedUtils.java
Javadoc
<ide><path>ttpclient/src/main/java/org/apache/http/client/utils/URLEncodedUtils.java <ide> return result.toString(); <ide> } <ide> <add> /** Unreserved characters, i.e. alphanumeric, plus: _ - ! . ~ ' ( ) * */ <ide> private static final BitSet UNRESERVED = new BitSet(256); <add> /** Punctuation characters: , ; : $ & + = */ <ide> private static final BitSet PUNCT = new BitSet(256); <add> /** Characters which are safe to use, i.e. {@link #UNRESERVED} plus {@link #PUNCT}uation */ <ide> private static final BitSet SAFE = new BitSet(256); <add> /** Characters which are safe to use in a path, i.e. {@link #UNRESERVED} plus {@link #PUNCT}uation plus / @ */ <ide> private static final BitSet PATHSAFE = new BitSet(256); <ide> <ide> static { <ide> return urlencode(content, charset != null ? charset : Consts.UTF_8, UNRESERVED); <ide> } <ide> <add> /** <add> * Encode a String using the {@link #SAFE} set of characters. <add> * <add> * @param content the string to encode <add> * @param charset the charset to use <add> * @return the encoded string <add> */ <ide> static String enc(final String content, final Charset charset) { <ide> return urlencode(content, charset, SAFE); <ide> } <ide> <add> /** <add> * Encode a String using the {@link #PATHSAFE} set of characters. <add> * <add> * @param content the string to encode <add> * @param charset the charset to use <add> * @return the encoded string <add> */ <ide> static String encPath(final String content, final Charset charset) { <ide> return urlencode(content, charset, PATHSAFE); <ide> }
Java
apache-2.0
99dd0f3451a0d3031650cf386c6a77a8709791ca
0
Kodehawa/imageboard-api
/* * Copyright 2017 Kodehawa * * 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 net.kodehawa.lib.imageboards.entities.impl; import net.kodehawa.lib.imageboards.entities.BoardImage; import net.kodehawa.lib.imageboards.entities.Rating; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Kodehawa */ public class DanbooruImage implements BoardImage { private int uploader_id; private int score; private String source; private Rating rating; private int image_width; private int image_height; private String tag_string; private String file_ext; private int file_size; private int up_score; private int down_score; private int tag_count; private String uploader_name; private String tag_string_artist; private String tag_string_character; private String file_url; private String large_file_url; private String preview_file_url; private Pattern urlPattern = Pattern.compile("https(:)?//[\\w\\d.]*donmai.us"); /** * Danbooru normally returns the URL as <p>"file_url": "/data/__furude_rika_higurashi_no_naku_koro_ni_drawn_by_kamaboko_red__fc6fb27e9c6ea2a77c849e5483eafc40.png"</p> * Which isn't reachable. This methods gets around it. * @return The *reachable* URL to get this image. PNG format, or the extension defined in file_ext. */ public String getParsedFileUrl() { return getFixedURL(file_url); } /** * Danbooru normally returns the URL as <p>"large_file_url": "/data/__furude_rika_higurashi_no_naku_koro_ni_drawn_by_kamaboko_red__fc6fb27e9c6ea2a77c849e5483eafc40.jpg"</p> * Which isn't reachable. This methods gets around it. * @return The *reachable* URL to get this image. JPG format. */ public String getParsedLargeFileUrl() { return getFixedURL(large_file_url); } /** * Danbooru normally returns the URL as <p>"preview_file_url": "/data/preview/fc6fb27e9c6ea2a77c849e5483eafc40.jpg"</p> * Which isn't reachable. This methods gets around it. * @return The *reachable* URL to get this image. JPG format. */ public String getParsedPreviewFileUrl() { return getFixedURL(this.preview_file_url); } private String getFixedURL(String url) { if (url == null) { return null; } Matcher matcher = urlPattern.matcher(url); if(matcher.find()) { if(matcher.group(1).isEmpty()) { // Broken URL (https//) return url.replace("https//", "https://"); } else { return url; // Valid URL } } else { // URL without domain (/data/XXX) return "https://danbooru.donmai.us" + url; } } @Override public int getWidth() { return image_width; } @Override public int getHeight() { return image_height; } @Override public Rating getRating() { return rating; } @Override public int getScore() { return score; } @Override public List<String> getTags() { return Collections.unmodifiableList(Arrays.asList(tag_string.split(" "))); } @Override public String getURL() { return getParsedFileUrl(); } public int getUploader_id() { return uploader_id; } public String getSource() { return source; } public int getImage_width() { return image_width; } public int getImage_height() { return image_height; } public String getTag_string() { return tag_string; } public String getFile_ext() { return file_ext; } public int getFile_size() { return file_size; } public int getUp_score() { return up_score; } public int getDown_score() { return down_score; } public int getTag_count() { return tag_count; } public String getUploader_name() { return uploader_name; } public String getTag_string_artist() { return tag_string_artist; } public String getTag_string_character() { return tag_string_character; } public String getFile_url() { return file_url; } public String getLarge_file_url() { return large_file_url; } public String getPreview_file_url() { return preview_file_url; } }
src/main/java/net/kodehawa/lib/imageboards/entities/impl/DanbooruImage.java
/* * Copyright 2017 Kodehawa * * 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 net.kodehawa.lib.imageboards.entities.impl; import net.kodehawa.lib.imageboards.entities.BoardImage; import net.kodehawa.lib.imageboards.entities.Rating; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Kodehawa */ public class DanbooruImage implements BoardImage { private int uploader_id; private int score; private String source; private Rating rating; private int image_width; private int image_height; private String tag_string; private String file_ext; private int file_size; private int up_score; private int down_score; private int tag_count; private String uploader_name; private String tag_string_artist; private String tag_string_character; private String file_url; private String large_file_url; private String preview_file_url; private Pattern urlPattern = Pattern.compile("https(:)?//[\\w\\d.]*donmai.us"); /** * Danbooru normally returns the URL as <p>"file_url": "/data/__furude_rika_higurashi_no_naku_koro_ni_drawn_by_kamaboko_red__fc6fb27e9c6ea2a77c849e5483eafc40.png"</p> * Which isn't reachable. This methods gets around it. * @return The *reachable* URL to get this image. PNG format, or the extension defined in file_ext. */ public String getParsedFileUrl() { return getFixedURL(file_url); } /** * Danbooru normally returns the URL as <p>"large_file_url": "/data/__furude_rika_higurashi_no_naku_koro_ni_drawn_by_kamaboko_red__fc6fb27e9c6ea2a77c849e5483eafc40.jpg"</p> * Which isn't reachable. This methods gets around it. * @return The *reachable* URL to get this image. JPG format. */ public String getParsedLargeFileUrl() { return getFixedURL(large_file_url); } /** * Danbooru normally returns the URL as <p>"preview_file_url": "/data/preview/fc6fb27e9c6ea2a77c849e5483eafc40.jpg"</p> * Which isn't reachable. This methods gets around it. * @return The *reachable* URL to get this image. JPG format. */ public String getParsedPreviewFileUrl() { return getFixedURL(this.preview_file_url); } private String getFixedURL(String url) { Matcher matcher = urlPattern.matcher(url); if(matcher.find()) { if(matcher.group(1).isEmpty()) { // Broken URL (https//) return url.replace("https//", "https://"); } else { return url; // Valid URL } } else { // URL without domain (/data/XXX) return "https://danbooru.donmai.us" + url; } } @Override public int getWidth() { return image_width; } @Override public int getHeight() { return image_height; } @Override public Rating getRating() { return rating; } @Override public int getScore() { return score; } @Override public List<String> getTags() { return Collections.unmodifiableList(Arrays.asList(tag_string.split(" "))); } @Override public String getURL() { return getParsedFileUrl(); } public int getUploader_id() { return uploader_id; } public String getSource() { return source; } public int getImage_width() { return image_width; } public int getImage_height() { return image_height; } public String getTag_string() { return tag_string; } public String getFile_ext() { return file_ext; } public int getFile_size() { return file_size; } public int getUp_score() { return up_score; } public int getDown_score() { return down_score; } public int getTag_count() { return tag_count; } public String getUploader_name() { return uploader_name; } public String getTag_string_artist() { return tag_string_artist; } public String getTag_string_character() { return tag_string_character; } public String getFile_url() { return file_url; } public String getLarge_file_url() { return large_file_url; } public String getPreview_file_url() { return preview_file_url; } }
Stop making Matcher explode (#17) Danbooru is a meme
src/main/java/net/kodehawa/lib/imageboards/entities/impl/DanbooruImage.java
Stop making Matcher explode (#17)
<ide><path>rc/main/java/net/kodehawa/lib/imageboards/entities/impl/DanbooruImage.java <ide> } <ide> <ide> private String getFixedURL(String url) { <add> if (url == null) { <add> return null; <add> } <ide> Matcher matcher = urlPattern.matcher(url); <ide> if(matcher.find()) { <ide> if(matcher.group(1).isEmpty()) {
Java
agpl-3.0
error: pathspec 'projects/cadcTAP/test/src/ca/nrc/cadc/tap/upload/UploadUtilTest.java' did not match any file(s) known to git
db3d2f110c46534a4e21d3248c90890510a3b74d
1
opencadc/tap,opencadc/tap
/* ************************************************************************ ******************* CANADIAN ASTRONOMY DATA CENTRE ******************* ************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES ************** * * (c) 2009. (c) 2009. * Government of Canada Gouvernement du Canada * National Research Council Conseil national de recherches * Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6 * All rights reserved Tous droits réservés * * NRC disclaims any warranties, Le CNRC dénie toute garantie * expressed, implied, or énoncée, implicite ou légale, * statutory, of any kind with de quelque nature que ce * respect to the software, soit, concernant le logiciel, * including without limitation y compris sans restriction * any warranty of merchantability toute garantie de valeur * or fitness for a particular marchande ou de pertinence * purpose. NRC shall not be pour un usage particulier. * liable in any event for any Le CNRC ne pourra en aucun cas * damages, whether direct or être tenu responsable de tout * indirect, special or general, dommage, direct ou indirect, * consequential or incidental, particulier ou général, * arising from the use of the accessoire ou fortuit, résultant * software. Neither the name de l'utilisation du logiciel. Ni * of the National Research le nom du Conseil National de * Council of Canada nor the Recherches du Canada ni les noms * names of its contributors may de ses participants ne peuvent * be used to endorse or promote être utilisés pour approuver ou * products derived from this promouvoir les produits dérivés * software without specific prior de ce logiciel sans autorisation * written permission. préalable et particulière * par écrit. * * This file is part of the Ce fichier fait partie du projet * OpenCADC project. OpenCADC. * * OpenCADC is free software: OpenCADC est un logiciel libre ; * you can redistribute it and/or vous pouvez le redistribuer ou le * modify it under the terms of modifier suivant les termes de * the GNU Affero General Public la “GNU Affero General Public * License as published by the License” telle que publiée * Free Software Foundation, par la Free Software Foundation * either version 3 of the : soit la version 3 de cette * License, or (at your option) licence, soit (à votre gré) * any later version. toute version ultérieure. * * OpenCADC is distributed in the OpenCADC est distribué * hope that it will be useful, dans l’espoir qu’il vous * but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE * without even the implied GARANTIE : sans même la garantie * warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ * or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF * PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence * General Public License for Générale Publique GNU Affero * more details. pour plus de détails. * * You should have received Vous devriez avoir reçu une * a copy of the GNU Affero copie de la Licence Générale * General Public License along Publique GNU Affero avec * with OpenCADC. If not, see OpenCADC ; si ce n’est * <http://www.gnu.org/licenses/>. pas le cas, consultez : * <http://www.gnu.org/licenses/>. * * $Revision: 4 $ * ************************************************************************ */ package ca.nrc.cadc.tap.upload; import ca.nrc.cadc.util.Log4jInit; import junit.framework.Assert; import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * * @author jburke */ public class UploadUtilTest { private static Logger log = Logger.getLogger(UploadUtilTest.class); static { Log4jInit.setLevel("ca.nrc.cadc.tap.upload", org.apache.log4j.Level.DEBUG); } public UploadUtilTest() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testIsValidateIdentifier() { try { Assert.assertTrue(UploadUtil.isValidateIdentifier("a")); Assert.assertTrue(UploadUtil.isValidateIdentifier("A")); Assert.assertTrue(UploadUtil.isValidateIdentifier("z")); Assert.assertTrue(UploadUtil.isValidateIdentifier("Z")); Assert.assertTrue(UploadUtil.isValidateIdentifier("a1")); Assert.assertTrue(UploadUtil.isValidateIdentifier("a_1")); Assert.assertTrue(UploadUtil.isValidateIdentifier("Z1_")); try { UploadUtil.isValidateIdentifier(null); fail("null is not a valid identifier"); } catch (ADQLIdentifierException ignore) { } try { UploadUtil.isValidateIdentifier(""); fail("empty string is not a valid identifier"); } catch (ADQLIdentifierException ignore) { } try { UploadUtil.isValidateIdentifier("1name"); fail("identifier cannot start with a digit"); } catch (ADQLIdentifierException ignore) { } try { UploadUtil.isValidateIdentifier("_"); fail("identifier cannot start with an underscore"); } catch (ADQLIdentifierException ignore) { } try { UploadUtil.isValidateIdentifier(" name"); fail("identifier cannot start with a space"); } catch (ADQLIdentifierException ignore) { } try { UploadUtil.isValidateIdentifier("a name"); fail("identifier cannot contain with a space"); } catch (ADQLIdentifierException ignore) { } try { UploadUtil.isValidateIdentifier("name "); fail("identifier cannot end with a space"); } catch (ADQLIdentifierException ignore) { } try { UploadUtil.isValidateIdentifier("name?"); fail("identifier must only contain letter, digits, or an underscore"); } catch (ADQLIdentifierException ignore) { } try { UploadUtil.isValidateIdentifier("n-ame"); fail("identifier must only contain letter, digits, or an underscore"); } catch (ADQLIdentifierException ignore) { } try { UploadUtil.isValidateIdentifier("name!"); fail("identifier must only contain letter, digits, or an underscore"); } catch (ADQLIdentifierException ignore) { } try { UploadUtil.isValidateIdentifier("name="); fail("identifier must only contain letter, digits, or an underscore"); } catch (ADQLIdentifierException ignore) { } } catch (Exception unexpected) { log.error("unexpected exception", unexpected); fail("unexpected exception: " + unexpected); } } @Test public void testIsAscii() { try { Assert.assertTrue(UploadUtil.isAsciiLetter('a')); Assert.assertTrue(UploadUtil.isAsciiLetter('A')); Assert.assertTrue(UploadUtil.isAsciiLetter('z')); Assert.assertTrue(UploadUtil.isAsciiLetter('Z')); Assert.assertFalse(UploadUtil.isAsciiLetter('1')); Assert.assertFalse(UploadUtil.isAsciiLetter(' ')); Assert.assertFalse(UploadUtil.isAsciiLetter('@')); Assert.assertFalse(UploadUtil.isAsciiLetter('_')); } catch (Exception unexpected) { log.error("unexpected exception", unexpected); fail("unexpected exception: " + unexpected); } } @Test public void testIsValidIdentifierCharacter() { try { Assert.assertTrue(UploadUtil.isValidIdentifierCharacter('a')); Assert.assertTrue(UploadUtil.isValidIdentifierCharacter('A')); Assert.assertTrue(UploadUtil.isValidIdentifierCharacter('z')); Assert.assertTrue(UploadUtil.isValidIdentifierCharacter('Z')); Assert.assertTrue(UploadUtil.isValidIdentifierCharacter('0')); Assert.assertTrue(UploadUtil.isValidIdentifierCharacter('9')); Assert.assertTrue(UploadUtil.isValidIdentifierCharacter('_')); Assert.assertFalse(UploadUtil.isValidIdentifierCharacter(' ')); Assert.assertFalse(UploadUtil.isValidIdentifierCharacter('@')); Assert.assertFalse(UploadUtil.isValidIdentifierCharacter('?')); } catch (Exception unexpected) { log.error("unexpected exception", unexpected); fail("unexpected exception: " + unexpected); } } }
projects/cadcTAP/test/src/ca/nrc/cadc/tap/upload/UploadUtilTest.java
Unit tests for UploadUtil. git-svn-id: 311fcc5b8b03427d323cee07bbb9e5a14d8d22e9@1200 728ff76a-78ac-11de-a72b-d90af8dea425
projects/cadcTAP/test/src/ca/nrc/cadc/tap/upload/UploadUtilTest.java
Unit tests for UploadUtil.
<ide><path>rojects/cadcTAP/test/src/ca/nrc/cadc/tap/upload/UploadUtilTest.java <add>/* <add> ************************************************************************ <add> ******************* CANADIAN ASTRONOMY DATA CENTRE ******************* <add> ************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES ************** <add> * <add> * (c) 2009. (c) 2009. <add> * Government of Canada Gouvernement du Canada <add> * National Research Council Conseil national de recherches <add> * Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6 <add> * All rights reserved Tous droits réservés <add> * <add> * NRC disclaims any warranties, Le CNRC dénie toute garantie <add> * expressed, implied, or énoncée, implicite ou légale, <add> * statutory, of any kind with de quelque nature que ce <add> * respect to the software, soit, concernant le logiciel, <add> * including without limitation y compris sans restriction <add> * any warranty of merchantability toute garantie de valeur <add> * or fitness for a particular marchande ou de pertinence <add> * purpose. NRC shall not be pour un usage particulier. <add> * liable in any event for any Le CNRC ne pourra en aucun cas <add> * damages, whether direct or être tenu responsable de tout <add> * indirect, special or general, dommage, direct ou indirect, <add> * consequential or incidental, particulier ou général, <add> * arising from the use of the accessoire ou fortuit, résultant <add> * software. Neither the name de l'utilisation du logiciel. Ni <add> * of the National Research le nom du Conseil National de <add> * Council of Canada nor the Recherches du Canada ni les noms <add> * names of its contributors may de ses participants ne peuvent <add> * be used to endorse or promote être utilisés pour approuver ou <add> * products derived from this promouvoir les produits dérivés <add> * software without specific prior de ce logiciel sans autorisation <add> * written permission. préalable et particulière <add> * par écrit. <add> * <add> * This file is part of the Ce fichier fait partie du projet <add> * OpenCADC project. OpenCADC. <add> * <add> * OpenCADC is free software: OpenCADC est un logiciel libre ; <add> * you can redistribute it and/or vous pouvez le redistribuer ou le <add> * modify it under the terms of modifier suivant les termes de <add> * the GNU Affero General Public la “GNU Affero General Public <add> * License as published by the License” telle que publiée <add> * Free Software Foundation, par la Free Software Foundation <add> * either version 3 of the : soit la version 3 de cette <add> * License, or (at your option) licence, soit (à votre gré) <add> * any later version. toute version ultérieure. <add> * <add> * OpenCADC is distributed in the OpenCADC est distribué <add> * hope that it will be useful, dans l’espoir qu’il vous <add> * but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE <add> * without even the implied GARANTIE : sans même la garantie <add> * warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ <add> * or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF <add> * PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence <add> * General Public License for Générale Publique GNU Affero <add> * more details. pour plus de détails. <add> * <add> * You should have received Vous devriez avoir reçu une <add> * a copy of the GNU Affero copie de la Licence Générale <add> * General Public License along Publique GNU Affero avec <add> * with OpenCADC. If not, see OpenCADC ; si ce n’est <add> * <http://www.gnu.org/licenses/>. pas le cas, consultez : <add> * <http://www.gnu.org/licenses/>. <add> * <add> * $Revision: 4 $ <add> * <add> ************************************************************************ <add> */ <add>package ca.nrc.cadc.tap.upload; <add> <add>import ca.nrc.cadc.util.Log4jInit; <add>import junit.framework.Assert; <add>import org.apache.log4j.Logger; <add>import org.junit.After; <add>import org.junit.Before; <add>import org.junit.Test; <add>import static org.junit.Assert.*; <add> <add>/** <add> * <add> * @author jburke <add> */ <add>public class UploadUtilTest <add>{ <add> private static Logger log = Logger.getLogger(UploadUtilTest.class); <add> static <add> { <add> Log4jInit.setLevel("ca.nrc.cadc.tap.upload", org.apache.log4j.Level.DEBUG); <add> } <add> <add> public UploadUtilTest() <add> { <add> } <add> <add> @Before <add> public void setUp() <add> { <add> } <add> <add> @After <add> public void tearDown() <add> { <add> } <add> <add> @Test <add> public void testIsValidateIdentifier() <add> { <add> try <add> { <add> Assert.assertTrue(UploadUtil.isValidateIdentifier("a")); <add> Assert.assertTrue(UploadUtil.isValidateIdentifier("A")); <add> Assert.assertTrue(UploadUtil.isValidateIdentifier("z")); <add> Assert.assertTrue(UploadUtil.isValidateIdentifier("Z")); <add> Assert.assertTrue(UploadUtil.isValidateIdentifier("a1")); <add> Assert.assertTrue(UploadUtil.isValidateIdentifier("a_1")); <add> Assert.assertTrue(UploadUtil.isValidateIdentifier("Z1_")); <add> <add> try <add> { <add> UploadUtil.isValidateIdentifier(null); <add> fail("null is not a valid identifier"); <add> } <add> catch (ADQLIdentifierException ignore) { } <add> <add> try <add> { <add> UploadUtil.isValidateIdentifier(""); <add> fail("empty string is not a valid identifier"); <add> } <add> catch (ADQLIdentifierException ignore) { } <add> <add> try <add> { <add> UploadUtil.isValidateIdentifier("1name"); <add> fail("identifier cannot start with a digit"); <add> } <add> catch (ADQLIdentifierException ignore) { } <add> <add> try <add> { <add> UploadUtil.isValidateIdentifier("_"); <add> fail("identifier cannot start with an underscore"); <add> } <add> catch (ADQLIdentifierException ignore) { } <add> <add> try <add> { <add> UploadUtil.isValidateIdentifier(" name"); <add> fail("identifier cannot start with a space"); <add> } <add> catch (ADQLIdentifierException ignore) { } <add> <add> try <add> { <add> UploadUtil.isValidateIdentifier("a name"); <add> fail("identifier cannot contain with a space"); <add> } <add> catch (ADQLIdentifierException ignore) { } <add> <add> try <add> { <add> UploadUtil.isValidateIdentifier("name "); <add> fail("identifier cannot end with a space"); <add> } <add> catch (ADQLIdentifierException ignore) { } <add> <add> try <add> { <add> UploadUtil.isValidateIdentifier("name?"); <add> fail("identifier must only contain letter, digits, or an underscore"); <add> } <add> catch (ADQLIdentifierException ignore) { } <add> <add> try <add> { <add> UploadUtil.isValidateIdentifier("n-ame"); <add> fail("identifier must only contain letter, digits, or an underscore"); <add> } <add> catch (ADQLIdentifierException ignore) { } <add> <add> try <add> { <add> UploadUtil.isValidateIdentifier("name!"); <add> fail("identifier must only contain letter, digits, or an underscore"); <add> } <add> catch (ADQLIdentifierException ignore) { } <add> <add> try <add> { <add> UploadUtil.isValidateIdentifier("name="); <add> fail("identifier must only contain letter, digits, or an underscore"); <add> } <add> catch (ADQLIdentifierException ignore) { } <add> <add> } <add> catch (Exception unexpected) <add> { <add> log.error("unexpected exception", unexpected); <add> fail("unexpected exception: " + unexpected); <add> } <add> } <add> <add> @Test <add> public void testIsAscii() <add> { <add> try <add> { <add> Assert.assertTrue(UploadUtil.isAsciiLetter('a')); <add> Assert.assertTrue(UploadUtil.isAsciiLetter('A')); <add> Assert.assertTrue(UploadUtil.isAsciiLetter('z')); <add> Assert.assertTrue(UploadUtil.isAsciiLetter('Z')); <add> Assert.assertFalse(UploadUtil.isAsciiLetter('1')); <add> Assert.assertFalse(UploadUtil.isAsciiLetter(' ')); <add> Assert.assertFalse(UploadUtil.isAsciiLetter('@')); <add> Assert.assertFalse(UploadUtil.isAsciiLetter('_')); <add> } <add> catch (Exception unexpected) <add> { <add> log.error("unexpected exception", unexpected); <add> fail("unexpected exception: " + unexpected); <add> } <add> } <add> <add> @Test <add> public void testIsValidIdentifierCharacter() <add> { <add> try <add> { <add> Assert.assertTrue(UploadUtil.isValidIdentifierCharacter('a')); <add> Assert.assertTrue(UploadUtil.isValidIdentifierCharacter('A')); <add> Assert.assertTrue(UploadUtil.isValidIdentifierCharacter('z')); <add> Assert.assertTrue(UploadUtil.isValidIdentifierCharacter('Z')); <add> Assert.assertTrue(UploadUtil.isValidIdentifierCharacter('0')); <add> Assert.assertTrue(UploadUtil.isValidIdentifierCharacter('9')); <add> Assert.assertTrue(UploadUtil.isValidIdentifierCharacter('_')); <add> Assert.assertFalse(UploadUtil.isValidIdentifierCharacter(' ')); <add> Assert.assertFalse(UploadUtil.isValidIdentifierCharacter('@')); <add> Assert.assertFalse(UploadUtil.isValidIdentifierCharacter('?')); <add> } <add> catch (Exception unexpected) <add> { <add> log.error("unexpected exception", unexpected); <add> fail("unexpected exception: " + unexpected); <add> } <add> } <add> <add>}
JavaScript
mit
dab13b527d4fa8ebb68e01bc6d1ce8921c3eeaed
0
jcwaco/TestSetList,jcwaco/TestSetList
// This App is supposed to find Test Sets and then list the Test Cases within them // // // //A new comment is added // // Verify connector function // Prepare to add pull requests // // //This a Test of vcs connector 2.0.5 // //Creating a change in the code // // Test the logistics // A change for the better // Added by JC // // Ext.define('CustomApp', { extend: 'Rally.app.App', componentCls: 'app', items:{ html:'<a href="https://help.rallydev.com/apps/2.0rc3/doc/">App SDK 2.0rc3 Docs</a>'}, launch: function() { var deStore; var panel1 = Ext.create( 'Ext.panel.Panel', { layout : { type : 'hbox', // Arrange child items vertically align : 'middle', // Each takes up full width }, width : '100%', bodyPadding : 10, bodyStyle : { background : '#9A9494', }, items : [ { xtype : 'container', itemId : 'iterationFilter' }, { xtype : 'rallybutton', text : 'Print Summary', handler : function () { this._printSummary(); }, style : { marginRight : '10px', marginLeft : '10px' }, // flex:'1', scope : this } /* * { xtype:'rallybutton', text: 'Print Defects', handler: function() { this._printDefects(); }, style: { marginLeft: '10px' }, * * flex:'1', scope:this } */ ] } ); this.add( panel1 ); var panel2 = Ext.create( 'Ext.panel.Panel', { layout : 'vbox', width : '100%', bodyPadding : 10, bodyStyle : { background : '#9A9494', }, items : [ { xtype : 'container', layout : 'accordion', itemId : 'testStatus', width : '100%', height : 500 } ] } ); this.add( panel2 ); this._testSummary = []; this._testResultList = []; this._testSetTestList = []; var TestSetStore; var TestResultStore; scope: this; this.down( '#iterationFilter' ).add( { xtype : 'rallyiterationcombobox', itemId : 'iterationComboBox', listeners : { change : this._queryForTestSets, ready : this._queryForTestSets, scope : this } } ); ; }, _queryForTestSets : function () { // if loading new iteration, destroy existing grids if ( this._summaryGrid !== undefined ) { this._summaryGrid.destroy(); this._Grid.destroy(); this._Grid2.destroy(); } TestSetStore = Ext.create( 'Rally.data.WsapiDataStore', { model : 'TestSet', autoLoad : true, storeId : 'TestSetStorer', context : { projectScopeUp : false, projectScopeDown : true }, filters : [ { property : 'Project', operator : '=', value : this.getContext().getDataContext().project }, { property : 'Iteration.Name', operator : '=', value : this.down( '#iterationComboBox' ).getRecord().data.Name } ], fetch : [ 'FormattedID', 'Name', 'TestCases', 'ObjectID', 'Project' ], limit : 10000, listeners : { load : function ( store, data, success ) { this._queryForTestResults( store, data ) }, scope : this } } ); }, });
App.js
// This App is supposed to find Test Sets and then list the Test Cases within them // // // //A new comment is added // // Verify connector function // Prepare to add pull requests // // //This a Test of vcs connector 2.0.5 // //Creating a change in the code // //Her we go again // // // Test the logistics // A change for the better // Added by JC // Ext.define('CustomApp', { extend: 'Rally.app.App', componentCls: 'app', items:{ html:'<a href="https://help.rallydev.com/apps/2.0rc3/doc/">App SDK 2.0rc3 Docs</a>'}, launch: function() { var deStore; var panel1 = Ext.create( 'Ext.panel.Panel', { layout : { type : 'hbox', // Arrange child items vertically align : 'middle', // Each takes up full width }, width : '100%', bodyPadding : 10, bodyStyle : { background : '#9A9494', }, items : [ { xtype : 'container', itemId : 'iterationFilter' }, { xtype : 'rallybutton', text : 'Print Summary', handler : function () { this._printSummary(); }, style : { marginRight : '10px', marginLeft : '10px' }, // flex:'1', scope : this } /* * { xtype:'rallybutton', text: 'Print Defects', handler: function() { this._printDefects(); }, style: { marginLeft: '10px' }, * * flex:'1', scope:this } */ ] } ); this.add( panel1 ); var panel2 = Ext.create( 'Ext.panel.Panel', { layout : 'vbox', width : '100%', bodyPadding : 10, bodyStyle : { background : '#9A9494', }, items : [ { xtype : 'container', layout : 'accordion', itemId : 'testStatus', width : '100%', height : 500 } ] } ); this.add( panel2 ); this._testSummary = []; this._testResultList = []; this._testSetTestList = []; var TestSetStore; var TestResultStore; scope: this; this.down( '#iterationFilter' ).add( { xtype : 'rallyiterationcombobox', itemId : 'iterationComboBox', listeners : { change : this._queryForTestSets, ready : this._queryForTestSets, scope : this } } ); ; }, _queryForTestSets : function () { // if loading new iteration, destroy existing grids if ( this._summaryGrid !== undefined ) { this._summaryGrid.destroy(); this._Grid.destroy(); this._Grid2.destroy(); } TestSetStore = Ext.create( 'Rally.data.WsapiDataStore', { model : 'TestSet', autoLoad : true, storeId : 'TestSetStorer', context : { projectScopeUp : false, projectScopeDown : true }, filters : [ { property : 'Project', operator : '=', value : this.getContext().getDataContext().project }, { property : 'Iteration.Name', operator : '=', value : this.down( '#iterationComboBox' ).getRecord().data.Name } ], fetch : [ 'FormattedID', 'Name', 'TestCases', 'ObjectID', 'Project' ], limit : 10000, listeners : { load : function ( store, data, success ) { this._queryForTestResults( store, data ) }, scope : this } } ); }, });
US99: Purchase Your Items Task-Url: https://rally1.rallydev.com/slm/detail/ar/335708299808 This change should kick off a build
App.js
US99: Purchase Your Items
<ide><path>pp.js <ide> // <ide> //Creating a change in the code <ide> // <del>//Her we go again <del>// <del>// <ide> // Test the logistics <ide> <ide> // A change for the better <ide> // Added by JC <del> <add>// <ide> // <ide> Ext.define('CustomApp', { <ide> extend: 'Rally.app.App',
Java
agpl-3.0
26a0aa2a7a709c0998c5b755ffd4d77c235f42c8
0
exomiser/Exomiser,exomiser/Exomiser
/* * The Exomiser - A tool to annotate and prioritize genomic variants * * Copyright (c) 2016-2018 Queen Mary University of London. * Copyright (c) 2012-2016 Charité Universitätsmedizin Berlin and Genome Research Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.monarchinitiative.exomiser.core.analysis.util; import com.google.common.collect.ImmutableMap; import de.charite.compbio.jannovar.mendel.ModeOfInheritance; import de.charite.compbio.jannovar.mendel.SubModeOfInheritance; import org.junit.Test; import java.util.Map; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; /** * @author Jules Jacobsen <[email protected]> */ public class InheritanceModeMaxFrequenciesTest { @Test public void defaultModeOfInheritanceValues() { InheritanceModeMaxFrequencies instance = InheritanceModeMaxFrequencies.defaultValues(); float defaultDominantFreq = 0.1f; assertThat(instance.getMaxFreqForMode(ModeOfInheritance.AUTOSOMAL_DOMINANT), equalTo(defaultDominantFreq)); assertThat(instance.getMaxFreqForMode(ModeOfInheritance.X_DOMINANT), equalTo(defaultDominantFreq)); float defaultRecessiveFreq = 2.0f; assertThat(instance.getMaxFreqForMode(ModeOfInheritance.AUTOSOMAL_RECESSIVE), equalTo(defaultRecessiveFreq)); assertThat(instance.getMaxFreqForMode(ModeOfInheritance.X_RECESSIVE), equalTo(defaultRecessiveFreq)); float defaultMitoFreq = 0.2f; assertThat(instance.getMaxFreqForMode(ModeOfInheritance.MITOCHONDRIAL), equalTo(defaultMitoFreq)); assertThat(instance.getMaxFreqForMode(ModeOfInheritance.ANY), equalTo(Float.MAX_VALUE)); } @Test public void defaultSubModeOfInheritanceValues() { InheritanceModeMaxFrequencies instance = InheritanceModeMaxFrequencies.defaultValues(); float defaultDominantFreq = 0.1f; assertThat(instance.getMaxFreqForSubMode(SubModeOfInheritance.AUTOSOMAL_DOMINANT), equalTo(defaultDominantFreq)); assertThat(instance.getMaxFreqForSubMode(SubModeOfInheritance.X_DOMINANT), equalTo(defaultDominantFreq)); float defaultCompHetRecessiveFreq = 2.0f; assertThat(instance.getMaxFreqForSubMode(SubModeOfInheritance.AUTOSOMAL_RECESSIVE_COMP_HET), equalTo(defaultCompHetRecessiveFreq)); assertThat(instance.getMaxFreqForSubMode(SubModeOfInheritance.X_RECESSIVE_COMP_HET), equalTo(defaultCompHetRecessiveFreq)); //This should be changed float defaultHomAltRecessiveFreq = 2.0f; assertThat(instance.getMaxFreqForSubMode(SubModeOfInheritance.AUTOSOMAL_RECESSIVE_HOM_ALT), equalTo(defaultHomAltRecessiveFreq)); assertThat(instance.getMaxFreqForSubMode(SubModeOfInheritance.X_RECESSIVE_HOM_ALT), equalTo(defaultHomAltRecessiveFreq)); float defaultMitoFreq = 0.2f; assertThat(instance.getMaxFreqForSubMode(SubModeOfInheritance.MITOCHONDRIAL), equalTo(defaultMitoFreq)); assertThat(instance.getMaxFreqForSubMode(SubModeOfInheritance.ANY), equalTo(Float.MAX_VALUE)); } @Test(expected = NullPointerException.class) public void throwsExceptionWithNullInput() { InheritanceModeMaxFrequencies.of(null); } @Test(expected = IllegalArgumentException.class) public void throwsExceptionWithNonPercentageValue() { //check upper bounds Map<SubModeOfInheritance, Float> tooHigh = ImmutableMap.of(SubModeOfInheritance.AUTOSOMAL_DOMINANT, 101f); InheritanceModeMaxFrequencies.of(tooHigh); //check lower bounds Map<SubModeOfInheritance, Float> tooLow = ImmutableMap.of(SubModeOfInheritance.AUTOSOMAL_DOMINANT, -1f); InheritanceModeMaxFrequencies.of(tooLow); } @Test public void testMaxAndMinValues() { //check max Map<SubModeOfInheritance, Float> max = ImmutableMap.of(SubModeOfInheritance.AUTOSOMAL_DOMINANT, 100f); InheritanceModeMaxFrequencies.of(max); //check min Map<SubModeOfInheritance, Float> min = ImmutableMap.of(SubModeOfInheritance.AUTOSOMAL_DOMINANT, 0f); InheritanceModeMaxFrequencies.of(min); } @Test public void userDefinedFrequencyCutoffs() { Map<SubModeOfInheritance, Float> userDefinedThresholds = ImmutableMap.of(SubModeOfInheritance.AUTOSOMAL_RECESSIVE_COMP_HET, 1f); //should we allow this to happen? If people don't define the COMP_HET and HOM_ALT then the recessive modes won't InheritanceModeMaxFrequencies instance = InheritanceModeMaxFrequencies.of(userDefinedThresholds); assertThat(instance.getMaxFreqForSubMode(SubModeOfInheritance.AUTOSOMAL_RECESSIVE_COMP_HET), equalTo(1f)); assertThat(instance.getMaxFreqForMode(ModeOfInheritance.AUTOSOMAL_RECESSIVE), equalTo(1f)); //non-user-defined assertThat(instance.getMaxFreqForSubMode(SubModeOfInheritance.AUTOSOMAL_RECESSIVE_HOM_ALT), equalTo(Float.MAX_VALUE)); } @Test public void testToString() { System.out.println(InheritanceModeMaxFrequencies.defaultValues()); } }
exomiser-core/src/test/java/org/monarchinitiative/exomiser/core/analysis/util/InheritanceModeMaxFrequenciesTest.java
/* * The Exomiser - A tool to annotate and prioritize genomic variants * * Copyright (c) 2016-2018 Queen Mary University of London. * Copyright (c) 2012-2016 Charité Universitätsmedizin Berlin and Genome Research Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.monarchinitiative.exomiser.core.analysis.util; import de.charite.compbio.jannovar.mendel.ModeOfInheritance; import de.charite.compbio.jannovar.mendel.SubModeOfInheritance; import org.junit.Test; import java.util.EnumMap; import java.util.HashMap; import java.util.Map; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; /** * @author Jules Jacobsen <[email protected]> */ public class InheritanceModeMaxFrequenciesTest { @Test public void defaultModeOfInheritanceValues() { InheritanceModeMaxFrequencies instance = InheritanceModeMaxFrequencies.defaultValues(); float defaultDominantFreq = 0.1f; assertThat(instance.getMaxFreqForMode(ModeOfInheritance.AUTOSOMAL_DOMINANT), equalTo(defaultDominantFreq)); assertThat(instance.getMaxFreqForMode(ModeOfInheritance.X_DOMINANT), equalTo(defaultDominantFreq)); float defaultRecessiveFreq = 2.0f; assertThat(instance.getMaxFreqForMode(ModeOfInheritance.AUTOSOMAL_RECESSIVE), equalTo(defaultRecessiveFreq)); assertThat(instance.getMaxFreqForMode(ModeOfInheritance.X_RECESSIVE), equalTo(defaultRecessiveFreq)); float defaultMitoFreq = 0.2f; assertThat(instance.getMaxFreqForMode(ModeOfInheritance.MITOCHONDRIAL), equalTo(defaultMitoFreq)); assertThat(instance.getMaxFreqForMode(ModeOfInheritance.ANY), equalTo(Float.MAX_VALUE)); } @Test public void defaultSubModeOfInheritanceValues() { InheritanceModeMaxFrequencies instance = InheritanceModeMaxFrequencies.defaultValues(); float defaultDominantFreq = 0.1f; assertThat(instance.getMaxFreqForSubMode(SubModeOfInheritance.AUTOSOMAL_DOMINANT), equalTo(defaultDominantFreq)); assertThat(instance.getMaxFreqForSubMode(SubModeOfInheritance.X_DOMINANT), equalTo(defaultDominantFreq)); float defaultCompHetRecessiveFreq = 2.0f; assertThat(instance.getMaxFreqForSubMode(SubModeOfInheritance.AUTOSOMAL_RECESSIVE_COMP_HET), equalTo(defaultCompHetRecessiveFreq)); assertThat(instance.getMaxFreqForSubMode(SubModeOfInheritance.X_RECESSIVE_COMP_HET), equalTo(defaultCompHetRecessiveFreq)); //This should be changed float defaultHomAltRecessiveFreq = 2.0f; assertThat(instance.getMaxFreqForSubMode(SubModeOfInheritance.AUTOSOMAL_RECESSIVE_HOM_ALT), equalTo(defaultHomAltRecessiveFreq)); assertThat(instance.getMaxFreqForSubMode(SubModeOfInheritance.X_RECESSIVE_HOM_ALT), equalTo(defaultHomAltRecessiveFreq)); float defaultMitoFreq = 0.2f; assertThat(instance.getMaxFreqForSubMode(SubModeOfInheritance.MITOCHONDRIAL), equalTo(defaultMitoFreq)); assertThat(instance.getMaxFreqForSubMode(SubModeOfInheritance.ANY), equalTo(Float.MAX_VALUE)); } @Test(expected = NullPointerException.class) public void throwsExceptionWithNullInput() { InheritanceModeMaxFrequencies.of(null); } @Test(expected = IllegalArgumentException.class) public void throwsExceptionWithNonPercentageValue() { //check upper bounds Map<SubModeOfInheritance, Float> tooHigh = new HashMap<>(); tooHigh.put(SubModeOfInheritance.AUTOSOMAL_DOMINANT, 101f); InheritanceModeMaxFrequencies.of(tooHigh); //check lower bounds Map<SubModeOfInheritance, Float> toolow = new HashMap<>(); tooHigh.put(SubModeOfInheritance.AUTOSOMAL_DOMINANT, -1f); InheritanceModeMaxFrequencies.of(toolow); } @Test public void testMaxAndMinValues() { //check max Map<SubModeOfInheritance, Float> max = new HashMap<>(); max.put(SubModeOfInheritance.AUTOSOMAL_DOMINANT, 100f); InheritanceModeMaxFrequencies.of(max); //check min Map<SubModeOfInheritance, Float> min = new HashMap<>(); max.put(SubModeOfInheritance.AUTOSOMAL_DOMINANT, 0f); InheritanceModeMaxFrequencies.of(min); } @Test public void userDefinedFrequencyCutoffs() { Map<SubModeOfInheritance, Float> userDefinedThresholds = new EnumMap<>(SubModeOfInheritance.class); userDefinedThresholds.put(SubModeOfInheritance.AUTOSOMAL_RECESSIVE_COMP_HET, 1f); //should we allow this to happen? If people don't define the COMP_HET and HOM_ALT then the recessive modes won't InheritanceModeMaxFrequencies instance = InheritanceModeMaxFrequencies.of(userDefinedThresholds); assertThat(instance.getMaxFreqForSubMode(SubModeOfInheritance.AUTOSOMAL_RECESSIVE_COMP_HET), equalTo(1f)); assertThat(instance.getMaxFreqForMode(ModeOfInheritance.AUTOSOMAL_RECESSIVE), equalTo(1f)); //non-user-defined assertThat(instance.getMaxFreqForSubMode(SubModeOfInheritance.AUTOSOMAL_RECESSIVE_HOM_ALT), equalTo(Float.MAX_VALUE)); } @Test public void testToString() { System.out.println(InheritanceModeMaxFrequencies.defaultValues()); } }
Tidy-up InheritanceModeMaxFrequenciesTest
exomiser-core/src/test/java/org/monarchinitiative/exomiser/core/analysis/util/InheritanceModeMaxFrequenciesTest.java
Tidy-up InheritanceModeMaxFrequenciesTest
<ide><path>xomiser-core/src/test/java/org/monarchinitiative/exomiser/core/analysis/util/InheritanceModeMaxFrequenciesTest.java <ide> <ide> package org.monarchinitiative.exomiser.core.analysis.util; <ide> <add>import com.google.common.collect.ImmutableMap; <ide> import de.charite.compbio.jannovar.mendel.ModeOfInheritance; <ide> import de.charite.compbio.jannovar.mendel.SubModeOfInheritance; <ide> import org.junit.Test; <ide> <del>import java.util.EnumMap; <del>import java.util.HashMap; <ide> import java.util.Map; <ide> <ide> import static org.hamcrest.CoreMatchers.equalTo; <ide> @Test(expected = IllegalArgumentException.class) <ide> public void throwsExceptionWithNonPercentageValue() { <ide> //check upper bounds <del> Map<SubModeOfInheritance, Float> tooHigh = new HashMap<>(); <del> tooHigh.put(SubModeOfInheritance.AUTOSOMAL_DOMINANT, 101f); <del> <add> Map<SubModeOfInheritance, Float> tooHigh = ImmutableMap.of(SubModeOfInheritance.AUTOSOMAL_DOMINANT, 101f); <ide> InheritanceModeMaxFrequencies.of(tooHigh); <ide> <ide> //check lower bounds <del> Map<SubModeOfInheritance, Float> toolow = new HashMap<>(); <del> tooHigh.put(SubModeOfInheritance.AUTOSOMAL_DOMINANT, -1f); <del> <del> InheritanceModeMaxFrequencies.of(toolow); <add> Map<SubModeOfInheritance, Float> tooLow = ImmutableMap.of(SubModeOfInheritance.AUTOSOMAL_DOMINANT, -1f); <add> InheritanceModeMaxFrequencies.of(tooLow); <ide> } <ide> <ide> @Test <ide> public void testMaxAndMinValues() { <ide> //check max <del> Map<SubModeOfInheritance, Float> max = new HashMap<>(); <del> max.put(SubModeOfInheritance.AUTOSOMAL_DOMINANT, 100f); <del> <add> Map<SubModeOfInheritance, Float> max = ImmutableMap.of(SubModeOfInheritance.AUTOSOMAL_DOMINANT, 100f); <ide> InheritanceModeMaxFrequencies.of(max); <ide> <ide> //check min <del> Map<SubModeOfInheritance, Float> min = new HashMap<>(); <del> max.put(SubModeOfInheritance.AUTOSOMAL_DOMINANT, 0f); <del> <add> Map<SubModeOfInheritance, Float> min = ImmutableMap.of(SubModeOfInheritance.AUTOSOMAL_DOMINANT, 0f); <ide> InheritanceModeMaxFrequencies.of(min); <ide> } <ide> <ide> @Test <ide> public void userDefinedFrequencyCutoffs() { <del> Map<SubModeOfInheritance, Float> userDefinedThresholds = new EnumMap<>(SubModeOfInheritance.class); <del> userDefinedThresholds.put(SubModeOfInheritance.AUTOSOMAL_RECESSIVE_COMP_HET, 1f); <add> Map<SubModeOfInheritance, Float> userDefinedThresholds = ImmutableMap.of(SubModeOfInheritance.AUTOSOMAL_RECESSIVE_COMP_HET, 1f); <ide> //should we allow this to happen? If people don't define the COMP_HET and HOM_ALT then the recessive modes won't <ide> InheritanceModeMaxFrequencies instance = InheritanceModeMaxFrequencies.of(userDefinedThresholds); <ide>
Java
unknown
error: pathspec 'Sato/memento/Caretaker.java' did not match any file(s) known to git
e1002b695b01adde2e27c1239bc7a3f2c43030ee
1
tectijuana/javapdd,tectijuana/pddjava
import java.util.List; import java.util.ArrayList; class Caretaker { public static void main(String[] args) { List<Originator.Memento> savedStates = new ArrayList<Originator.Memento>(); Originator originator = new Originator(); originator.set("State1"); originator.set("State2"); savedStates.add(originator.saveToMemento()); originator.set("State3"); // We can request multiple mementos, and choose which one to roll back to. savedStates.add(originator.saveToMemento()); originator.set("State4"); originator.restoreFromMemento(savedStates.get(1)); } }
Sato/memento/Caretaker.java
Create Caretaker.java
Sato/memento/Caretaker.java
Create Caretaker.java
<ide><path>ato/memento/Caretaker.java <add>import java.util.List; <add>import java.util.ArrayList; <add> <add>class Caretaker { <add> public static void main(String[] args) { <add> List<Originator.Memento> savedStates = new ArrayList<Originator.Memento>(); <add> <add> Originator originator = new Originator(); <add> originator.set("State1"); <add> originator.set("State2"); <add> savedStates.add(originator.saveToMemento()); <add> originator.set("State3"); <add> // We can request multiple mementos, and choose which one to roll back to. <add> savedStates.add(originator.saveToMemento()); <add> originator.set("State4"); <add> <add> originator.restoreFromMemento(savedStates.get(1)); <add> } <add>}
Java
apache-2.0
624ea6ed636f74b4b1f48e5cb9d710792be23e03
0
PasaLab/tachyon,Alluxio/alluxio,maboelhassan/alluxio,jsimsa/alluxio,WilliamZapata/alluxio,maboelhassan/alluxio,calvinjia/tachyon,Alluxio/alluxio,Alluxio/alluxio,bf8086/alluxio,Reidddddd/mo-alluxio,ChangerYoung/alluxio,uronce-cc/alluxio,riversand963/alluxio,wwjiang007/alluxio,riversand963/alluxio,PasaLab/tachyon,aaudiber/alluxio,ShailShah/alluxio,EvilMcJerkface/alluxio,Reidddddd/alluxio,jswudi/alluxio,Reidddddd/alluxio,maboelhassan/alluxio,Alluxio/alluxio,uronce-cc/alluxio,wwjiang007/alluxio,ChangerYoung/alluxio,wwjiang007/alluxio,aaudiber/alluxio,calvinjia/tachyon,maobaolong/alluxio,EvilMcJerkface/alluxio,riversand963/alluxio,Reidddddd/alluxio,bf8086/alluxio,Alluxio/alluxio,EvilMcJerkface/alluxio,maobaolong/alluxio,maobaolong/alluxio,maobaolong/alluxio,calvinjia/tachyon,wwjiang007/alluxio,aaudiber/alluxio,yuluo-ding/alluxio,maboelhassan/alluxio,calvinjia/tachyon,ChangerYoung/alluxio,Reidddddd/mo-alluxio,calvinjia/tachyon,wwjiang007/alluxio,madanadit/alluxio,jswudi/alluxio,aaudiber/alluxio,Reidddddd/mo-alluxio,Alluxio/alluxio,EvilMcJerkface/alluxio,apc999/alluxio,PasaLab/tachyon,uronce-cc/alluxio,apc999/alluxio,WilliamZapata/alluxio,bf8086/alluxio,ShailShah/alluxio,ShailShah/alluxio,maobaolong/alluxio,aaudiber/alluxio,apc999/alluxio,bf8086/alluxio,jswudi/alluxio,Reidddddd/alluxio,calvinjia/tachyon,PasaLab/tachyon,WilliamZapata/alluxio,jsimsa/alluxio,apc999/alluxio,Alluxio/alluxio,maobaolong/alluxio,wwjiang007/alluxio,ShailShah/alluxio,madanadit/alluxio,apc999/alluxio,EvilMcJerkface/alluxio,riversand963/alluxio,Alluxio/alluxio,Alluxio/alluxio,uronce-cc/alluxio,uronce-cc/alluxio,riversand963/alluxio,riversand963/alluxio,madanadit/alluxio,ChangerYoung/alluxio,jsimsa/alluxio,Reidddddd/mo-alluxio,Reidddddd/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,jswudi/alluxio,EvilMcJerkface/alluxio,apc999/alluxio,yuluo-ding/alluxio,ChangerYoung/alluxio,madanadit/alluxio,ChangerYoung/alluxio,Reidddddd/alluxio,PasaLab/tachyon,Reidddddd/alluxio,yuluo-ding/alluxio,maboelhassan/alluxio,jsimsa/alluxio,madanadit/alluxio,uronce-cc/alluxio,maobaolong/alluxio,jswudi/alluxio,yuluo-ding/alluxio,madanadit/alluxio,aaudiber/alluxio,Reidddddd/mo-alluxio,Alluxio/alluxio,WilliamZapata/alluxio,PasaLab/tachyon,EvilMcJerkface/alluxio,madanadit/alluxio,bf8086/alluxio,ShailShah/alluxio,ShailShah/alluxio,PasaLab/tachyon,bf8086/alluxio,maobaolong/alluxio,wwjiang007/alluxio,maobaolong/alluxio,aaudiber/alluxio,calvinjia/tachyon,jsimsa/alluxio,bf8086/alluxio,yuluo-ding/alluxio,calvinjia/tachyon,Reidddddd/mo-alluxio,WilliamZapata/alluxio,jswudi/alluxio,maobaolong/alluxio,apc999/alluxio,maboelhassan/alluxio,maboelhassan/alluxio,wwjiang007/alluxio,yuluo-ding/alluxio,madanadit/alluxio,EvilMcJerkface/alluxio,bf8086/alluxio,jsimsa/alluxio,WilliamZapata/alluxio
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the “License”). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.worker.file; import alluxio.AlluxioURI; import alluxio.Configuration; import alluxio.exception.ExceptionMessage; import alluxio.exception.FileAlreadyExistsException; import alluxio.exception.FileDoesNotExistException; import alluxio.underfs.UnderFileSystem; import alluxio.util.IdUtils; import alluxio.util.io.PathUtils; import alluxio.worker.WorkerContext; import com.google.common.base.Preconditions; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; import javax.annotation.concurrent.ThreadSafe; /** * Handles writes to the under file system. Manages open output streams to Under File Systems. * Individual streams should only be used by one client. Each instance keeps its own state of * temporary file ids to open streams. */ @ThreadSafe public final class UnderFileSystemManager { /** * An object which generates input streams to under file system files given a position. This * class does not manage the life cycles of the generated streams and it is up to the caller to * close the streams when appropriate. */ private class UnderFileSystemInputStream { /** Configuration to use for this stream. */ private final Configuration mConfiguration; /** The string form of the uri to the file in the under file system */ private final String mUri; private UnderFileSystemInputStream(AlluxioURI ufsUri, Configuration conf) { mUri = ufsUri.toString(); mConfiguration = conf; } /** * Opens a new input stream to the file this object references. The new stream will be at the * specified position when it is returned to the caller. The caller is responsible for * closing the stream. * * @param position the absolute position in the file to start the stream at * @return an input stream to the file starting at the specified position * @throws IOException if an error occurs when interacting with the UFS */ private InputStream openAtPosition(long position) throws IOException { UnderFileSystem ufs = UnderFileSystem.get(mUri, mConfiguration); InputStream stream = ufs.open(mUri); if (position != stream.skip(position)) { throw new IOException(ExceptionMessage.FAILED_SKIP.getMessage(position)); } return stream; } } /** * A wrapper around the output stream to the under file system. This class handles writing the * data to a temporary file. When the stream is closed, the temporary file will attempt to be * renamed to the final file path. This stream guarantees the temporary file will be cleaned up * when close or cancel is called. */ // TODO(calvin): This can be defined by the UnderFileSystem private final class UnderFileSystemOutputStream { /** Configuration to use for this stream. */ private final Configuration mConfiguration; /** Underlying stream to the under file system file. */ private final OutputStream mStream; /** String form of the final uri to write to in the under file system. */ private final String mUri; /** String form of the temporary uri to write to in the under file system. */ private final String mTemporaryUri; private UnderFileSystemOutputStream(AlluxioURI ufsUri, Configuration conf) throws FileAlreadyExistsException, IOException { mConfiguration = Preconditions.checkNotNull(conf); mUri = Preconditions.checkNotNull(ufsUri).toString(); mTemporaryUri = PathUtils.temporaryFileName(IdUtils.getRandomNonNegativeLong(), mUri); UnderFileSystem ufs = UnderFileSystem.get(mUri, mConfiguration); if (ufs.exists(mUri)) { throw new FileAlreadyExistsException(ExceptionMessage.FAILED_UFS_CREATE.getMessage(mUri)); } mStream = ufs.create(mTemporaryUri); } /** * Closes the temporary file and deletes it. This object should be discarded after this call. * * @throws IOException if an error occurs during the under file system operation */ private void cancel() throws IOException { mStream.close(); UnderFileSystem ufs = UnderFileSystem.get(mUri, mConfiguration); // TODO(calvin): Log a warning if the delete fails ufs.delete(mTemporaryUri, false); } /** * Closes the temporary file and attempts to promote it to the final file path. If the final * path already exists, the stream is canceled instead. * * @throws IOException if an error occurs during the under file system operation */ private void complete() throws IOException { mStream.close(); UnderFileSystem ufs = UnderFileSystem.get(mUri, mConfiguration); if (!ufs.rename(mTemporaryUri, mUri)) { // TODO(calvin): Log a warning if the delete fails ufs.delete(mTemporaryUri, false); } } /** * @return the wrapped output stream to the under file system file */ private OutputStream getStream() { return mStream; } } /** A random id generator for worker file ids. */ private AtomicLong mIdGenerator; /** Map of worker file ids to open under file system input streams. */ private ConcurrentMap<Long, UnderFileSystemInputStream> mInputStreams; /** Map of worker file ids to open under file system output streams. */ private ConcurrentMap<Long, UnderFileSystemOutputStream> mOutputStreams; /** * Creates a new under file system manager. Stream ids are unique to each under file system * manager. */ public UnderFileSystemManager() { mIdGenerator = new AtomicLong(IdUtils.getRandomNonNegativeLong()); mInputStreams = new ConcurrentHashMap<>(); mOutputStreams = new ConcurrentHashMap<>(); } /** * Creates a {@link UnderFileSystemOutputStream} for the given file path and adds it to the * open streams map keyed with the returned worker file id. * * @param ufsUri the path to create in the under file system * @return the worker file id which should be used to reference the open stream * @throws FileAlreadyExistsException if the under file system path already exists * @throws IOException if an error occurs when operating on the under file system */ public long createFile(AlluxioURI ufsUri) throws FileAlreadyExistsException, IOException { UnderFileSystemOutputStream stream = new UnderFileSystemOutputStream(ufsUri, WorkerContext.getConf()); long workerFileId = mIdGenerator.getAndIncrement(); mOutputStreams.put(workerFileId, stream); return workerFileId; } /** * Cancels the open stream associated with the given worker file id. This will close the open * stream. * * @param tempUfsFileId the worker id referencing an open file in the under file system * @throws FileDoesNotExistException if the worker file id is not valid * @throws IOException if an error occurs when operating on the under file system */ public void cancelFile(long tempUfsFileId) throws FileDoesNotExistException, IOException { UnderFileSystemOutputStream stream = mOutputStreams.remove(tempUfsFileId); if (stream != null) { stream.cancel(); } else { throw new FileDoesNotExistException( ExceptionMessage.BAD_WORKER_FILE_ID.getMessage(tempUfsFileId)); } } /** * Closes an open input stream associated with the given temporary ufs file id. The temporary * ufs file id will be invalid after this is called. * * @param tempUfsFileId the temporary ufs file id * @throws IOException if an error occurs when operating on the under file system */ public void closeFile(long tempUfsFileId) throws IOException { mInputStreams.remove(tempUfsFileId); } /** * Completes an open stream associated with the given worker file id. This will close the open * stream. * * @param tempUfsFileId the worker id referencing an open file in the under file system * @throws FileDoesNotExistException if the worker file id is not valid * @throws IOException if an error occurs when operating on the under file system */ public void completeFile(long tempUfsFileId) throws FileDoesNotExistException, IOException { UnderFileSystemOutputStream stream = mOutputStreams.remove(tempUfsFileId); if (stream != null) { stream.complete(); } else { throw new FileDoesNotExistException( ExceptionMessage.BAD_WORKER_FILE_ID.getMessage(tempUfsFileId)); } } /** * @param tempUfsFileId the temporary ufs file id * @return the input stream to read from this file */ public InputStream getInputStreamAtPosition(long tempUfsFileId, long position) throws IOException { return mInputStreams.get(tempUfsFileId).openAtPosition(position); } /** * @param tempUfsFileId the temporary ufs file id * @return the output stream to write to this file */ public OutputStream getOutputStream(long tempUfsFileId) { return mOutputStreams.get(tempUfsFileId).getStream(); } /** * Opens a file from the under file system and associates it with a worker file id. * * @param ufsUri the path to create in the under file system * @return the worker file id which should be used to reference the open stream * @throws IOException if an error occurs when operating on the under file system */ public long openFile(AlluxioURI ufsUri) throws IOException { UnderFileSystemInputStream stream = new UnderFileSystemInputStream(ufsUri, WorkerContext.getConf()); long workerFileId = mIdGenerator.getAndIncrement(); mInputStreams.put(workerFileId, stream); return workerFileId; } }
core/server/src/main/java/alluxio/worker/file/UnderFileSystemManager.java
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the “License”). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.worker.file; import alluxio.AlluxioURI; import alluxio.Configuration; import alluxio.exception.ExceptionMessage; import alluxio.exception.FileAlreadyExistsException; import alluxio.exception.FileDoesNotExistException; import alluxio.underfs.UnderFileSystem; import alluxio.util.IdUtils; import alluxio.util.io.PathUtils; import alluxio.worker.WorkerContext; import com.google.common.base.Preconditions; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; import javax.annotation.concurrent.ThreadSafe; /** * Handles writes to the under file system. Manages open output streams to Under File Systems. * Individual streams should only be used by one client. Each instance keeps its own state of * temporary file ids to open streams. */ @ThreadSafe public final class UnderFileSystemManager { /** * A wrapper around the output stream to the under file system. This class handles writing the * data to a temporary file. When the stream is closed, the temporary file will attempt to be * renamed to the final file path. This stream guarantees the temporary file will be cleaned up * when close or cancel is called. */ // TODO(calvin): This can be defined by the UnderFileSystem private final class UnderFileSystemOutputStream { /** Configuration to use for this stream. */ private final Configuration mConf; /** Underlying stream to the under file system file. */ private final OutputStream mStream; /** String form of the final uri to write to in the under file system. */ private final String mUri; /** String form of the temporary uri to write to in the under file system. */ private final String mTemporaryUri; private UnderFileSystemOutputStream(AlluxioURI ufsUri, Configuration conf) throws FileAlreadyExistsException, IOException { mConf = Preconditions.checkNotNull(conf); mUri = Preconditions.checkNotNull(ufsUri).toString(); mTemporaryUri = PathUtils.temporaryFileName(IdUtils.getRandomNonNegativeLong(), mUri); UnderFileSystem ufs = UnderFileSystem.get(mUri, mConf); if (ufs.exists(mUri)) { throw new FileAlreadyExistsException(ExceptionMessage.FAILED_UFS_CREATE.getMessage(mUri)); } mStream = ufs.create(mTemporaryUri); } /** * Closes the temporary file and deletes it. This object should be discarded after this call. * * @throws IOException if an error occurs during the under file system operation */ private void cancel() throws IOException { mStream.close(); UnderFileSystem ufs = UnderFileSystem.get(mUri, mConf); // TODO(calvin): Log a warning if the delete fails ufs.delete(mTemporaryUri, false); } /** * Closes the temporary file and attempts to promote it to the final file path. If the final * path already exists, the stream is canceled instead. * * @throws IOException if an error occurs during the under file system operation */ private void complete() throws IOException { mStream.close(); UnderFileSystem ufs = UnderFileSystem.get(mUri, mConf); if (!ufs.rename(mTemporaryUri, mUri)) { // TODO(calvin): Log a warning if the delete fails ufs.delete(mTemporaryUri, false); } } /** * @return the wrapped output stream to the under file system file */ private OutputStream getStream() { return mStream; } } /** A random id generator for worker file ids. */ private AtomicLong mIdGenerator; /** Map of worker file ids to open under file system input streams. */ private ConcurrentMap<Long, UnderFileSystemInputStream> mInputStreams; /** Map of worker file ids to open under file system output streams. */ private ConcurrentMap<Long, UnderFileSystemOutputStream> mOutputStreams; /** * Creates a new under file system manager. Stream ids are unique to each under file system * manager. */ public UnderFileSystemManager() { mIdGenerator = new AtomicLong(IdUtils.getRandomNonNegativeLong()); mInputStreams = new ConcurrentHashMap<>(); mOutputStreams = new ConcurrentHashMap<>(); } /** * Creates a {@link UnderFileSystemOutputStream} for the given file path and adds it to the * open streams map keyed with the returned worker file id. * * @param ufsUri the path to create in the under file system * @return the worker file id which should be used to reference the open stream * @throws FileAlreadyExistsException if the under file system path already exists * @throws IOException if an error occurs when operating on the under file system */ public long createFile(AlluxioURI ufsUri) throws FileAlreadyExistsException, IOException { UnderFileSystemOutputStream stream = new UnderFileSystemOutputStream(ufsUri, WorkerContext.getConf()); long workerFileId = mIdGenerator.getAndIncrement(); mOutputStreams.put(workerFileId, stream); return workerFileId; } /** * Cancels the open stream associated with the given worker file id. This will close the open * stream. * * @param tempUfsFileId the worker id referencing an open file in the under file system * @throws FileDoesNotExistException if the worker file id is not valid * @throws IOException if an error occurs when operating on the under file system */ public void cancelFile(long tempUfsFileId) throws FileDoesNotExistException, IOException { UnderFileSystemOutputStream stream = mOutputStreams.remove(tempUfsFileId); if (stream != null) { stream.cancel(); } else { throw new FileDoesNotExistException( ExceptionMessage.BAD_WORKER_FILE_ID.getMessage(tempUfsFileId)); } } /** * Closes an open input stream associated with the given temporary ufs file id. The temporary * ufs file id will be invalid after this is called. * * @param tempUfsFileId the temporary ufs file id * @throws IOException if an error occurs when operating on the under file system */ public void closeFile(long tempUfsFileId) throws IOException { mInputStreams.remove(tempUfsFileId); } /** * Completes an open stream associated with the given worker file id. This will close the open * stream. * * @param tempUfsFileId the worker id referencing an open file in the under file system * @throws FileDoesNotExistException if the worker file id is not valid * @throws IOException if an error occurs when operating on the under file system */ public void completeFile(long tempUfsFileId) throws FileDoesNotExistException, IOException { UnderFileSystemOutputStream stream = mOutputStreams.remove(tempUfsFileId); if (stream != null) { stream.complete(); } else { throw new FileDoesNotExistException( ExceptionMessage.BAD_WORKER_FILE_ID.getMessage(tempUfsFileId)); } } /** * @param tempUfsFileId the temporary ufs file id * @return the input stream to read from this file */ public InputStream getInputStreamAtPosition(long tempUfsFileId, long position) throws IOException { return mInputStreams.get(tempUfsFileId).openAtPosition(position); } /** * @param tempUfsFileId the temporary ufs file id * @return the output stream to write to this file */ public OutputStream getOutputStream(long tempUfsFileId) { return mOutputStreams.get(tempUfsFileId).getStream(); } /** * Opens a file from the under file system and associates it with a worker file id. * * @param ufsUri the path to create in the under file system * @return the worker file id which should be used to reference the open stream * @throws IOException if an error occurs when operating on the under file system */ public long openFile(AlluxioURI ufsUri) throws IOException { UnderFileSystemInputStream stream = new UnderFileSystemInputStream(ufsUri, WorkerContext.getConf()); long workerFileId = mIdGenerator.getAndIncrement(); mInputStreams.put(workerFileId, stream); return workerFileId; } private class UnderFileSystemInputStream { private final String mUfsPath; private final Configuration mConfiguration; private UnderFileSystemInputStream(AlluxioURI ufsUri, Configuration conf) { mUfsPath = ufsUri.toString(); mConfiguration = conf; } private InputStream openAtPosition(long position) throws IOException { UnderFileSystem ufs = UnderFileSystem.get(mUfsPath, mConfiguration); InputStream stream = ufs.open(mUfsPath); if (position != stream.skip(position)) { throw new IOException(ExceptionMessage.FAILED_SKIP.getMessage(position)); } return stream; } } }
Clean up UFSManager.
core/server/src/main/java/alluxio/worker/file/UnderFileSystemManager.java
Clean up UFSManager.
<ide><path>ore/server/src/main/java/alluxio/worker/file/UnderFileSystemManager.java <ide> @ThreadSafe <ide> public final class UnderFileSystemManager { <ide> /** <add> * An object which generates input streams to under file system files given a position. This <add> * class does not manage the life cycles of the generated streams and it is up to the caller to <add> * close the streams when appropriate. <add> */ <add> private class UnderFileSystemInputStream { <add> /** Configuration to use for this stream. */ <add> private final Configuration mConfiguration; <add> /** The string form of the uri to the file in the under file system */ <add> private final String mUri; <add> <add> private UnderFileSystemInputStream(AlluxioURI ufsUri, Configuration conf) { <add> mUri = ufsUri.toString(); <add> mConfiguration = conf; <add> } <add> <add> /** <add> * Opens a new input stream to the file this object references. The new stream will be at the <add> * specified position when it is returned to the caller. The caller is responsible for <add> * closing the stream. <add> * <add> * @param position the absolute position in the file to start the stream at <add> * @return an input stream to the file starting at the specified position <add> * @throws IOException if an error occurs when interacting with the UFS <add> */ <add> private InputStream openAtPosition(long position) throws IOException { <add> UnderFileSystem ufs = UnderFileSystem.get(mUri, mConfiguration); <add> InputStream stream = ufs.open(mUri); <add> if (position != stream.skip(position)) { <add> throw new IOException(ExceptionMessage.FAILED_SKIP.getMessage(position)); <add> } <add> return stream; <add> } <add> } <add> <add> /** <ide> * A wrapper around the output stream to the under file system. This class handles writing the <ide> * data to a temporary file. When the stream is closed, the temporary file will attempt to be <ide> * renamed to the final file path. This stream guarantees the temporary file will be cleaned up <ide> // TODO(calvin): This can be defined by the UnderFileSystem <ide> private final class UnderFileSystemOutputStream { <ide> /** Configuration to use for this stream. */ <del> private final Configuration mConf; <add> private final Configuration mConfiguration; <ide> /** Underlying stream to the under file system file. */ <ide> private final OutputStream mStream; <ide> /** String form of the final uri to write to in the under file system. */ <ide> <ide> private UnderFileSystemOutputStream(AlluxioURI ufsUri, Configuration conf) <ide> throws FileAlreadyExistsException, IOException { <del> mConf = Preconditions.checkNotNull(conf); <add> mConfiguration = Preconditions.checkNotNull(conf); <ide> mUri = Preconditions.checkNotNull(ufsUri).toString(); <ide> mTemporaryUri = PathUtils.temporaryFileName(IdUtils.getRandomNonNegativeLong(), mUri); <del> UnderFileSystem ufs = UnderFileSystem.get(mUri, mConf); <add> UnderFileSystem ufs = UnderFileSystem.get(mUri, mConfiguration); <ide> if (ufs.exists(mUri)) { <ide> throw new FileAlreadyExistsException(ExceptionMessage.FAILED_UFS_CREATE.getMessage(mUri)); <ide> } <ide> */ <ide> private void cancel() throws IOException { <ide> mStream.close(); <del> UnderFileSystem ufs = UnderFileSystem.get(mUri, mConf); <add> UnderFileSystem ufs = UnderFileSystem.get(mUri, mConfiguration); <ide> // TODO(calvin): Log a warning if the delete fails <ide> ufs.delete(mTemporaryUri, false); <ide> } <ide> */ <ide> private void complete() throws IOException { <ide> mStream.close(); <del> UnderFileSystem ufs = UnderFileSystem.get(mUri, mConf); <add> UnderFileSystem ufs = UnderFileSystem.get(mUri, mConfiguration); <ide> if (!ufs.rename(mTemporaryUri, mUri)) { <ide> // TODO(calvin): Log a warning if the delete fails <ide> ufs.delete(mTemporaryUri, false); <ide> mInputStreams.put(workerFileId, stream); <ide> return workerFileId; <ide> } <del> <del> private class UnderFileSystemInputStream { <del> private final String mUfsPath; <del> private final Configuration mConfiguration; <del> <del> private UnderFileSystemInputStream(AlluxioURI ufsUri, Configuration conf) { <del> mUfsPath = ufsUri.toString(); <del> mConfiguration = conf; <del> } <del> <del> private InputStream openAtPosition(long position) throws IOException { <del> UnderFileSystem ufs = UnderFileSystem.get(mUfsPath, mConfiguration); <del> InputStream stream = ufs.open(mUfsPath); <del> if (position != stream.skip(position)) { <del> throw new IOException(ExceptionMessage.FAILED_SKIP.getMessage(position)); <del> } <del> return stream; <del> } <del> } <ide> }
Java
apache-2.0
e44d821cd4ab8799db8d57c453215b41e6810097
0
opensingular/singular-core,opensingular/singular-core,opensingular/singular-core,opensingular/singular-core
/* * Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opensingular.form.io; import org.apache.commons.lang3.StringUtils; import org.opensingular.form.ICompositeInstance; import org.opensingular.form.InternalAccess; import org.opensingular.form.SIComposite; import org.opensingular.form.SIList; import org.opensingular.form.SISimple; import org.opensingular.form.SInstance; import org.opensingular.form.SType; import org.opensingular.form.STypeSimple; import org.opensingular.form.SingularFormException; import org.opensingular.form.document.RefType; import org.opensingular.form.document.SDocument; import org.opensingular.form.document.SDocumentFactory; import org.opensingular.form.type.core.annotation.DocumentAnnotations; import org.opensingular.form.type.core.annotation.SIAnnotation; import org.opensingular.internal.lib.commons.xml.MDocument; import org.opensingular.internal.lib.commons.xml.MElement; import org.opensingular.internal.lib.commons.xml.MParser; import org.w3c.dom.Attr; import org.w3c.dom.NamedNodeMap; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; /** * Métodos utilitários para converter instancias e anotaçãoes para e de XML. * * @author Daniel C. Bordin */ public final class SFormXMLUtil { public static final String ATRIBUTO_ID = "id"; public static final String ATRIBUTO_LAST_ID = "lastId"; private static InternalAccess internalAccess; private SFormXMLUtil() {} /** * Cria uma instância não passível de serialização para do tipo com o * conteúdo persistido no XML informado. */ @Nonnull public static <T extends SInstance> T fromXML(@Nonnull SType<T> tipo, @Nullable String xmlString) { return fromXMLInterno(tipo.newInstance(), parseXml(xmlString)); } /** * Cria uma instância não passível de serialização para do tipo com o * conteúdo persistido no XML informado. */ @Nonnull public static <T extends SInstance> T fromXML(@Nonnull SType<T> tipo, @Nullable MElement xml) { return fromXMLInterno(tipo.newInstance(), xml); } /** * Cria uma instância passível de serialização para o tipo referenciado e a * factory de documento informada. */ @Nonnull public static <T extends SInstance> T fromXML(@Nonnull RefType refType, @Nullable String xmlString, @Nonnull SDocumentFactory documentFactory) { return fromXML(refType, parseXml(xmlString), documentFactory); } /** * Cria uma instância passível de serialização para o tipo referenciado e a * factory de documento informada. */ @Nonnull public static <T extends SInstance> T fromXML(@Nonnull RefType refType, @Nullable MElement xml, @Nonnull SDocumentFactory documentFactory) { SInstance novo = documentFactory.createInstance(refType, false); return (T) fromXMLInterno(novo, xml); } /** Preenche a instância criada com o xml fornecido. */ @Nonnull private static <T extends SInstance> T fromXMLInterno(@Nonnull T novo, @Nullable MElement xml) { Integer lastId = 0; if (xml != null) { lastId = xml.getInteger("@" + ATRIBUTO_LAST_ID); } // Colocar em modo de não geraçao de IDs novo.getDocument().setLastId(-1); fromXML(novo, xml); int maxId = verificarIds(novo, new HashSet<>()); if (lastId == null) { novo.getDocument().setLastId(maxId); } else { novo.getDocument().setLastId(lastId); } return novo; } private static int verificarIds(@Nonnull SInstance instancia, @Nonnull Set<Integer> ids) { Integer id = instancia.getId(); if (ids.contains(id)) { throw new SingularFormException("A instance tem ID repetido (igual a outra instância) id=" + id, instancia); } if (instancia instanceof ICompositeInstance) { int max = id; for (SInstance filho : ((ICompositeInstance) instancia).getChildren()) { max = Math.max(max, verificarIds(filho, ids)); } return max; } return id; } private static void fromXML(@Nonnull SInstance instance, @Nullable MElement xml) { if (xml == null) return; // Não precisa fazer nada instance.clearInstance(); lerAtributos(instance, xml); if (instance instanceof SISimple) { fromXMLSISImple(instance, xml); } else if (instance instanceof SIComposite) { fromXMLSIComposite(instance, xml); } else if (instance instanceof SIList) { fromXMLSIList(instance, xml); } else { throw new SingularFormException( "Conversão não implementando para a classe " + instance.getClass().getName(), instance); } } private static void fromXMLSISImple(@Nonnull SInstance instance, @Nullable MElement xml) { SISimple<?> instanceSimple = (SISimple<?>) instance; STypeSimple<?, ?> type = instanceSimple.getType(); instance.setValue(type.fromStringPersistence(xml.getTextContent())); } private static void fromXMLSIList(@Nonnull SInstance instance, @Nullable MElement xml) { SIList<?> list = (SIList<?>) instance; String childrenName = list.getType().getElementsType().getNameSimple(); for(MElement xmlChild = xml.getPrimeiroFilho(); xmlChild != null; xmlChild = xmlChild.getProximoIrmao()) { if(childrenName.equals(xmlChild.getTagName())) { fromXML(list.addNew(), xmlChild); } else { getInternalAccess().addUnreadInfo(instance, xmlChild); } } } private static void fromXMLSIComposite(@Nonnull SInstance instance, @Nullable MElement xml) { SIComposite instc = (SIComposite) instance; for(MElement xmlChild = xml.getPrimeiroFilho(); xmlChild != null; xmlChild = xmlChild.getProximoIrmao()) { Optional<SInstance> instcField = instc.getFieldOpt(xmlChild.getTagName()); if (instcField.isPresent()) { fromXML(instcField.get(), xmlChild); } else { getInternalAccess().addUnreadInfo(instance, xmlChild); } } } private static void lerAtributos(SInstance instancia, MElement xml) { NamedNodeMap atributos = xml.getAttributes(); if (atributos != null) { for (int i = 0; i < atributos.getLength(); i++) { Attr at = (Attr) atributos.item(i); if (at.getName().equals(ATRIBUTO_ID)) { instancia.setId(Integer.valueOf(at.getValue())); } else if (!at.getName().equals(ATRIBUTO_LAST_ID)) { getInternalAccess().setAttributeValueSavingForLatter(instancia, at.getName(), at.getValue()); } } } } /** * Gera uma string XML representando a instância de forma apropriada para persitência permanente (ex: para * armazenamento em banco de dados). Já trata escapes de caracteres especiais dentro dos valores. * @return Se a instância não conter nenhum valor, então retorna um resultado null no Optional */ @Nonnull public static Optional<String> toStringXML(@Nonnull SInstance instance) { return toXML(instance).map(MElement::toStringExato); } /** * Gera uma string XML representando a instância de forma apropriada para persitência permanente (ex: para * armazenamento em banco de dados). Já trata escapes de caracteres especiais dentro dos valores. * @return Se a instância não conter nenhum valor, então retorna um XML com apenas o nome do tipo da instância. */ @Nonnull public static String toStringXMLOrEmptyXML(@Nonnull SInstance instance) { return toXMLOrEmptyXML(instance).toStringExato(); } /** * Gera um XML representando a instância de forma apropriada para persitência permanente (ex: para armazenamento em * banco de dados). * @return Se a instância não conter nenhum valor, então retorna um resultado null no Optional */ @Nonnull public static Optional<MElement> toXML(@Nonnull SInstance instancia) { return Optional.ofNullable(createDefaultBuilder().toXML(instancia)); } /** * Gera uma string XML representando a instância de forma apropriada para persitência permanente (ex: para * armazenamento em banco de dados). * @return Se a instância não conter nenhum valor, então retorna um XML com apenas o nome do tipo da instância. */ @Nonnull public static MElement toXMLOrEmptyXML(@Nonnull SInstance instancia) { return createDefaultBuilder().withReturnNullXML(false).toXML(instancia); } /** Cria uma configuração default para a geração de XML. */ private static PersistenceBuilderXML createDefaultBuilder() { return new PersistenceBuilderXML().withPersistNull(false); } /** * Gera uma string XML representando os dados da instância e o atributos de runtime para persistência temporária * (provavelemnte temporariamente durante a tela de edição). */ @Nonnull public static MElement toXMLPreservingRuntimeEdition(@Nonnull SInstance instancia) { return new PersistenceBuilderXML().withPersistNull(true).withPersistAttributes(true).withReturnNullXML(false) .toXML(instancia); } @Nullable static MElement toXML(MElement pai, String nomePai, @Nonnull SInstance instancia, @Nonnull PersistenceBuilderXML builder) { MDocument xmlDocument = (pai == null) ? MDocument.newInstance() : pai.getMDocument(); ConfXMLGeneration conf = new ConfXMLGeneration(builder, xmlDocument); MElement xmlResultado = toXML(conf, instancia); if (xmlResultado == null) { if (builder.isReturnNullXML()) { return pai; } xmlResultado = conf.createMElement(instancia); } if (nomePai != null) { MElement novo = xmlDocument.createMElement(nomePai); novo.addElement(xmlResultado); xmlResultado = novo; } if (pai != null) { pai.addElement(xmlResultado); return pai; } xmlDocument.setRaiz(xmlResultado); if (builder.isPersistId()) { xmlResultado.setAttribute(ATRIBUTO_LAST_ID, Integer.toString(instancia.getDocument().getLastId())); } return xmlResultado; } static MElement parseXml(String xmlString) { try { if (StringUtils.isBlank(xmlString)) { return null; } return MParser.parse(xmlString); } catch (Exception e) { throw new SingularFormException("Erro lendo xml (parse)", e); } } /** * Carrega na instance informada as anotação contidas no xml, fazendo * parser do mesmo antes. * * @param xmlString Se nulo ou em branco, não faz carga */ @Deprecated public static void annotationLoadFromXml(SInstance instance, String xmlString) { annotationLoadFromXml(instance.getDocument(), xmlString); } /** * Carrega na instance informada as anotação contidas no xml, fazendo * parser do mesmo antes. * * @param xmlAnnotations Se nulo, não faz carga */ @Deprecated public static void annotationLoadFromXml(SInstance instance, MElement xmlAnnotations) { annotationLoadFromXml(instance.getDocument(), xmlAnnotations); } /** * Carrega na instance informada as anotação contidas no xml, fazendo * parser do mesmo antes. * * @param xmlString Se nulo ou em branco, não faz carga */ public static void annotationLoadFromXml(@Nonnull SDocument document, @Nullable String xmlString) { annotationLoadFromXml(document, parseXml(xmlString)); } /** * Carrega na instance informada as anotação contidas no xml, fazendo * parser do mesmo antes. * * @param xmlAnnotations Se nulo, não faz carga */ public static void annotationLoadFromXml(@Nonnull SDocument document, @Nullable MElement xmlAnnotations) { if (xmlAnnotations == null) { return; } SIList<SIAnnotation> iAnnotations = DocumentAnnotations.newAnnotationList(document, false); fromXMLInterno(iAnnotations, xmlAnnotations); document.getDocumentAnnotations().loadAnnotations(iAnnotations); } /** Gera um XML representando as anotações se existirem. */ @Nonnull public static Optional<String> annotationToXmlString(@Nonnull SInstance instance) { return annotationToXml(instance).map(MElement::toStringExato); } /** Gera um XML representando as anotações se existirem. */ @Nonnull public static Optional<MElement> annotationToXml(@Nonnull SInstance instance) { return annotationToXml(instance, null); } /** Gera um XML representando as anotações se existirem. */ @Nonnull public static Optional<MElement> annotationToXml(@Nonnull SInstance instance, @Nullable String classifier) { return annotationToXml(instance.getDocument(), classifier); } /** Gera um XML representando as anotações se existirem. */ @Nonnull public static Optional<MElement> annotationToXml(@Nonnull SDocument document, @Nullable String classifier) { DocumentAnnotations documentAnnotations = document.getDocumentAnnotations(); if (documentAnnotations.hasAnnotations()) { if (classifier != null) { return toXML(documentAnnotations.persistentAnnotationsClassified(classifier)); } else { return toXML(documentAnnotations.getAnnotations()); } } return Optional.empty(); } /** Gera o xml para instance e para seus dados interno. */ private static MElement toXML(ConfXMLGeneration conf, SInstance instance) { MElement newElement = null; if (instance instanceof SISimple<?>) { SISimple<?> iSimples = (SISimple<?>) instance; String sPersistence = iSimples.toStringPersistence(); if (sPersistence != null) { newElement = conf.createMElementComValor(instance, sPersistence); } else if (conf.isPersistirNull()) { newElement = conf.createMElement(instance); } } else if (instance instanceof SIComposite) { newElement = toXMLChildren(conf, instance, newElement, ((SIComposite) instance).getFields()); } else if (instance instanceof SIList) { newElement = toXMLChildren(conf, instance, newElement, ((SIList<?>) instance).getValues()); } else { throw new SingularFormException("Instancia da classe " + instance.getClass().getName() + " não suportada", instance); } //Verifica se há alguma informação lida anteriormente que deva ser grava novamente newElement = toXMLOldElementWithoutType(conf, instance, newElement); return newElement; } /** * Gera no XML a os elemento filhos (senão existirem). */ private static MElement toXMLChildren(ConfXMLGeneration conf, SInstance instance, MElement newElement, List<? extends SInstance> children) { MElement result = newElement; for (SInstance child : children) { MElement xmlChild = toXML(conf, child); if (xmlChild != null) { if (result == null) { result = conf.createMElement(instance); } result.appendChild(xmlChild); } } return result; } /** * Escreve para o XML os elemento que foram lidos do XML anterior e foram preservados apesar de não terem um type * correspondente. Ou seja, mantêm campo "fantasmas" entre leituras e gravações. */ private static MElement toXMLOldElementWithoutType(ConfXMLGeneration conf, SInstance instance, MElement newElement) { List<MElement> unreadInfo = getInternalAccess().getUnreadInfo(instance); MElement result = newElement; if (! unreadInfo.isEmpty()) { if (result == null) { result = conf.createMElement(instance); } for(MElement extra : unreadInfo) { result.copy(extra, null); } } return result; } /** Garante a carga do objeto a chamada internas da API. */ @Nonnull private static final InternalAccess getInternalAccess() { if (internalAccess == null) { InternalAccess.load(); return Objects.requireNonNull(internalAccess); } return internalAccess; } /** Recebe o objeto que viabiliza executar chamadas internas da API (chamadas a métodos não públicos). */ public static final void setInternalAccess(@Nonnull InternalAccess internalAccess) { SFormXMLUtil.internalAccess = internalAccess; } private static final class ConfXMLGeneration { private final MDocument xmlDocument; private final PersistenceBuilderXML builder; public ConfXMLGeneration(PersistenceBuilderXML builder, MDocument xmlDocument) { this.builder = builder; this.xmlDocument = xmlDocument; } public boolean isPersistirNull() { return builder.isPersistNull(); } public MElement createMElement(SInstance instancia) { return complement(instancia, xmlDocument.createMElement(instancia.getType().getNameSimple())); } public MElement createMElementComValor(SInstance instancia, String valorPersistencia) { return complement(instancia, xmlDocument.createMElementComValor(instancia.getType().getNameSimple(), valorPersistencia)); } private MElement complement(SInstance instancia, MElement element) { Integer id = instancia.getId(); if (builder.isPersistId()) { element.setAttribute(ATRIBUTO_ID, id.toString()); } if (builder.isPersistAttributes()) { for (SInstance atr : instancia.getAttributes()) { String name = atr.getAttributeInstanceInfo().getName(); if (atr instanceof SISimple) { String sPersistence = ((SISimple<?>) atr).toStringPersistence(); element.setAttribute(name, sPersistence); } else { throw new SingularFormException("Não implementada a persitência de atributos compostos: " + name, instancia); } } } return element; } } }
form/core/src/main/java/org/opensingular/form/io/SFormXMLUtil.java
/* * Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opensingular.form.io; import org.apache.commons.lang3.StringUtils; import org.opensingular.form.ICompositeInstance; import org.opensingular.form.InternalAccess; import org.opensingular.form.SIComposite; import org.opensingular.form.SIList; import org.opensingular.form.SISimple; import org.opensingular.form.SInstance; import org.opensingular.form.SType; import org.opensingular.form.STypeSimple; import org.opensingular.form.SingularFormException; import org.opensingular.form.document.RefType; import org.opensingular.form.document.SDocument; import org.opensingular.form.document.SDocumentFactory; import org.opensingular.form.type.core.annotation.DocumentAnnotations; import org.opensingular.form.type.core.annotation.SIAnnotation; import org.opensingular.internal.lib.commons.xml.MDocument; import org.opensingular.internal.lib.commons.xml.MElement; import org.opensingular.internal.lib.commons.xml.MParser; import org.w3c.dom.Attr; import org.w3c.dom.NamedNodeMap; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; /** * Métodos utilitários para converter instancias e anotaçãoes para e de XML. * * @author Daniel C. Bordin */ public final class SFormXMLUtil { public static final String ATRIBUTO_ID = "id"; public static final String ATRIBUTO_LAST_ID = "lastId"; private static InternalAccess internalAccess; private SFormXMLUtil() {} /** * Cria uma instância não passível de serialização para do tipo com o * conteúdo persistido no XML informado. */ @Nonnull public static <T extends SInstance> T fromXML(@Nonnull SType<T> tipo, @Nullable String xmlString) { return fromXMLInterno(tipo.newInstance(), parseXml(xmlString)); } /** * Cria uma instância não passível de serialização para do tipo com o * conteúdo persistido no XML informado. */ @Nonnull public static <T extends SInstance> T fromXML(@Nonnull SType<T> tipo, @Nullable MElement xml) { return fromXMLInterno(tipo.newInstance(), xml); } /** * Cria uma instância passível de serialização para o tipo referenciado e a * factory de documento informada. */ @Nonnull public static <T extends SInstance> T fromXML(@Nonnull RefType refType, @Nullable String xmlString, @Nonnull SDocumentFactory documentFactory) { return fromXML(refType, parseXml(xmlString), documentFactory); } /** * Cria uma instância passível de serialização para o tipo referenciado e a * factory de documento informada. */ @Nonnull public static <T extends SInstance> T fromXML(@Nonnull RefType refType, @Nullable MElement xml, @Nonnull SDocumentFactory documentFactory) { SInstance novo = documentFactory.createInstance(refType, false); return (T) fromXMLInterno(novo, xml); } /** Preenche a instância criada com o xml fornecido. */ @Nonnull private static <T extends SInstance> T fromXMLInterno(@Nonnull T novo, @Nullable MElement xml) { Integer lastId = 0; if (xml != null) { lastId = xml.getInteger("@" + ATRIBUTO_LAST_ID); } // Colocar em modo de não geraçao de IDs novo.getDocument().setLastId(-1); fromXML(novo, xml); int maxId = verificarIds(novo, new HashSet<>()); if (lastId == null) { novo.getDocument().setLastId(maxId); } else { novo.getDocument().setLastId(lastId); } return novo; } private static int verificarIds(@Nonnull SInstance instancia, @Nonnull Set<Integer> ids) { Integer id = instancia.getId(); if (ids.contains(id)) { throw new SingularFormException("A instance tem ID repetido (igual a outra instância) id=" + id, instancia); } if (instancia instanceof ICompositeInstance) { int max = id; for (SInstance filho : ((ICompositeInstance) instancia).getChildren()) { max = Math.max(max, verificarIds(filho, ids)); } return max; } return id; } private static void fromXML(@Nonnull SInstance instance, @Nullable MElement xml) { if (xml == null) return; // Não precisa fazer nada instance.clearInstance(); lerAtributos(instance, xml); if (instance instanceof SISimple) { SISimple<?> instanceSimple = (SISimple<?>) instance; STypeSimple<?, ?> type = instanceSimple.getType(); instance.setValue(type.fromStringPersistence(xml.getTextContent())); } else if (instance instanceof SIComposite) { SIComposite instc = (SIComposite) instance; for(MElement xmlChild = xml.getPrimeiroFilho(); xmlChild != null; xmlChild = xmlChild.getProximoIrmao()) { Optional<SInstance> instcField = instc.getFieldOpt(xmlChild.getTagName()); if (instcField.isPresent()) { fromXML(instcField.get(), xmlChild); } else { getInternalAccess().addUnreadInfo(instance, xmlChild); } } } else if (instance instanceof SIList) { SIList<?> list = (SIList<?>) instance; String childrenName = list.getType().getElementsType().getNameSimple(); for(MElement xmlChild = xml.getPrimeiroFilho(); xmlChild != null; xmlChild = xmlChild.getProximoIrmao()) { if(childrenName.equals(xmlChild.getTagName())) { fromXML(list.addNew(), xmlChild); } else { getInternalAccess().addUnreadInfo(instance, xmlChild); } } } else { throw new SingularFormException( "Conversão não implementando para a classe " + instance.getClass().getName(), instance); } } private static void lerAtributos(SInstance instancia, MElement xml) { NamedNodeMap atributos = xml.getAttributes(); if (atributos != null) { for (int i = 0; i < atributos.getLength(); i++) { Attr at = (Attr) atributos.item(i); if (at.getName().equals(ATRIBUTO_ID)) { instancia.setId(Integer.valueOf(at.getValue())); } else if (!at.getName().equals(ATRIBUTO_LAST_ID)) { getInternalAccess().setAttributeValueSavingForLatter(instancia, at.getName(), at.getValue()); } } } } /** * Gera uma string XML representando a instância de forma apropriada para persitência permanente (ex: para * armazenamento em banco de dados). Já trata escapes de caracteres especiais dentro dos valores. * @return Se a instância não conter nenhum valor, então retorna um resultado null no Optional */ @Nonnull public static Optional<String> toStringXML(@Nonnull SInstance instance) { return toXML(instance).map(MElement::toStringExato); } /** * Gera uma string XML representando a instância de forma apropriada para persitência permanente (ex: para * armazenamento em banco de dados). Já trata escapes de caracteres especiais dentro dos valores. * @return Se a instância não conter nenhum valor, então retorna um XML com apenas o nome do tipo da instância. */ @Nonnull public static String toStringXMLOrEmptyXML(@Nonnull SInstance instance) { return toXMLOrEmptyXML(instance).toStringExato(); } /** * Gera um XML representando a instância de forma apropriada para persitência permanente (ex: para armazenamento em * banco de dados). * @return Se a instância não conter nenhum valor, então retorna um resultado null no Optional */ @Nonnull public static Optional<MElement> toXML(@Nonnull SInstance instancia) { return Optional.ofNullable(createDefaultBuilder().toXML(instancia)); } /** * Gera uma string XML representando a instância de forma apropriada para persitência permanente (ex: para * armazenamento em banco de dados). * @return Se a instância não conter nenhum valor, então retorna um XML com apenas o nome do tipo da instância. */ @Nonnull public static MElement toXMLOrEmptyXML(@Nonnull SInstance instancia) { return createDefaultBuilder().withReturnNullXML(false).toXML(instancia); } /** Cria uma configuração default para a geração de XML. */ private static PersistenceBuilderXML createDefaultBuilder() { return new PersistenceBuilderXML().withPersistNull(false); } /** * Gera uma string XML representando os dados da instância e o atributos de runtime para persistência temporária * (provavelemnte temporariamente durante a tela de edição). */ @Nonnull public static MElement toXMLPreservingRuntimeEdition(@Nonnull SInstance instancia) { return new PersistenceBuilderXML().withPersistNull(true).withPersistAttributes(true).withReturnNullXML(false) .toXML(instancia); } @Nullable static MElement toXML(MElement pai, String nomePai, @Nonnull SInstance instancia, @Nonnull PersistenceBuilderXML builder) { MDocument xmlDocument = (pai == null) ? MDocument.newInstance() : pai.getMDocument(); ConfXMLGeneration conf = new ConfXMLGeneration(builder, xmlDocument); MElement xmlResultado = toXML(conf, instancia); if (xmlResultado == null) { if (builder.isReturnNullXML()) { return pai; } xmlResultado = conf.createMElement(instancia); } if (nomePai != null) { MElement novo = xmlDocument.createMElement(nomePai); novo.addElement(xmlResultado); xmlResultado = novo; } if (pai != null) { pai.addElement(xmlResultado); return pai; } xmlDocument.setRaiz(xmlResultado); if (builder.isPersistId()) { xmlResultado.setAttribute(ATRIBUTO_LAST_ID, Integer.toString(instancia.getDocument().getLastId())); } return xmlResultado; } static MElement parseXml(String xmlString) { try { if (StringUtils.isBlank(xmlString)) { return null; } return MParser.parse(xmlString); } catch (Exception e) { throw new SingularFormException("Erro lendo xml (parse)", e); } } /** * Carrega na instance informada as anotação contidas no xml, fazendo * parser do mesmo antes. * * @param xmlString Se nulo ou em branco, não faz carga */ @Deprecated public static void annotationLoadFromXml(SInstance instance, String xmlString) { annotationLoadFromXml(instance.getDocument(), xmlString); } /** * Carrega na instance informada as anotação contidas no xml, fazendo * parser do mesmo antes. * * @param xmlAnnotations Se nulo, não faz carga */ @Deprecated public static void annotationLoadFromXml(SInstance instance, MElement xmlAnnotations) { annotationLoadFromXml(instance.getDocument(), xmlAnnotations); } /** * Carrega na instance informada as anotação contidas no xml, fazendo * parser do mesmo antes. * * @param xmlString Se nulo ou em branco, não faz carga */ public static void annotationLoadFromXml(@Nonnull SDocument document, @Nullable String xmlString) { annotationLoadFromXml(document, parseXml(xmlString)); } /** * Carrega na instance informada as anotação contidas no xml, fazendo * parser do mesmo antes. * * @param xmlAnnotations Se nulo, não faz carga */ public static void annotationLoadFromXml(@Nonnull SDocument document, @Nullable MElement xmlAnnotations) { if (xmlAnnotations == null) { return; } SIList<SIAnnotation> iAnnotations = DocumentAnnotations.newAnnotationList(document, false); fromXMLInterno(iAnnotations, xmlAnnotations); document.getDocumentAnnotations().loadAnnotations(iAnnotations); } /** Gera um XML representando as anotações se existirem. */ @Nonnull public static Optional<String> annotationToXmlString(@Nonnull SInstance instance) { return annotationToXml(instance).map(MElement::toStringExato); } /** Gera um XML representando as anotações se existirem. */ @Nonnull public static Optional<MElement> annotationToXml(@Nonnull SInstance instance) { return annotationToXml(instance, null); } /** Gera um XML representando as anotações se existirem. */ @Nonnull public static Optional<MElement> annotationToXml(@Nonnull SInstance instance, @Nullable String classifier) { return annotationToXml(instance.getDocument(), classifier); } /** Gera um XML representando as anotações se existirem. */ @Nonnull public static Optional<MElement> annotationToXml(@Nonnull SDocument document, @Nullable String classifier) { DocumentAnnotations documentAnnotations = document.getDocumentAnnotations(); if (documentAnnotations.hasAnnotations()) { if (classifier != null) { return toXML(documentAnnotations.persistentAnnotationsClassified(classifier)); } else { return toXML(documentAnnotations.getAnnotations()); } } return Optional.empty(); } /** Gera o xml para instance e para seus dados interno. */ private static MElement toXML(ConfXMLGeneration conf, SInstance instance) { MElement newElement = null; if (instance instanceof SISimple<?>) { SISimple<?> iSimples = (SISimple<?>) instance; String sPersistence = iSimples.toStringPersistence(); if (sPersistence != null) { newElement = conf.createMElementComValor(instance, sPersistence); } else if (conf.isPersistirNull()) { newElement = conf.createMElement(instance); } } else if (instance instanceof SIComposite) { newElement = toXMLChildren(conf, instance, newElement, ((SIComposite) instance).getFields()); } else if (instance instanceof SIList) { newElement = toXMLChildren(conf, instance, newElement, ((SIList<?>) instance).getValues()); } else { throw new SingularFormException("Instancia da classe " + instance.getClass().getName() + " não suportada", instance); } //Verifica se há alguma informação lida anteriormente que deva ser grava novamente newElement = toXMLOldElementWithoutType(conf, instance, newElement); return newElement; } /** * Gera no XML a os elemento filhos (senão existirem). */ private static MElement toXMLChildren(ConfXMLGeneration conf, SInstance instance, MElement newElement, List<? extends SInstance> children) { MElement result = newElement; for (SInstance child : children) { MElement xmlChild = toXML(conf, child); if (xmlChild != null) { if (result == null) { result = conf.createMElement(instance); } result.appendChild(xmlChild); } } return result; } /** * Escreve para o XML os elemento que foram lidos do XML anterior e foram preservados apesar de não terem um type * correspondente. Ou seja, mantêm campo "fantasmas" entre leituras e gravações. */ private static MElement toXMLOldElementWithoutType(ConfXMLGeneration conf, SInstance instance, MElement newElement) { List<MElement> unreadInfo = getInternalAccess().getUnreadInfo(instance); MElement result = newElement; if (! unreadInfo.isEmpty()) { if (result == null) { result = conf.createMElement(instance); } for(MElement extra : unreadInfo) { result.copy(extra, null); } } return result; } /** Garante a carga do objeto a chamada internas da API. */ @Nonnull private static final InternalAccess getInternalAccess() { if (internalAccess == null) { InternalAccess.load(); return Objects.requireNonNull(internalAccess); } return internalAccess; } /** Recebe o objeto que viabiliza executar chamadas internas da API (chamadas a métodos não públicos). */ public static final void setInternalAccess(@Nonnull InternalAccess internalAccess) { SFormXMLUtil.internalAccess = internalAccess; } private static final class ConfXMLGeneration { private final MDocument xmlDocument; private final PersistenceBuilderXML builder; public ConfXMLGeneration(PersistenceBuilderXML builder, MDocument xmlDocument) { this.builder = builder; this.xmlDocument = xmlDocument; } public boolean isPersistirNull() { return builder.isPersistNull(); } public MElement createMElement(SInstance instancia) { return complement(instancia, xmlDocument.createMElement(instancia.getType().getNameSimple())); } public MElement createMElementComValor(SInstance instancia, String valorPersistencia) { return complement(instancia, xmlDocument.createMElementComValor(instancia.getType().getNameSimple(), valorPersistencia)); } private MElement complement(SInstance instancia, MElement element) { Integer id = instancia.getId(); if (builder.isPersistId()) { element.setAttribute(ATRIBUTO_ID, id.toString()); } if (builder.isPersistAttributes()) { for (SInstance atr : instancia.getAttributes()) { String name = atr.getAttributeInstanceInfo().getName(); if (atr instanceof SISimple) { String sPersistence = ((SISimple<?>) atr).toStringPersistence(); element.setAttribute(name, sPersistence); } else { throw new SingularFormException("Não implementada a persitência de atributos compostos: " + name, instancia); } } } return element; } } }
Reduzindo Cognitive Complexity
form/core/src/main/java/org/opensingular/form/io/SFormXMLUtil.java
Reduzindo Cognitive Complexity
<ide><path>orm/core/src/main/java/org/opensingular/form/io/SFormXMLUtil.java <ide> instance.clearInstance(); <ide> lerAtributos(instance, xml); <ide> if (instance instanceof SISimple) { <del> SISimple<?> instanceSimple = (SISimple<?>) instance; <del> STypeSimple<?, ?> type = instanceSimple.getType(); <del> instance.setValue(type.fromStringPersistence(xml.getTextContent())); <add> fromXMLSISImple(instance, xml); <ide> } else if (instance instanceof SIComposite) { <del> SIComposite instc = (SIComposite) instance; <del> for(MElement xmlChild = xml.getPrimeiroFilho(); xmlChild != null; xmlChild = xmlChild.getProximoIrmao()) { <del> Optional<SInstance> instcField = instc.getFieldOpt(xmlChild.getTagName()); <del> if (instcField.isPresent()) { <del> fromXML(instcField.get(), xmlChild); <del> } else { <del> getInternalAccess().addUnreadInfo(instance, xmlChild); <del> } <del> } <add> fromXMLSIComposite(instance, xml); <ide> } else if (instance instanceof SIList) { <del> SIList<?> list = (SIList<?>) instance; <del> String childrenName = list.getType().getElementsType().getNameSimple(); <del> for(MElement xmlChild = xml.getPrimeiroFilho(); xmlChild != null; xmlChild = xmlChild.getProximoIrmao()) { <del> if(childrenName.equals(xmlChild.getTagName())) { <del> fromXML(list.addNew(), xmlChild); <del> } else { <del> getInternalAccess().addUnreadInfo(instance, xmlChild); <del> } <del> } <add> fromXMLSIList(instance, xml); <ide> } else { <ide> throw new SingularFormException( <ide> "Conversão não implementando para a classe " + instance.getClass().getName(), instance); <add> } <add> } <add> <add> private static void fromXMLSISImple(@Nonnull SInstance instance, @Nullable MElement xml) { <add> SISimple<?> instanceSimple = (SISimple<?>) instance; <add> STypeSimple<?, ?> type = instanceSimple.getType(); <add> instance.setValue(type.fromStringPersistence(xml.getTextContent())); <add> } <add> <add> private static void fromXMLSIList(@Nonnull SInstance instance, @Nullable MElement xml) { <add> SIList<?> list = (SIList<?>) instance; <add> String childrenName = list.getType().getElementsType().getNameSimple(); <add> for(MElement xmlChild = xml.getPrimeiroFilho(); xmlChild != null; xmlChild = xmlChild.getProximoIrmao()) { <add> if(childrenName.equals(xmlChild.getTagName())) { <add> fromXML(list.addNew(), xmlChild); <add> } else { <add> getInternalAccess().addUnreadInfo(instance, xmlChild); <add> } <add> } <add> } <add> <add> private static void fromXMLSIComposite(@Nonnull SInstance instance, @Nullable MElement xml) { <add> SIComposite instc = (SIComposite) instance; <add> for(MElement xmlChild = xml.getPrimeiroFilho(); xmlChild != null; xmlChild = xmlChild.getProximoIrmao()) { <add> Optional<SInstance> instcField = instc.getFieldOpt(xmlChild.getTagName()); <add> if (instcField.isPresent()) { <add> fromXML(instcField.get(), xmlChild); <add> } else { <add> getInternalAccess().addUnreadInfo(instance, xmlChild); <add> } <ide> } <ide> } <ide>
Java
mpl-2.0
88a8914584152aa194cf660e7c738fe7cd089c96
0
zamojski/TowerCollector,zamojski/TowerCollector
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package info.zamojski.soft.towercollector.views; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.location.Criteria; import android.location.Location; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.Network; import android.net.NetworkCapabilities; import android.net.NetworkRequest; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.text.method.LinkMovementMethod; import android.view.InputDevice; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.view.ContextThemeWrapper; import androidx.core.content.res.ResourcesCompat; import androidx.core.net.ConnectivityManagerCompat; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import org.osmdroid.api.IMapController; import org.osmdroid.bonuspack.clustering.RadiusMarkerClusterer; import org.osmdroid.events.DelayedMapListener; import org.osmdroid.events.MapListener; import org.osmdroid.events.ScrollEvent; import org.osmdroid.events.ZoomEvent; import org.osmdroid.tileprovider.tilesource.TileSourceFactory; import org.osmdroid.util.BoundingBox; import org.osmdroid.util.GeoPoint; import org.osmdroid.views.MapView; import org.osmdroid.views.overlay.Marker; import org.osmdroid.views.overlay.ScaleBarOverlay; import org.osmdroid.views.overlay.TilesOverlay; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import info.zamojski.soft.towercollector.MyApplication; import info.zamojski.soft.towercollector.R; import info.zamojski.soft.towercollector.dao.MeasurementsDatabase; import info.zamojski.soft.towercollector.events.MeasurementSavedEvent; import info.zamojski.soft.towercollector.events.PrintMainWindowEvent; import info.zamojski.soft.towercollector.map.FollowMyLocationOverlay; import info.zamojski.soft.towercollector.model.Boundaries; import info.zamojski.soft.towercollector.model.MapCell; import info.zamojski.soft.towercollector.model.MapMeasurement; import info.zamojski.soft.towercollector.model.Measurement; import info.zamojski.soft.towercollector.model.Tuple; import info.zamojski.soft.towercollector.utils.GpsUtils; import info.zamojski.soft.towercollector.utils.MapUtils; import info.zamojski.soft.towercollector.utils.NetworkTypeUtils; import info.zamojski.soft.towercollector.utils.ResourceUtils; import timber.log.Timber; public class MainMapFragment extends MainFragmentBase implements FollowMyLocationOverlay.FollowMyLocationChangeListener { private static final int MAP_DATA_LOAD_DELAY_IN_MILLIS = 200; private static final int MAX_MARKERS_ADDED_INDIVIDUALLY = 500; private static final float BOUNDARIES_INCREASE_FACTOR = 1.2f; // 10% more each side private MapView mainMapView; private FollowMyLocationOverlay myLocationOverlay; private ImageButton followMeButton; private ImageButton myLocationButton; private RadiusMarkerClusterer markersOverlay; private Bitmap clusterIcon; private BackgroundMarkerLoaderTask backgroundMarkerLoaderTask; private boolean missedMapZoomScrollUpdates = false; private int markersAddedIndividually = 0; private BoundingBox lastLoadedBoundingBox = null; private boolean isLightThemeForced; private Resources.Theme theme; private ConnectivityManager connectivityManager; private boolean isNetworkCallbackRegistered = false; private SimpleDateFormat dateTimeFormatStandard; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { MapUtils.configureMap(MyApplication.getApplication()); View rootView = inflater.inflate(R.layout.main_map_fragment, container, false); configureControls(rootView); connectivityManager = (ConnectivityManager) MyApplication.getApplication().getSystemService(Context.CONNECTIVITY_SERVICE); return rootView; } @Override protected void configureOnResume() { super.configureOnResume(); boolean themeChanged = reloadTheme(); if (themeChanged) { reloadMapTheme(); reloadMarkers(true); } registerNetworkCallback(); if (mainMapView != null) { mainMapView.onResume(); } setFollowMe(MyApplication.getPreferencesProvider().isMainMapFollowMeEnabled()); myLocationOverlay.enableMyLocation(); } @Override protected void configureOnPause() { super.configureOnPause(); if (mainMapView != null) mainMapView.onPause(); myLocationOverlay.disableFollowLocation(); myLocationOverlay.disableMyLocation(); unregisterNetworkCallback(); } @Override public void onDestroyView() { super.onDestroyView(); if (backgroundMarkerLoaderTask != null) backgroundMarkerLoaderTask.cancel(false); if (mainMapView != null) mainMapView.onDetach(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); markersOverlay = createMarkersOverlay(); mainMapView.getOverlays().add(markersOverlay); mainMapView.addOnFirstLayoutListener(new MapView.OnFirstLayoutListener() { @Override public void onFirstLayout(View v, int left, int top, int right, int bottom) { Timber.d("onFirstLayout(): Move to last measurement"); moveToLastMeasurement(); } }); } private RadiusMarkerClusterer createMarkersOverlay() { RadiusMarkerClusterer overlay = new RadiusMarkerClusterer(MyApplication.getApplication()); overlay.setIcon(getClusterIcon()); overlay.setRadius(100); overlay.setMaxClusteringZoomLevel(13); return overlay; } @Override protected void configureControls(View view) { super.configureControls(view); reloadTheme(); mainMapView = view.findViewById(R.id.main_map); followMeButton = view.findViewById(R.id.main_map_follow_me_button); followMeButton.setOnLongClickListener(IMAGE_BUTTON_LONG_CLICK_LISTENER); myLocationButton = view.findViewById(R.id.main_map_my_location_button); myLocationButton.setOnLongClickListener(IMAGE_BUTTON_LONG_CLICK_LISTENER); TextView copyrightTextView = view.findViewById(R.id.main_map_copyright); copyrightTextView.setMovementMethod(LinkMovementMethod.getInstance()); mainMapView.setTileSource(TileSourceFactory.MAPNIK); mainMapView.setMultiTouchControls(true); mainMapView.setMinZoomLevel(5.0); mainMapView.setMaxZoomLevel(20.0); IMapController mapController = mainMapView.getController(); mapController.setZoom(MyApplication.getPreferencesProvider().getMainMapZoomLevel()); myLocationOverlay = new FollowMyLocationOverlay(mainMapView); myLocationOverlay.setFollowMyLocationChangeListener(this); myLocationOverlay.setDrawAccuracyEnabled(true); myLocationOverlay.setEnableAutoStop(true); setFollowMe(MyApplication.getPreferencesProvider().isMainMapFollowMeEnabled()); mainMapView.getOverlays().add(myLocationOverlay); ScaleBarOverlay scaleOverlay = new ScaleBarOverlay(mainMapView); scaleOverlay.setAlignBottom(true); scaleOverlay.setUnitsOfMeasure(MyApplication.getPreferencesProvider().getUseImperialUnits() ? ScaleBarOverlay.UnitsOfMeasure.imperial : ScaleBarOverlay.UnitsOfMeasure.metric); mainMapView.getOverlays().add(scaleOverlay); reloadMapTheme(); // configure zoom using mouse wheel mainMapView.setOnGenericMotionListener(new View.OnGenericMotionListener() { @Override public boolean onGenericMotion(View v, MotionEvent event) { if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { if (event.getAction() == MotionEvent.ACTION_SCROLL) { if (event.getAxisValue(MotionEvent.AXIS_VSCROLL) < 0.0f) mainMapView.getController().zoomOut(); else { mainMapView.getController().zoomIn(); } return true; } } return false; } }); myLocationButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Location lastLocation = myLocationOverlay.getLastFix(); Timber.i("onMyLocationClick(): Moving to %s", lastLocation); if (lastLocation != null) { GeoPoint myPosition = new GeoPoint(lastLocation.getLatitude(), lastLocation.getLongitude()); mainMapView.getController().animateTo(myPosition); } } }); followMeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setFollowMe(!myLocationOverlay.isFollowLocationEnabled()); } }); mainMapView.addMapListener(new DelayedMapListener(new MapListener() { private final String INNER_TAG = MainMapFragment.class.getSimpleName() + "." + DelayedMapListener.class.getSimpleName(); @Override public boolean onScroll(ScrollEvent scrollEvent) { Timber.tag(INNER_TAG).d("onScroll(): Scrolling to x=%1$s, y=%2$s", scrollEvent.getX(), scrollEvent.getY()); reloadMarkers(false); return false; } @Override public boolean onZoom(ZoomEvent zoomEvent) { Timber.tag(INNER_TAG).d("onZoom(): Changing zoom level to %s", zoomEvent.getZoomLevel()); MyApplication.getPreferencesProvider().setMainMapZoomLevel((float) zoomEvent.getZoomLevel()); reloadMarkers(true); return false; } }, MAP_DATA_LOAD_DELAY_IN_MILLIS)); dateTimeFormatStandard = new SimpleDateFormat(getString(R.string.date_time_format_standard), new Locale(getString(R.string.locale))); } private void reloadMarkers(boolean force) { if (backgroundMarkerLoaderTask == null) { if (force || lastLoadedBoundingBox == null) { Timber.d("reloadMarkers(): Loading markers due to force=%1$s, lastLoadedBoundingBox=%2$s", force, lastLoadedBoundingBox); Tuple<Boundaries, BoundingBox> boundaries = getVisibleBoundaries(); this.backgroundMarkerLoaderTask = new BackgroundMarkerLoaderTask(boundaries.getItem2()); this.backgroundMarkerLoaderTask.execute(boundaries.getItem1()); } else { BoundingBox boundingBox = mainMapView.getProjection().getBoundingBox(); double north = boundingBox.getActualNorth(); double south = boundingBox.getActualSouth(); double east = boundingBox.getLonEast(); double west = boundingBox.getLonWest(); if (!lastLoadedBoundingBox.contains(north, east) || !lastLoadedBoundingBox.contains(north, west) || !lastLoadedBoundingBox.contains(south, east) || !lastLoadedBoundingBox.contains(south, west)) { Timber.d("reloadMarkers(): No overlap between new and previously loaded bounding boxes"); reloadMarkers(true); } else { Timber.d("reloadMarkers(): New and previously loaded bounding boxes overlap, skipping load"); } } } else { // background load is active, we miss the scroll/zoom missedMapZoomScrollUpdates = true; } } private void displayMarkers(RadiusMarkerClusterer newMarkersOverlay) { mainMapView.getOverlays().remove(markersOverlay); markersOverlay.onDetach(mainMapView); markersOverlay = newMarkersOverlay; mainMapView.getOverlays().add(markersOverlay); if (mainMapView.isAnimating()) { mainMapView.postInvalidate(); } else { mainMapView.invalidate(); } markersAddedIndividually = 0; } private Tuple<Boundaries, BoundingBox> getVisibleBoundaries() { BoundingBox boundingBox = mainMapView.getProjection().getBoundingBox(); BoundingBox boundingBoxWithReserve = boundingBox.increaseByScale(BOUNDARIES_INCREASE_FACTOR); double minLat = boundingBoxWithReserve.getActualSouth(); double maxLat = boundingBoxWithReserve.getActualNorth(); double minLon = boundingBoxWithReserve.getLonWest(); double maxLon = boundingBoxWithReserve.getLonEast(); // when passing date line if (maxLon < minLon) { double swap = minLon; minLon = maxLon; maxLon = swap; } return new Tuple<Boundaries, BoundingBox>(new Boundaries(minLat, minLon, maxLat, maxLon), boundingBoxWithReserve); } private Marker createMarker(MapMeasurement m) { List<MapCell> mainCells = m.getMainCells(); @DrawableRes int iconId; if (mainCells.size() == 1) { iconId = NetworkTypeUtils.getNetworkGroupIcon(mainCells.get(0).getNetworkType()); } else { iconId = NetworkTypeUtils.getNetworkGroupIcon(mainCells.get(0).getNetworkType(), mainCells.get(1).getNetworkType()); } Marker item = new Marker(mainMapView); item.setIcon(ResourcesCompat.getDrawable(getResources(), iconId, theme)); item.setTitle(dateTimeFormatStandard.format(new Date(m.getMeasuredAt()))); item.setSnippet(String.valueOf(m.getDescription(MyApplication.getApplication()))); item.setPosition(new GeoPoint(m.getLatitude(), m.getLongitude())); item.setAnchor(0.5f, 0.5f); item.setOnMarkerClickListener(MARKER_CLICK_LISTENER); return item; } private void moveToLastMeasurement() { Measurement lastMeasurement = MeasurementsDatabase.getInstance(MyApplication.getApplication()).getLastMeasurement(); if (lastMeasurement != null) { moveToLocation(lastMeasurement.getLatitude(), lastMeasurement.getLongitude()); } else { Timber.d("moveToLastMeasurement(): No measurements, moving to last known location"); if (GpsUtils.hasGpsPermissions(MyApplication.getApplication())) { LocationManager locationManager = (LocationManager) MyApplication.getApplication().getSystemService(Context.LOCATION_SERVICE); @SuppressLint("MissingPermission") Location lastKnownLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(new Criteria(), false)); if (lastKnownLocation != null) { moveToLocation(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude()); } } } } private void moveToLocation(double lat, double lon) { Timber.d("moveToLocation(): Moving screen to lat=%1$s, lon=%2$s", lat, lon); GeoPoint startPoint = new GeoPoint(lat, lon); mainMapView.getController().setCenter(startPoint); // don't animate because it's used on first load } private void setFollowMe(boolean enable) { if (enable) { Timber.i("onFollowMeClick(): Enabling follow me"); myLocationOverlay.enableFollowLocation(); followMeButton.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.map_follow_me_enabled, theme)); } else { Timber.i("onFollowMeClick(): Disabling follow me"); myLocationOverlay.disableFollowLocation(); followMeButton.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.map_follow_me, theme)); } MyApplication.getPreferencesProvider().setMainMapFollowMeEnabled(myLocationOverlay.isFollowLocationEnabled()); } private Bitmap getClusterIcon() { if (clusterIcon == null) { clusterIcon = ResourceUtils.getDrawableBitmap(MyApplication.getApplication(), R.drawable.dot_cluster); } return clusterIcon; } private boolean reloadTheme() { boolean previousLightTheme = isLightThemeForced; isLightThemeForced = MyApplication.getPreferencesProvider().isMainMapForceLightThemeEnabled(); theme = isLightThemeForced ? new ContextThemeWrapper(getActivity(), R.style.LightAppTheme).getTheme() : getActivity().getTheme(); return previousLightTheme != isLightThemeForced; } private void reloadMapTheme() { myLocationButton.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.map_my_location, theme)); if (MyApplication.getCurrentAppTheme() == R.style.DarkAppTheme && !isLightThemeForced) mainMapView.getOverlayManager().getTilesOverlay().setColorFilter(TilesOverlay.INVERT_COLORS); else mainMapView.getOverlayManager().getTilesOverlay().setColorFilter(null); myLocationOverlay.setDirectionArrow(ResourceUtils.getDrawableBitmap(MyApplication.getApplication(), R.drawable.map_person, theme), ResourceUtils.getDrawableBitmap(MyApplication.getApplication(), R.drawable.map_direction_arrow, theme)); } @Subscribe(threadMode = ThreadMode.MAIN) public void onEvent(MeasurementSavedEvent event) { if (++markersAddedIndividually <= MAX_MARKERS_ADDED_INDIVIDUALLY) { Timber.d("onEvent(): Adding single measurement to the map, added %s of %s", markersAddedIndividually, MAX_MARKERS_ADDED_INDIVIDUALLY); MapMeasurement m = MapMeasurement.fromMeasurement(event.getMeasurement()); markersOverlay.add(createMarker(m)); markersOverlay.invalidate(); } else { reloadMarkers(true); } } @Subscribe(threadMode = ThreadMode.MAIN) public void onEvent(PrintMainWindowEvent event) { reloadMarkers(true); } @Override public void onFollowMyLocationChanged(boolean enabled) { setFollowMe(enabled); } private class BackgroundMarkerLoaderTask extends AsyncTask<Boundaries, Void, RadiusMarkerClusterer> { private final String INNER_TAG = MainMapFragment.class.getSimpleName() + "." + BackgroundMarkerLoaderTask.class.getSimpleName(); private final BoundingBox boundingBox; public BackgroundMarkerLoaderTask(BoundingBox boundingBox) { this.boundingBox = boundingBox; } @Override protected RadiusMarkerClusterer doInBackground(Boundaries... boundariesParams) { RadiusMarkerClusterer result = createMarkersOverlay(); try { Boundaries boundaries = boundariesParams[0]; List<MapMeasurement> measurements = MeasurementsDatabase.getInstance(MyApplication.getApplication()).getMeasurementsInArea(boundaries); for (MapMeasurement m : measurements) { if (isCancelled()) return null; result.add(createMarker(m)); } } catch (Exception ex) { Timber.tag(INNER_TAG).e(ex, "doInBackground(): Failed to load markers"); cancel(false); } if (!isCancelled()) { Timber.tag(INNER_TAG).d("doInBackground(): Loaded %s markers", result.getItems().size()); return result; } Timber.tag(INNER_TAG).d("doInBackground(): Markers loading cancelled"); return null; } @Override protected void onPostExecute(RadiusMarkerClusterer result) { if (!isCancelled() && result != null) { displayMarkers(result); } lastLoadedBoundingBox = boundingBox; backgroundMarkerLoaderTask = null; // reload if scroll/zoom occurred while loading if (missedMapZoomScrollUpdates) { Timber.tag(INNER_TAG).d("onPostExecute(): Missed scroll/zoom updates - reloading"); missedMapZoomScrollUpdates = false; reloadMarkers(true); } } } private static final Marker.OnMarkerClickListener MARKER_CLICK_LISTENER = new Marker.OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker marker, MapView mapView) { if (marker.isInfoWindowShown()) { marker.closeInfoWindow(); } else { marker.showInfoWindow(); } return true; } }; private final View.OnLongClickListener IMAGE_BUTTON_LONG_CLICK_LISTENER = new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast.makeText(getActivity(), v.getContentDescription(), Toast.LENGTH_SHORT).show(); return true; } }; private void registerNetworkCallback() { if (!MyApplication.getPreferencesProvider().isMapUpdatedOnlyOnWifi()) { mainMapView.setUseDataConnection(true); return; } // register for network connectivity changes NetworkRequest.Builder networkRequestBuilder = new NetworkRequest.Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { networkRequestBuilder.addCapability(NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED); } connectivityManager.registerNetworkCallback(networkRequestBuilder.build(), networkCallback); isNetworkCallbackRegistered = true; updateNetworkStatus(); } private void unregisterNetworkCallback() { if (isNetworkCallbackRegistered) { connectivityManager.unregisterNetworkCallback(networkCallback); } isNetworkCallbackRegistered = false; } private final ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(@NonNull Network network) { super.onAvailable(network); updateNetworkStatus(); } @Override public void onLost(@NonNull Network network) { super.onLost(network); updateNetworkStatus(); } @Override public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) { super.onCapabilitiesChanged(network, networkCapabilities); updateNetworkStatus(); } }; private void updateNetworkStatus() { boolean isNetworkMetered = ConnectivityManagerCompat.isActiveNetworkMetered(connectivityManager); mainMapView.setUseDataConnection(!isNetworkMetered); } }
app/src/main/java/info/zamojski/soft/towercollector/views/MainMapFragment.java
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package info.zamojski.soft.towercollector.views; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.location.Criteria; import android.location.Location; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.Network; import android.net.NetworkCapabilities; import android.net.NetworkRequest; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.text.method.LinkMovementMethod; import android.view.InputDevice; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.view.ContextThemeWrapper; import androidx.core.content.res.ResourcesCompat; import androidx.core.net.ConnectivityManagerCompat; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import org.osmdroid.api.IMapController; import org.osmdroid.bonuspack.clustering.RadiusMarkerClusterer; import org.osmdroid.events.DelayedMapListener; import org.osmdroid.events.MapListener; import org.osmdroid.events.ScrollEvent; import org.osmdroid.events.ZoomEvent; import org.osmdroid.tileprovider.tilesource.TileSourceFactory; import org.osmdroid.util.BoundingBox; import org.osmdroid.util.GeoPoint; import org.osmdroid.views.MapView; import org.osmdroid.views.overlay.Marker; import org.osmdroid.views.overlay.ScaleBarOverlay; import org.osmdroid.views.overlay.TilesOverlay; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import info.zamojski.soft.towercollector.MyApplication; import info.zamojski.soft.towercollector.R; import info.zamojski.soft.towercollector.dao.MeasurementsDatabase; import info.zamojski.soft.towercollector.events.MeasurementSavedEvent; import info.zamojski.soft.towercollector.events.PrintMainWindowEvent; import info.zamojski.soft.towercollector.map.FollowMyLocationOverlay; import info.zamojski.soft.towercollector.model.Boundaries; import info.zamojski.soft.towercollector.model.MapCell; import info.zamojski.soft.towercollector.model.MapMeasurement; import info.zamojski.soft.towercollector.model.Measurement; import info.zamojski.soft.towercollector.model.Tuple; import info.zamojski.soft.towercollector.utils.GpsUtils; import info.zamojski.soft.towercollector.utils.MapUtils; import info.zamojski.soft.towercollector.utils.NetworkTypeUtils; import info.zamojski.soft.towercollector.utils.ResourceUtils; import timber.log.Timber; public class MainMapFragment extends MainFragmentBase implements FollowMyLocationOverlay.FollowMyLocationChangeListener { private static final int MAP_DATA_LOAD_DELAY_IN_MILLIS = 200; private static final int MAX_MARKERS_ADDED_INDIVIDUALLY = 500; private static final float BOUNDARIES_INCREASE_FACTOR = 1.2f; // 10% more each side private MapView mainMapView; private FollowMyLocationOverlay myLocationOverlay; private ImageButton followMeButton; private ImageButton myLocationButton; private RadiusMarkerClusterer markersOverlay; private Bitmap clusterIcon; private BackgroundMarkerLoaderTask backgroundMarkerLoaderTask; private boolean missedMapZoomScrollUpdates = false; private int markersAddedIndividually = 0; private BoundingBox lastLoadedBoundingBox = null; private boolean isLightThemeForced; private Resources.Theme theme; private ConnectivityManager connectivityManager; private boolean isNetworkCallbackRegistered = false; private SimpleDateFormat dateTimeFormatStandard; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { MapUtils.configureMap(MyApplication.getApplication()); View rootView = inflater.inflate(R.layout.main_map_fragment, container, false); configureControls(rootView); connectivityManager = (ConnectivityManager) MyApplication.getApplication().getSystemService(Context.CONNECTIVITY_SERVICE); return rootView; } @Override protected void configureOnResume() { super.configureOnResume(); boolean themeChanged = reloadTheme(); if (themeChanged) { reloadMapTheme(); reloadMarkers(true); } registerNetworkCallback(); if (mainMapView != null) { mainMapView.onResume(); } setFollowMe(MyApplication.getPreferencesProvider().isMainMapFollowMeEnabled()); myLocationOverlay.enableMyLocation(); } @Override protected void configureOnPause() { super.configureOnPause(); if (mainMapView != null) mainMapView.onPause(); myLocationOverlay.disableFollowLocation(); myLocationOverlay.disableMyLocation(); unregisterNetworkCallback(); } @Override public void onDestroyView() { super.onDestroyView(); if (backgroundMarkerLoaderTask != null) backgroundMarkerLoaderTask.cancel(false); if (mainMapView != null) mainMapView.onDetach(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); markersOverlay = createMarkersOverlay(); mainMapView.getOverlays().add(markersOverlay); mainMapView.addOnFirstLayoutListener(new MapView.OnFirstLayoutListener() { @Override public void onFirstLayout(View v, int left, int top, int right, int bottom) { Timber.d("onFirstLayout(): Move to last measurement"); moveToLastMeasurement(); } }); } private RadiusMarkerClusterer createMarkersOverlay() { RadiusMarkerClusterer overlay = new RadiusMarkerClusterer(MyApplication.getApplication()); overlay.setIcon(getClusterIcon()); overlay.setRadius(100); overlay.setMaxClusteringZoomLevel(13); return overlay; } @Override protected void configureControls(View view) { super.configureControls(view); reloadTheme(); mainMapView = view.findViewById(R.id.main_map); followMeButton = view.findViewById(R.id.main_map_follow_me_button); followMeButton.setOnLongClickListener(IMAGE_BUTTON_LONG_CLICK_LISTENER); myLocationButton = view.findViewById(R.id.main_map_my_location_button); myLocationButton.setOnLongClickListener(IMAGE_BUTTON_LONG_CLICK_LISTENER); TextView copyrightTextView = view.findViewById(R.id.main_map_copyright); copyrightTextView.setMovementMethod(LinkMovementMethod.getInstance()); mainMapView.setTileSource(TileSourceFactory.MAPNIK); mainMapView.setMultiTouchControls(true); mainMapView.setMinZoomLevel(5.0); mainMapView.setMaxZoomLevel(20.0); IMapController mapController = mainMapView.getController(); mapController.setZoom(MyApplication.getPreferencesProvider().getMainMapZoomLevel()); myLocationOverlay = new FollowMyLocationOverlay(mainMapView); myLocationOverlay.setFollowMyLocationChangeListener(this); myLocationOverlay.setDrawAccuracyEnabled(true); myLocationOverlay.setEnableAutoStop(true); setFollowMe(MyApplication.getPreferencesProvider().isMainMapFollowMeEnabled()); mainMapView.getOverlays().add(myLocationOverlay); ScaleBarOverlay scaleOverlay = new ScaleBarOverlay(mainMapView); scaleOverlay.setAlignBottom(true); scaleOverlay.setUnitsOfMeasure(MyApplication.getPreferencesProvider().getUseImperialUnits() ? ScaleBarOverlay.UnitsOfMeasure.imperial : ScaleBarOverlay.UnitsOfMeasure.metric); mainMapView.getOverlays().add(scaleOverlay); reloadMapTheme(); // configure zoom using mouse wheel mainMapView.setOnGenericMotionListener(new View.OnGenericMotionListener() { @Override public boolean onGenericMotion(View v, MotionEvent event) { if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { if (event.getAction() == MotionEvent.ACTION_SCROLL) { if (event.getAxisValue(MotionEvent.AXIS_VSCROLL) < 0.0f) mainMapView.getController().zoomOut(); else { mainMapView.getController().zoomIn(); } return true; } } return false; } }); myLocationButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Location lastLocation = myLocationOverlay.getLastFix(); Timber.i("onMyLocationClick(): Moving to %s", lastLocation); if (lastLocation != null) { GeoPoint myPosition = new GeoPoint(lastLocation.getLatitude(), lastLocation.getLongitude()); mainMapView.getController().animateTo(myPosition); } } }); followMeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setFollowMe(!myLocationOverlay.isFollowLocationEnabled()); } }); mainMapView.addMapListener(new DelayedMapListener(new MapListener() { private final String INNER_TAG = MainMapFragment.class.getSimpleName() + "." + DelayedMapListener.class.getSimpleName(); @Override public boolean onScroll(ScrollEvent scrollEvent) { Timber.tag(INNER_TAG).d("onScroll(): Scrolling to x=%1$s, y=%2$s", scrollEvent.getX(), scrollEvent.getY()); reloadMarkers(false); return false; } @Override public boolean onZoom(ZoomEvent zoomEvent) { Timber.tag(INNER_TAG).d("onZoom(): Changing zoom level to %s", zoomEvent.getZoomLevel()); MyApplication.getPreferencesProvider().setMainMapZoomLevel((float) zoomEvent.getZoomLevel()); reloadMarkers(true); return false; } }, MAP_DATA_LOAD_DELAY_IN_MILLIS)); dateTimeFormatStandard = new SimpleDateFormat(getString(R.string.date_time_format_standard), new Locale(getString(R.string.locale))); } private void reloadMarkers(boolean force) { if (backgroundMarkerLoaderTask == null) { if (force || lastLoadedBoundingBox == null) { Timber.d("reloadMarkers(): Loading markers due to force=%1$s, lastLoadedBoundingBox=%2$s", force, lastLoadedBoundingBox); Tuple<Boundaries, BoundingBox> boundaries = getVisibleBoundaries(); this.backgroundMarkerLoaderTask = new BackgroundMarkerLoaderTask(boundaries.getItem2()); this.backgroundMarkerLoaderTask.execute(boundaries.getItem1()); } else { BoundingBox boundingBox = mainMapView.getProjection().getBoundingBox(); double north = boundingBox.getActualNorth(); double south = boundingBox.getActualSouth(); double east = boundingBox.getLonEast(); double west = boundingBox.getLonWest(); if (!lastLoadedBoundingBox.contains(north, east) || !lastLoadedBoundingBox.contains(north, west) || !lastLoadedBoundingBox.contains(south, east) || !lastLoadedBoundingBox.contains(south, west)) { Timber.d("reloadMarkers(): No overlap between new and previously loaded bounding boxes"); reloadMarkers(true); } else { Timber.d("reloadMarkers(): New and previously loaded bounding boxes overlap, skipping load"); } } } else { // background load is active, we miss the scroll/zoom missedMapZoomScrollUpdates = true; } } private void displayMarkers(RadiusMarkerClusterer newMarkersOverlay) { mainMapView.getOverlays().remove(markersOverlay); markersOverlay.onDetach(mainMapView); markersOverlay = newMarkersOverlay; mainMapView.getOverlays().add(markersOverlay); if (mainMapView.isAnimating()) { mainMapView.postInvalidate(); } else { mainMapView.invalidate(); } markersAddedIndividually = 0; } private Tuple<Boundaries, BoundingBox> getVisibleBoundaries() { BoundingBox boundingBox = mainMapView.getProjection().getBoundingBox(); BoundingBox boundingBoxWithReserve = boundingBox.increaseByScale(BOUNDARIES_INCREASE_FACTOR); double minLat = boundingBoxWithReserve.getActualSouth(); double maxLat = boundingBoxWithReserve.getActualNorth(); double minLon = boundingBoxWithReserve.getLonWest(); double maxLon = boundingBoxWithReserve.getLonEast(); // when passing date line if (maxLon < minLon) { double swap = minLon; minLon = maxLon; maxLon = swap; } return new Tuple<Boundaries, BoundingBox>(new Boundaries(minLat, minLon, maxLat, maxLon), boundingBoxWithReserve); } private Marker createMarker(MapMeasurement m) { List<MapCell> mainCells = m.getMainCells(); @DrawableRes int iconId; if (mainCells.size() == 1) { iconId = NetworkTypeUtils.getNetworkGroupIcon(mainCells.get(0).getNetworkType()); } else { iconId = NetworkTypeUtils.getNetworkGroupIcon(mainCells.get(0).getNetworkType(), mainCells.get(1).getNetworkType()); } Marker item = new Marker(mainMapView); item.setIcon(ResourcesCompat.getDrawable(getResources(), iconId, theme)); item.setTitle(dateTimeFormatStandard.format(new Date(m.getMeasuredAt()))); item.setSnippet(String.valueOf(m.getDescription(MyApplication.getApplication()))); item.setPosition(new GeoPoint(m.getLatitude(), m.getLongitude())); item.setAnchor(0.5f, 0.5f); item.setOnMarkerClickListener(MARKER_CLICK_LISTENER); return item; } private void moveToLastMeasurement() { Measurement lastMeasurement = MeasurementsDatabase.getInstance(MyApplication.getApplication()).getLastMeasurement(); if (lastMeasurement != null) { moveToLocation(lastMeasurement.getLatitude(), lastMeasurement.getLongitude()); } else { Timber.d("moveToLastMeasurement(): No measurements, moving to last known location"); if (GpsUtils.hasGpsPermissions(MyApplication.getApplication())) { LocationManager locationManager = (LocationManager) MyApplication.getApplication().getSystemService(Context.LOCATION_SERVICE); @SuppressLint("MissingPermission") Location lastKnownLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(new Criteria(), false)); if (lastKnownLocation != null) { moveToLocation(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude()); } } } } private void moveToLocation(double lat, double lon) { Timber.d("moveToLocation(): Moving screen to lat=%1$s, lon=%2$s", lat, lon); GeoPoint startPoint = new GeoPoint(lat, lon); mainMapView.getController().setCenter(startPoint); // don't animate because it's used on first load } private void setFollowMe(boolean enable) { if (enable) { Timber.i("onFollowMeClick(): Enabling follow me"); myLocationOverlay.enableFollowLocation(); followMeButton.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.map_follow_me_enabled, theme)); } else { Timber.i("onFollowMeClick(): Disabling follow me"); myLocationOverlay.disableFollowLocation(); followMeButton.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.map_follow_me, theme)); } MyApplication.getPreferencesProvider().setMainMapFollowMeEnabled(myLocationOverlay.isFollowLocationEnabled()); } private Bitmap getClusterIcon() { if (clusterIcon == null) { clusterIcon = ResourceUtils.getDrawableBitmap(MyApplication.getApplication(), R.drawable.dot_cluster); } return clusterIcon; } private boolean reloadTheme() { boolean previousLightTheme = isLightThemeForced; isLightThemeForced = MyApplication.getPreferencesProvider().isMainMapForceLightThemeEnabled(); theme = isLightThemeForced ? new ContextThemeWrapper(getActivity(), R.style.LightAppTheme).getTheme() : getActivity().getTheme(); return previousLightTheme != isLightThemeForced; } private void reloadMapTheme() { myLocationButton.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.map_my_location, theme)); if (MyApplication.getCurrentAppTheme() == R.style.DarkAppTheme && !isLightThemeForced) mainMapView.getOverlayManager().getTilesOverlay().setColorFilter(TilesOverlay.INVERT_COLORS); else mainMapView.getOverlayManager().getTilesOverlay().setColorFilter(null); myLocationOverlay.setDirectionArrow(ResourceUtils.getDrawableBitmap(MyApplication.getApplication(), R.drawable.map_person, theme), ResourceUtils.getDrawableBitmap(MyApplication.getApplication(), R.drawable.map_direction_arrow, theme)); } @Subscribe(threadMode = ThreadMode.MAIN) public void onEvent(MeasurementSavedEvent event) { if (++markersAddedIndividually <= MAX_MARKERS_ADDED_INDIVIDUALLY) { Timber.d("onEvent(): Adding single measurement to the map, added %s of %s", markersAddedIndividually, MAX_MARKERS_ADDED_INDIVIDUALLY); MapMeasurement m = MapMeasurement.fromMeasurement(event.getMeasurement()); markersOverlay.add(createMarker(m)); markersOverlay.invalidate(); } else { reloadMarkers(true); } } @Subscribe(threadMode = ThreadMode.MAIN) public void onEvent(PrintMainWindowEvent event) { reloadMarkers(true); } @Override public void onFollowMyLocationChanged(boolean enabled) { setFollowMe(enabled); } private class BackgroundMarkerLoaderTask extends AsyncTask<Boundaries, Void, RadiusMarkerClusterer> { private final String INNER_TAG = MainMapFragment.class.getSimpleName() + "." + BackgroundMarkerLoaderTask.class.getSimpleName(); private final BoundingBox boundingBox; public BackgroundMarkerLoaderTask(BoundingBox boundingBox) { this.boundingBox = boundingBox; } @Override protected RadiusMarkerClusterer doInBackground(Boundaries... boundariesParams) { RadiusMarkerClusterer result = createMarkersOverlay(); try { Boundaries boundaries = boundariesParams[0]; List<MapMeasurement> measurements = MeasurementsDatabase.getInstance(MyApplication.getApplication()).getMeasurementsInArea(boundaries); for (MapMeasurement m : measurements) { if (isCancelled()) return null; result.add(createMarker(m)); } } catch (Exception ex) { Timber.tag(INNER_TAG).e(ex, "doInBackground(): Failed to load markers"); cancel(false); } if (!isCancelled()) { Timber.tag(INNER_TAG).d("doInBackground(): Loaded %s markers", result.getItems().size()); return result; } Timber.tag(INNER_TAG).d("doInBackground(): Markers loading cancelled"); return null; } @Override protected void onPostExecute(RadiusMarkerClusterer result) { if (!isCancelled() && result != null) { displayMarkers(result); } lastLoadedBoundingBox = boundingBox; backgroundMarkerLoaderTask = null; // reload if scroll/zoom occurred while loading if (missedMapZoomScrollUpdates) { Timber.tag(INNER_TAG).d("onPostExecute(): Missed scroll/zoom updates - reloading"); missedMapZoomScrollUpdates = false; reloadMarkers(true); } } } private static final Marker.OnMarkerClickListener MARKER_CLICK_LISTENER = new Marker.OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker marker, MapView mapView) { marker.showInfoWindow(); return true; } }; private final View.OnLongClickListener IMAGE_BUTTON_LONG_CLICK_LISTENER = new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast.makeText(getActivity(), v.getContentDescription(), Toast.LENGTH_SHORT).show(); return true; } }; private void registerNetworkCallback() { if (!MyApplication.getPreferencesProvider().isMapUpdatedOnlyOnWifi()) { mainMapView.setUseDataConnection(true); return; } // register for network connectivity changes NetworkRequest.Builder networkRequestBuilder = new NetworkRequest.Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { networkRequestBuilder.addCapability(NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED); } connectivityManager.registerNetworkCallback(networkRequestBuilder.build(), networkCallback); isNetworkCallbackRegistered = true; updateNetworkStatus(); } private void unregisterNetworkCallback() { if (isNetworkCallbackRegistered) { connectivityManager.unregisterNetworkCallback(networkCallback); } isNetworkCallbackRegistered = false; } private final ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(@NonNull Network network) { super.onAvailable(network); updateNetworkStatus(); } @Override public void onLost(@NonNull Network network) { super.onLost(network); updateNetworkStatus(); } @Override public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) { super.onCapabilitiesChanged(network, networkCapabilities); updateNetworkStatus(); } }; private void updateNetworkStatus() { boolean isNetworkMetered = ConnectivityManagerCompat.isActiveNetworkMetered(connectivityManager); mainMapView.setUseDataConnection(!isNetworkMetered); } }
Hide marker tooltip on second click. Closes #110.
app/src/main/java/info/zamojski/soft/towercollector/views/MainMapFragment.java
Hide marker tooltip on second click.
<ide><path>pp/src/main/java/info/zamojski/soft/towercollector/views/MainMapFragment.java <ide> private static final Marker.OnMarkerClickListener MARKER_CLICK_LISTENER = new Marker.OnMarkerClickListener() { <ide> @Override <ide> public boolean onMarkerClick(Marker marker, MapView mapView) { <del> marker.showInfoWindow(); <add> if (marker.isInfoWindowShown()) { <add> marker.closeInfoWindow(); <add> } else { <add> marker.showInfoWindow(); <add> } <ide> return true; <ide> } <ide> };
Java
apache-2.0
8cf80b129dfd43385e5dcf06f9e2400f92912735
0
codepoke/libgdx,codepoke/libgdx,codepoke/libgdx,codepoke/libgdx,codepoke/libgdx,codepoke/libgdx,codepoke/libgdx,codepoke/libgdx
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.tools.flame; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableModel; import com.badlogic.gdx.graphics.g3d.particles.ParticleController; import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsInfluencer; import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier; import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier.BrownianAcceleration; import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier.CentripetalAcceleration; import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier.FaceDirection2D; import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier.PolarAcceleration; import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier.Rotational3D; import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier.TangentialAcceleration; import com.badlogic.gdx.tools.flame.FlameMain.ControllerType; import com.badlogic.gdx.utils.Array; /** @author Inferno */ public class DynamicsInfluencerPanel extends InfluencerPanel<DynamicsInfluencer> { private static final String VEL_TYPE_ROTATIONAL_2D = "Angular Velocity 2D", VEL_TYPE_ROTATIONAL_3D = "Angular Velocity 3D", VEL_TYPE_CENTRIPETAL = "Centripetal", VEL_TYPE_TANGENTIAL = "Tangential", VEL_TYPE_POLAR = "Polar", VEL_TYPE_BROWNIAN = "Brownian", VEL_TYPE_FACE = "Face", VEL_TYPE_FACE_2D = "Face 2D"; protected class VelocityWrapper { public DynamicsModifier velocityValue; public boolean isActive; public VelocityWrapper (DynamicsModifier value, boolean isActive) { this.velocityValue = value; this.isActive = isActive; } } JComboBox velocityBox; JTable velocityTable; DefaultTableModel velocityTableModel; JPanel selectedVelocityPanel; AngularVelocityPanel angularVelocityPanel; StrengthVelocityPanel strengthVelocityPanel; ParticleValuePanel emptyPanel; Array<VelocityWrapper> velocities; public DynamicsInfluencerPanel (FlameMain editor, DynamicsInfluencer influencer) { super(editor, influencer, "Dynamics Influencer", "Defines how the particles dynamics (acceleration, angular velocity)."); velocities = new Array<VelocityWrapper>(); setValue(value); set(influencer); } private void set (DynamicsInfluencer influencer) { // Clear for (int i = velocityTableModel.getRowCount() - 1; i >= 0; i--) { velocityTableModel.removeRow(i); } velocities.clear(); // Add for (int i = 0, c = influencer.velocities.size; i < c; ++i) { velocities.add(new VelocityWrapper((DynamicsModifier)influencer.velocities.items[i], true)); velocityTableModel.addRow(new Object[] {"Velocity " + i, true}); } DefaultComboBoxModel model = (DefaultComboBoxModel)velocityBox.getModel(); model.removeAllElements(); for (Object velocityObject : getAvailableVelocities(editor.getControllerType())) { model.addElement(velocityObject); } } private Object[] getAvailableVelocities (ControllerType type) { if (type == ControllerType.Billboard || type == ControllerType.PointSprite) { return new String[] {VEL_TYPE_ROTATIONAL_2D, VEL_TYPE_CENTRIPETAL, VEL_TYPE_TANGENTIAL, VEL_TYPE_POLAR, VEL_TYPE_BROWNIAN, VEL_TYPE_FACE_2D}; } else if (type == ControllerType.ModelInstance || type == ControllerType.ParticleController) { return new String[] {VEL_TYPE_ROTATIONAL_3D, VEL_TYPE_CENTRIPETAL, VEL_TYPE_TANGENTIAL, VEL_TYPE_POLAR, VEL_TYPE_BROWNIAN, VEL_TYPE_FACE}; } return null; } protected void initializeComponents () { super.initializeComponents(); JPanel velocitiesPanel = new JPanel(); velocitiesPanel.setLayout(new GridBagLayout()); { JPanel sideButtons = new JPanel(new GridBagLayout()); velocitiesPanel.add(sideButtons, new GridBagConstraints(1, 0, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); { sideButtons.add(velocityBox = new JComboBox(new DefaultComboBoxModel()), new GridBagConstraints(0, -1, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 6, 0), 0, 0)); } { JButton newButton = new JButton("New"); sideButtons.add(newButton, new GridBagConstraints(0, -1, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 6, 0), 0, 0)); newButton.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent event) { createVelocity(velocityBox.getSelectedItem()); } }); } { JButton deleteButton = new JButton("Delete"); sideButtons.add(deleteButton, new GridBagConstraints(0, -1, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 6, 0), 0, 0)); deleteButton.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent event) { deleteVelocity(); } }); } } JScrollPane scroll = new JScrollPane(); velocitiesPanel.add(scroll, new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 6), 0, 0)); velocityTable = new JTable() { public Class getColumnClass (int column) { return column == 1 ? Boolean.class : super.getColumnClass(column); } @Override public Dimension getPreferredScrollableViewportSize () { Dimension dim = super.getPreferredScrollableViewportSize(); dim.height = getPreferredSize().height; return dim; } }; velocityTable.getTableHeader().setReorderingAllowed(false); velocityTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); scroll.setViewportView(velocityTable); velocityTableModel = new DefaultTableModel(new String[0][0], new String[] {"Velocity", "Active"}); velocityTable.setModel(velocityTableModel); velocityTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged (ListSelectionEvent event) { if (event.getValueIsAdjusting()) return; velocitySelected(); } }); velocityTableModel.addTableModelListener(new TableModelListener() { public void tableChanged (TableModelEvent event) { if (event.getColumn() != 1) return; velocityChecked(event.getFirstRow(), (Boolean)velocityTable.getValueAt(event.getFirstRow(), 1)); } }); // Velocity values emptyPanel = new ParticleValuePanel(editor, "", "", true, false); strengthVelocityPanel = new StrengthVelocityPanel(editor, null, "Life", "", ""); angularVelocityPanel = new AngularVelocityPanel(editor, null, "Life", "", ""); strengthVelocityPanel.setVisible(false); angularVelocityPanel.setVisible(false); emptyPanel.setVisible(false); strengthVelocityPanel.setIsAlwayShown(true); angularVelocityPanel.setIsAlwayShown(true); emptyPanel.setIsAlwayShown(true); // emptyPanel.setValue(null); // Assemble int i = 0; addContent(i++, 0, velocitiesPanel); addContent(i++, 0, strengthVelocityPanel); addContent(i++, 0, angularVelocityPanel); addContent(i++, 0, emptyPanel); } protected void velocityChecked (int index, boolean isChecked) { ParticleController controller = editor.getEmitter(); DynamicsInfluencer influencer = (DynamicsInfluencer)controller.findInfluencer(DynamicsInfluencer.class); influencer.velocities.clear(); velocities.get(index).isActive = isChecked; for (VelocityWrapper wrapper : velocities) { if (wrapper.isActive) influencer.velocities.add(wrapper.velocityValue); } // Restart the effect and reinit the controller editor.restart(); } protected void velocitySelected () { // Show the velocity value panel int index = velocityTable.getSelectedRow(); if (index == -1) return; DynamicsModifier velocityValue = velocities.get(index).velocityValue; EditorPanel velocityPanel = getVelocityPanel(velocityValue); // Show the selected velocity if (selectedVelocityPanel != null && selectedVelocityPanel != velocityPanel) selectedVelocityPanel.setVisible(false); velocityPanel.setVisible(true); velocityPanel.showContent(true); selectedVelocityPanel = velocityPanel; } private EditorPanel getVelocityPanel (DynamicsModifier velocityValue) { EditorPanel panel = null; // Billboards if (velocityValue instanceof DynamicsModifier.Rotational2D) { strengthVelocityPanel.setValue((DynamicsModifier.Strength)velocityValue); strengthVelocityPanel.setName("Angular Velocity"); strengthVelocityPanel.setDescription("The angular speed around the billboard facing direction, in degrees/sec ."); panel = strengthVelocityPanel; } else if (velocityValue instanceof CentripetalAcceleration) { strengthVelocityPanel.setValue((DynamicsModifier.CentripetalAcceleration)velocityValue); strengthVelocityPanel.setName("Centripetal Acceleration"); strengthVelocityPanel.setDescription( "A directional acceleration, the direction is towards the origin (global), or towards the emitter position (local), in world units/sec2 ."); panel = strengthVelocityPanel; } else if (velocityValue instanceof TangentialAcceleration) { angularVelocityPanel.setValue((DynamicsModifier.Angular)velocityValue); angularVelocityPanel.setName("Tangetial Velocity"); angularVelocityPanel.setDescription( "A directional acceleration (axis and magnitude), the final direction is the cross product between particle position and the axis, in world units/sec2 ."); panel = angularVelocityPanel; } else if (velocityValue instanceof PolarAcceleration) { angularVelocityPanel.setValue((DynamicsModifier.Angular)velocityValue); angularVelocityPanel.setName("Polar Velocity"); angularVelocityPanel.setDescription("A directional acceleration (axis and magnitude), in world units/sec2 ."); panel = angularVelocityPanel; } else if (velocityValue instanceof BrownianAcceleration) { strengthVelocityPanel.setValue((DynamicsModifier.Strength)velocityValue); strengthVelocityPanel.setName("Brownian Velocity"); strengthVelocityPanel .setDescription("A directional acceleration which has random direction at each update, in world units/sec2."); panel = strengthVelocityPanel; } else if (velocityValue instanceof Rotational3D) { angularVelocityPanel.setValue((DynamicsModifier.Angular)velocityValue); angularVelocityPanel.setName("Angular Velocity"); angularVelocityPanel.setDescription("An angular velocity (axis and magnitude), in degree/sec2."); panel = angularVelocityPanel; } else if (velocityValue instanceof FaceDirection2D) { emptyPanel.setName("Face 2D"); emptyPanel.setDescription( "Rotates the billboard to align with its motion on the screen (Do not add any other angular velocity when using this)."); panel = emptyPanel; } return panel; } private DynamicsModifier createVelocityValue (Object selectedItem) { DynamicsModifier velocityValue = null; if (selectedItem == VEL_TYPE_ROTATIONAL_2D) velocityValue = new DynamicsModifier.Rotational2D(); else if (selectedItem == VEL_TYPE_ROTATIONAL_3D) velocityValue = new DynamicsModifier.Rotational3D(); else if (selectedItem == VEL_TYPE_CENTRIPETAL) velocityValue = new DynamicsModifier.CentripetalAcceleration(); else if (selectedItem == VEL_TYPE_TANGENTIAL) velocityValue = new DynamicsModifier.TangentialAcceleration(); else if (selectedItem == VEL_TYPE_POLAR) velocityValue = new DynamicsModifier.PolarAcceleration(); else if (selectedItem == VEL_TYPE_BROWNIAN) velocityValue = new DynamicsModifier.BrownianAcceleration(); else if (selectedItem == VEL_TYPE_FACE) velocityValue = new DynamicsModifier.FaceDirection(); else if (selectedItem == VEL_TYPE_FACE_2D) velocityValue = new DynamicsModifier.FaceDirection2D(); return velocityValue; } protected void deleteVelocity () { int row = velocityTable.getSelectedRow(); if (row == -1) return; // Remove the velocity from the table ParticleController controller = editor.getEmitter(); DynamicsInfluencer influencer = (DynamicsInfluencer)controller.findInfluencer(DynamicsInfluencer.class); influencer.velocities.removeValue(velocities.removeIndex(row).velocityValue, true); velocityTableModel.removeRow(row); // Restart the effect and reinit the controller editor.restart(); selectedVelocityPanel.setVisible(false); selectedVelocityPanel = null; } protected void createVelocity (Object selectedItem) { // Add the velocity to the table and to the influencer ParticleController controller = editor.getEmitter(); DynamicsInfluencer influencer = (DynamicsInfluencer)controller.findInfluencer(DynamicsInfluencer.class); VelocityWrapper wrapper = new VelocityWrapper(createVelocityValue(selectedItem), true); velocities.add(wrapper); influencer.velocities.add(wrapper.velocityValue); int index = velocities.size - 1; velocityTableModel.addRow(new Object[] {"Velocity " + index, true}); // Reinit editor.restart(); // Select new velocity velocityTable.getSelectionModel().setSelectionInterval(index, index); revalidate(); repaint(); } }
extensions/gdx-tools/src/com/badlogic/gdx/tools/flame/DynamicsInfluencerPanel.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.tools.flame; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableModel; import com.badlogic.gdx.graphics.g3d.particles.ParticleController; import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsInfluencer; import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier; import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier.BrownianAcceleration; import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier.CentripetalAcceleration; import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier.FaceDirection; import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier.PolarAcceleration; import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier.Rotational3D; import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier.TangentialAcceleration; import com.badlogic.gdx.tools.flame.FlameMain.ControllerType; import com.badlogic.gdx.utils.Array; /** @author Inferno */ public class DynamicsInfluencerPanel extends InfluencerPanel<DynamicsInfluencer> { private static final String VEL_TYPE_ROTATIONAL_2D = "Angular Velocity 2D", VEL_TYPE_ROTATIONAL_3D = "Angular Velocity 3D", VEL_TYPE_CENTRIPETAL = "Centripetal", VEL_TYPE_TANGENTIAL = "Tangential", VEL_TYPE_POLAR = "Polar", VEL_TYPE_BROWNIAN = "Brownian", VEL_TYPE_FACE = "Face", VEL_TYPE_FACE_2D = "Face 2D"; protected class VelocityWrapper { public DynamicsModifier velocityValue; public boolean isActive; public VelocityWrapper (DynamicsModifier value, boolean isActive) { this.velocityValue = value; this.isActive = isActive; } } JComboBox velocityBox; JTable velocityTable; DefaultTableModel velocityTableModel; JPanel selectedVelocityPanel; AngularVelocityPanel angularVelocityPanel; StrengthVelocityPanel strengthVelocityPanel; ParticleValuePanel emptyPanel; Array<VelocityWrapper> velocities; public DynamicsInfluencerPanel (FlameMain editor, DynamicsInfluencer influencer) { super(editor, influencer, "Dynamics Influencer", "Defines how the particles dynamics (acceleration, angular velocity)."); velocities = new Array<VelocityWrapper>(); setValue(value); set(influencer); } private void set (DynamicsInfluencer influencer) { // Clear for (int i = velocityTableModel.getRowCount() - 1; i >= 0; i--) { velocityTableModel.removeRow(i); } velocities.clear(); // Add for (int i = 0, c = influencer.velocities.size; i < c; ++i) { velocities.add(new VelocityWrapper((DynamicsModifier)influencer.velocities.items[i], true)); velocityTableModel.addRow(new Object[] {"Velocity " + i, true}); } DefaultComboBoxModel model = (DefaultComboBoxModel)velocityBox.getModel(); model.removeAllElements(); for (Object velocityObject : getAvailableVelocities(editor.getControllerType())) { model.addElement(velocityObject); } } private Object[] getAvailableVelocities (ControllerType type) { if (type == ControllerType.Billboard || type == ControllerType.PointSprite) { return new String[] {VEL_TYPE_ROTATIONAL_2D, VEL_TYPE_CENTRIPETAL, VEL_TYPE_TANGENTIAL, VEL_TYPE_POLAR, VEL_TYPE_BROWNIAN, VEL_TYPE_FACE_2D}; } else if (type == ControllerType.ModelInstance || type == ControllerType.ParticleController) { return new String[] {VEL_TYPE_ROTATIONAL_3D, VEL_TYPE_CENTRIPETAL, VEL_TYPE_TANGENTIAL, VEL_TYPE_POLAR, VEL_TYPE_BROWNIAN, VEL_TYPE_FACE}; } return null; } protected void initializeComponents () { super.initializeComponents(); JPanel velocitiesPanel = new JPanel(); velocitiesPanel.setLayout(new GridBagLayout()); { JPanel sideButtons = new JPanel(new GridBagLayout()); velocitiesPanel.add(sideButtons, new GridBagConstraints(1, 0, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); { sideButtons.add(velocityBox = new JComboBox(new DefaultComboBoxModel()), new GridBagConstraints(0, -1, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 6, 0), 0, 0)); } { JButton newButton = new JButton("New"); sideButtons.add(newButton, new GridBagConstraints(0, -1, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 6, 0), 0, 0)); newButton.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent event) { createVelocity(velocityBox.getSelectedItem()); } }); } { JButton deleteButton = new JButton("Delete"); sideButtons.add(deleteButton, new GridBagConstraints(0, -1, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 6, 0), 0, 0)); deleteButton.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent event) { deleteVelocity(); } }); } } JScrollPane scroll = new JScrollPane(); velocitiesPanel.add(scroll, new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 6), 0, 0)); velocityTable = new JTable() { public Class getColumnClass (int column) { return column == 1 ? Boolean.class : super.getColumnClass(column); } @Override public Dimension getPreferredScrollableViewportSize () { Dimension dim = super.getPreferredScrollableViewportSize(); dim.height = getPreferredSize().height; return dim; } }; velocityTable.getTableHeader().setReorderingAllowed(false); velocityTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); scroll.setViewportView(velocityTable); velocityTableModel = new DefaultTableModel(new String[0][0], new String[] {"Velocity", "Active"}); velocityTable.setModel(velocityTableModel); velocityTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged (ListSelectionEvent event) { if (event.getValueIsAdjusting()) return; velocitySelected(); } }); velocityTableModel.addTableModelListener(new TableModelListener() { public void tableChanged (TableModelEvent event) { if (event.getColumn() != 1) return; velocityChecked(event.getFirstRow(), (Boolean)velocityTable.getValueAt(event.getFirstRow(), 1)); } }); // Velocity values emptyPanel = new ParticleValuePanel(editor, "", "", true, false); strengthVelocityPanel = new StrengthVelocityPanel(editor, null, "Life", "", ""); angularVelocityPanel = new AngularVelocityPanel(editor, null, "Life", "", ""); strengthVelocityPanel.setVisible(false); angularVelocityPanel.setVisible(false); emptyPanel.setVisible(false); strengthVelocityPanel.setIsAlwayShown(true); angularVelocityPanel.setIsAlwayShown(true); emptyPanel.setIsAlwayShown(true); emptyPanel.setValue(null); // Assemble int i = 0; addContent(i++, 0, velocitiesPanel); addContent(i++, 0, strengthVelocityPanel); addContent(i++, 0, angularVelocityPanel); addContent(i++, 0, emptyPanel); } protected void velocityChecked (int index, boolean isChecked) { ParticleController controller = editor.getEmitter(); DynamicsInfluencer influencer = (DynamicsInfluencer)controller.findInfluencer(DynamicsInfluencer.class); influencer.velocities.clear(); velocities.get(index).isActive = isChecked; for (VelocityWrapper wrapper : velocities) { if (wrapper.isActive) influencer.velocities.add(wrapper.velocityValue); } // Restart the effect and reinit the controller editor.restart(); } protected void velocitySelected () { // Show the velocity value panel int index = velocityTable.getSelectedRow(); if (index == -1) return; DynamicsModifier velocityValue = velocities.get(index).velocityValue; EditorPanel velocityPanel = getVelocityPanel(velocityValue); // Show the selected velocity if (selectedVelocityPanel != null && selectedVelocityPanel != velocityPanel) selectedVelocityPanel.setVisible(false); velocityPanel.setVisible(true); velocityPanel.showContent(true); selectedVelocityPanel = velocityPanel; } private EditorPanel getVelocityPanel (DynamicsModifier velocityValue) { EditorPanel panel = null; // Billboards if (velocityValue instanceof DynamicsModifier.Rotational2D) { strengthVelocityPanel.setValue((DynamicsModifier.Strength)velocityValue); strengthVelocityPanel.setName("Angular Velocity"); strengthVelocityPanel.setDescription("The angular speed around the billboard facing direction, in degrees/sec ."); panel = strengthVelocityPanel; } else if (velocityValue instanceof CentripetalAcceleration) { strengthVelocityPanel.setValue((DynamicsModifier.CentripetalAcceleration)velocityValue); strengthVelocityPanel.setName("Centripetal Acceleration"); strengthVelocityPanel.setDescription( "A directional acceleration, the direction is towards the origin (global), or towards the emitter position (local), in world units/sec2 ."); panel = strengthVelocityPanel; } else if (velocityValue instanceof TangentialAcceleration) { angularVelocityPanel.setValue((DynamicsModifier.Angular)velocityValue); angularVelocityPanel.setName("Tangetial Velocity"); angularVelocityPanel.setDescription( "A directional acceleration (axis and magnitude), the final direction is the cross product between particle position and the axis, in world units/sec2 ."); panel = angularVelocityPanel; } else if (velocityValue instanceof PolarAcceleration) { angularVelocityPanel.setValue((DynamicsModifier.Angular)velocityValue); angularVelocityPanel.setName("Polar Velocity"); angularVelocityPanel.setDescription("A directional acceleration (axis and magnitude), in world units/sec2 ."); panel = angularVelocityPanel; } else if (velocityValue instanceof BrownianAcceleration) { strengthVelocityPanel.setValue((DynamicsModifier.Strength)velocityValue); strengthVelocityPanel.setName("Brownian Velocity"); strengthVelocityPanel .setDescription("A directional acceleration which has random direction at each update, in world units/sec2."); panel = strengthVelocityPanel; } else if (velocityValue instanceof Rotational3D) { angularVelocityPanel.setValue((DynamicsModifier.Angular)velocityValue); angularVelocityPanel.setName("Angular Velocity"); angularVelocityPanel.setDescription("An angular velocity (axis and magnitude), in degree/sec2."); panel = angularVelocityPanel; } else if (velocityValue instanceof FaceDirection) { emptyPanel.setName("Face"); emptyPanel.setDescription( "Rotates the model to face its current velocity (Do not add any other angular velocity when using this)."); panel = emptyPanel; } return panel; } private DynamicsModifier createVelocityValue (Object selectedItem) { DynamicsModifier velocityValue = null; if (selectedItem == VEL_TYPE_ROTATIONAL_2D) velocityValue = new DynamicsModifier.Rotational2D(); else if (selectedItem == VEL_TYPE_ROTATIONAL_3D) velocityValue = new DynamicsModifier.Rotational3D(); else if (selectedItem == VEL_TYPE_CENTRIPETAL) velocityValue = new DynamicsModifier.CentripetalAcceleration(); else if (selectedItem == VEL_TYPE_TANGENTIAL) velocityValue = new DynamicsModifier.TangentialAcceleration(); else if (selectedItem == VEL_TYPE_POLAR) velocityValue = new DynamicsModifier.PolarAcceleration(); else if (selectedItem == VEL_TYPE_BROWNIAN) velocityValue = new DynamicsModifier.BrownianAcceleration(); else if (selectedItem == VEL_TYPE_FACE) velocityValue = new DynamicsModifier.FaceDirection(); else if (selectedItem == VEL_TYPE_FACE_2D) velocityValue = new DynamicsModifier.FaceDirection2D(); return velocityValue; } protected void deleteVelocity () { int row = velocityTable.getSelectedRow(); if (row == -1) return; // Remove the velocity from the table ParticleController controller = editor.getEmitter(); DynamicsInfluencer influencer = (DynamicsInfluencer)controller.findInfluencer(DynamicsInfluencer.class); influencer.velocities.removeValue(velocities.removeIndex(row).velocityValue, true); velocityTableModel.removeRow(row); // Restart the effect and reinit the controller editor.restart(); selectedVelocityPanel.setVisible(false); selectedVelocityPanel = null; } protected void createVelocity (Object selectedItem) { // Add the velocity to the table and to the influencer ParticleController controller = editor.getEmitter(); DynamicsInfluencer influencer = (DynamicsInfluencer)controller.findInfluencer(DynamicsInfluencer.class); VelocityWrapper wrapper = new VelocityWrapper(createVelocityValue(selectedItem), true); velocities.add(wrapper); influencer.velocities.add(wrapper.velocityValue); int index = velocities.size - 1; velocityTableModel.addRow(new Object[] {"Velocity " + index, true}); // Reinit editor.restart(); // Select new velocity velocityTable.getSelectionModel().setSelectionInterval(index, index); revalidate(); repaint(); } }
Fixed a nullpointer caused by looking up the incorrect DynamicsModifier.
extensions/gdx-tools/src/com/badlogic/gdx/tools/flame/DynamicsInfluencerPanel.java
Fixed a nullpointer caused by looking up the incorrect DynamicsModifier.
<ide><path>xtensions/gdx-tools/src/com/badlogic/gdx/tools/flame/DynamicsInfluencerPanel.java <ide> import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier; <ide> import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier.BrownianAcceleration; <ide> import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier.CentripetalAcceleration; <del>import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier.FaceDirection; <add>import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier.FaceDirection2D; <ide> import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier.PolarAcceleration; <ide> import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier.Rotational3D; <ide> import com.badlogic.gdx.graphics.g3d.particles.influencers.DynamicsModifier.TangentialAcceleration; <ide> strengthVelocityPanel.setIsAlwayShown(true); <ide> angularVelocityPanel.setIsAlwayShown(true); <ide> emptyPanel.setIsAlwayShown(true); <del> emptyPanel.setValue(null); <add> // emptyPanel.setValue(null); <ide> <ide> // Assemble <ide> int i = 0; <ide> angularVelocityPanel.setName("Angular Velocity"); <ide> angularVelocityPanel.setDescription("An angular velocity (axis and magnitude), in degree/sec2."); <ide> panel = angularVelocityPanel; <del> } else if (velocityValue instanceof FaceDirection) { <del> emptyPanel.setName("Face"); <add> } else if (velocityValue instanceof FaceDirection2D) { <add> emptyPanel.setName("Face 2D"); <ide> emptyPanel.setDescription( <del> "Rotates the model to face its current velocity (Do not add any other angular velocity when using this)."); <add> "Rotates the billboard to align with its motion on the screen (Do not add any other angular velocity when using this)."); <ide> panel = emptyPanel; <ide> } <ide>
Java
apache-2.0
2f5c79d05290ced708e8d086c89be274c860e35e
0
codescale/logging-log4j2,xnslong/logging-log4j2,apache/logging-log4j2,neuro-sys/logging-log4j2,lburgazzoli/apache-logging-log4j2,apache/logging-log4j2,neuro-sys/logging-log4j2,renchunxiao/logging-log4j2,GFriedrich/logging-log4j2,ChetnaChaudhari/logging-log4j2,lburgazzoli/logging-log4j2,lqbweb/logging-log4j2,pisfly/logging-log4j2,lburgazzoli/apache-logging-log4j2,jsnikhil/nj-logging-log4j2,GFriedrich/logging-log4j2,pisfly/logging-log4j2,lburgazzoli/logging-log4j2,lburgazzoli/logging-log4j2,lqbweb/logging-log4j2,MagicWiz/log4j2,lburgazzoli/apache-logging-log4j2,jinxuan/logging-log4j2,jsnikhil/nj-logging-log4j2,lqbweb/logging-log4j2,xnslong/logging-log4j2,apache/logging-log4j2,GFriedrich/logging-log4j2,jinxuan/logging-log4j2,MagicWiz/log4j2,ChetnaChaudhari/logging-log4j2,codescale/logging-log4j2,codescale/logging-log4j2,renchunxiao/logging-log4j2,xnslong/logging-log4j2
/* * 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 org.apache.logging.log4j.util; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Collection; import java.util.Enumeration; import java.util.LinkedHashSet; /** * <em>Consider this class private.</em> Utility class for ClassLoaders. * @see ClassLoader * @see RuntimePermission * @see Thread#getContextClassLoader() * @see ClassLoader#getSystemClassLoader() */ public final class LoaderUtil { private LoaderUtil() {} public static final String IGNORE_TCCL_PROPERTY = "log4j.ignoreTCL"; private static final SecurityManager SECURITY_MANAGER = System.getSecurityManager(); // this variable must be lazily loaded; otherwise, we get a nice circular class loading problem where LoaderUtil // wants to use PropertiesUtil, but then PropertiesUtil wants to use LoaderUtil. private static Boolean ignoreTCCL; private static final boolean GET_CLASS_LOADER_DISABLED; private static final PrivilegedAction<ClassLoader> TCCL_GETTER = new ThreadContextClassLoaderGetter(); static { if (SECURITY_MANAGER != null) { boolean getClassLoaderDisabled; try { SECURITY_MANAGER.checkPermission(new RuntimePermission("getClassLoader")); getClassLoaderDisabled = false; } catch (final SecurityException ignored) { getClassLoaderDisabled = true; } GET_CLASS_LOADER_DISABLED = getClassLoaderDisabled; } else { GET_CLASS_LOADER_DISABLED = false; } } /** * Gets the current Thread ClassLoader. Returns the system ClassLoader if the TCCL is {@code null}. If the * system ClassLoader is {@code null} as well, then the ClassLoader for this class is returned. * If running with a {@link SecurityManager} that does not allow access to the Thread ClassLoader or system * ClassLoader, then the ClassLoader for this class is returned. * * @return the current ThreadContextClassLoader. */ public static ClassLoader getThreadContextClassLoader() { if (GET_CLASS_LOADER_DISABLED) { // we can at least get this class's ClassLoader regardless of security context // however, if this is null, there's really no option left at this point return LoaderUtil.class.getClassLoader(); } return SECURITY_MANAGER == null ? TCCL_GETTER.run() : AccessController.doPrivileged(TCCL_GETTER); } private static class ThreadContextClassLoaderGetter implements PrivilegedAction<ClassLoader> { @Override public ClassLoader run() { final ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl != null) { return cl; } final ClassLoader ccl = LoaderUtil.class.getClassLoader(); return ccl == null ? ClassLoader.getSystemClassLoader() : ccl; } } /** * Loads a class by name. This method respects the {@link #IGNORE_TCCL_PROPERTY} Log4j property. If this property * is specified and set to anything besides {@code false}, then the default ClassLoader will be used. * * @param className The class name. * @return the Class for the given name. * @throws ClassNotFoundException if the specified class name could not be found * @since 2.1 */ public static Class<?> loadClass(final String className) throws ClassNotFoundException { if (isIgnoreTccl()) { return Class.forName(className); } try { return getThreadContextClassLoader().loadClass(className); } catch (final Throwable ignored) { return Class.forName(className); } } /** * Loads and instantiates a Class using the default constructor. * * @param className The class name. * @return new instance of the class. * @throws ClassNotFoundException if the class isn't available to the usual ClassLoaders * @throws IllegalAccessException if the class can't be instantiated through a public constructor * @throws InstantiationException if there was an exception whilst instantiating the class * @throws NoSuchMethodException if there isn't a no-args constructor on the class * @throws InvocationTargetException if there was an exception whilst constructing the class * @since 2.1 */ public static Object newInstanceOf(final String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { final Class<?> clazz = loadClass(className); try { return clazz.getConstructor().newInstance(); } catch (final NoSuchMethodException ignored) { // FIXME: looking at the code for Class.newInstance(), this seems to do the same thing as above return clazz.newInstance(); } } /** * Loads and instantiates a derived class using its default constructor. * * @param className The class name. * @param clazz The class to cast it to. * @param <T> The type of the class to check. * @return new instance of the class cast to {@code T} * @throws ClassNotFoundException if the class isn't available to the usual ClassLoaders * @throws IllegalAccessException if the class can't be instantiated through a public constructor * @throws InstantiationException if there was an exception whilst instantiating the class * @throws NoSuchMethodException if there isn't a no-args constructor on the class * @throws InvocationTargetException if there was an exception whilst constructing the class * @throws ClassCastException if the constructed object isn't type compatible with {@code T} * @since 2.1 */ public static <T> T newCheckedInstanceOf(final String className, final Class<T> clazz) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { return clazz.cast(newInstanceOf(className)); } private static boolean isIgnoreTccl() { // we need to lazily initialize this, but concurrent access is not an issue if (ignoreTCCL == null) { final String ignoreTccl = PropertiesUtil.getProperties().getStringProperty(IGNORE_TCCL_PROPERTY, null); ignoreTCCL = ignoreTccl != null && !"false".equalsIgnoreCase(ignoreTccl.trim()); } return ignoreTCCL; } /** * Finds classpath {@linkplain URL resources}. * * @param resource the name of the resource to find. * @return a Collection of URLs matching the resource name. If no resources could be found, then this will be empty. * @since 2.1 */ public static Collection<URL> findResources(final String resource) { final Collection<UrlResource> urlResources = findUrlResources(resource); final Collection<URL> resources = new LinkedHashSet<URL>(urlResources.size()); for (final UrlResource urlResource : urlResources) { resources.add(urlResource.getUrl()); } return resources; } static Collection<UrlResource> findUrlResources(final String resource) { final ClassLoader[] candidates = { getThreadContextClassLoader(), LoaderUtil.class.getClassLoader(), ClassLoader.getSystemClassLoader() }; final Collection<UrlResource> resources = new LinkedHashSet<UrlResource>(); for (final ClassLoader cl : candidates) { if (cl != null) { try { final Enumeration<URL> resourceEnum = cl.getResources(resource); while (resourceEnum.hasMoreElements()) { resources.add(new UrlResource(cl, resourceEnum.nextElement())); } } catch (final IOException e) { e.printStackTrace(); } } } return resources; } /** * {@link URL} and {@link ClassLoader} pair. */ static class UrlResource { private final ClassLoader classLoader; private final URL url; public UrlResource(final ClassLoader classLoader, final URL url) { this.classLoader = classLoader; this.url = url; } public ClassLoader getClassLoader() { return classLoader; } public URL getUrl() { return url; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final UrlResource that = (UrlResource) o; if (classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) { return false; } if (url != null ? !url.equals(that.url) : that.url != null) { return false; } return true; } @Override public int hashCode() { int result = classLoader != null ? classLoader.hashCode() : 0; result = 31 * result + (url != null ? url.hashCode() : 0); return result; } } }
log4j-api/src/main/java/org/apache/logging/log4j/util/LoaderUtil.java
/* * 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 org.apache.logging.log4j.util; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Collection; import java.util.Enumeration; import java.util.LinkedHashSet; /** * <em>Consider this class private.</em> Utility class for ClassLoaders. * @see ClassLoader * @see RuntimePermission * @see Thread#getContextClassLoader() * @see ClassLoader#getSystemClassLoader() */ public final class LoaderUtil { private LoaderUtil() {} public static final String IGNORE_TCCL_PROPERTY = "log4j.ignoreTCL"; private static final SecurityManager SECURITY_MANAGER = System.getSecurityManager(); // this variable must be lazily loaded; otherwise, we get a nice circular class loading problem where LoaderUtil // wants to use PropertiesUtil, but then PropertiesUtil wants to use LoaderUtil. private static Boolean ignoreTCCL; private static final boolean GET_CLASS_LOADER_DISABLED; private static final PrivilegedAction<ClassLoader> TCCL_GETTER = new ThreadContextClassLoaderGetter(); static { if (SECURITY_MANAGER != null) { boolean getClassLoaderDisabled; try { SECURITY_MANAGER.checkPermission(new RuntimePermission("getClassLoader")); getClassLoaderDisabled = false; } catch (final SecurityException ignored) { getClassLoaderDisabled = true; } GET_CLASS_LOADER_DISABLED = getClassLoaderDisabled; } else { GET_CLASS_LOADER_DISABLED = false; } } /** * Gets the current Thread ClassLoader. Returns the system ClassLoader if the TCCL is {@code null}. If the * system ClassLoader is {@code null} as well, then the ClassLoader for this class is returned. * If running with a {@link SecurityManager} that does not allow access to the Thread ClassLoader or system * ClassLoader, then the ClassLoader for this class is returned. * * @return the current ThreadContextClassLoader. */ public static ClassLoader getThreadContextClassLoader() { if (GET_CLASS_LOADER_DISABLED) { // we can at least get this class's ClassLoader regardless of security context // however, if this is null, there's really no option left at this point return LoaderUtil.class.getClassLoader(); } return SECURITY_MANAGER == null ? TCCL_GETTER.run() : AccessController.doPrivileged(TCCL_GETTER); } private static class ThreadContextClassLoaderGetter implements PrivilegedAction<ClassLoader> { @Override public ClassLoader run() { final ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl != null) { return cl; } final ClassLoader ccl = LoaderUtil.class.getClassLoader(); return ccl == null ? ClassLoader.getSystemClassLoader() : ccl; } } /** * Loads a class by name. This method respects the {@link #IGNORE_TCCL_PROPERTY} Log4j property. If this property * is specified and set to anything besides {@code false}, then the default ClassLoader will be used. * * @param className The class name. * @return the Class for the given name. * @throws ClassNotFoundException if the specified class name could not be found * @since 2.1 */ public static Class<?> loadClass(final String className) throws ClassNotFoundException { if (isIgnoreTccl()) { return Class.forName(className); } try { return getThreadContextClassLoader().loadClass(className); } catch (final Throwable ignored) { return Class.forName(className); } } /** * Loads and instantiates a Class using the default constructor. * * @param className The class name. * @return new instance of the class. * @throws ClassNotFoundException if the class isn't available to the usual ClassLoaders * @throws IllegalAccessException if the class can't be instantiated through a public constructor * @throws InstantiationException if there was an exception whilst instantiating the class * @throws NoSuchMethodException if there isn't a no-args constructor on the class * @throws InvocationTargetException if there was an exception whilst constructing the class * @since 2.1 */ public static Object newInstanceOf(final String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { final Class<?> clazz = loadClass(className); try { return clazz.getConstructor().newInstance(); } catch (final NoSuchMethodException ignored) { // FIXME: looking at the code for Class.newInstance(), this seems to do the same thing as above return clazz.newInstance(); } } /** * Loads and instantiates a derived class using its default constructor. * * @param className The class name. * @param clazz The class to cast it to. * @param <T> The type of the class to check. * @return new instance of the class cast to {@code T} * @throws ClassNotFoundException if the class isn't available to the usual ClassLoaders * @throws IllegalAccessException if the class can't be instantiated through a public constructor * @throws InstantiationException if there was an exception whilst instantiating the class * @throws NoSuchMethodException if there isn't a no-args constructor on the class * @throws InvocationTargetException if there was an exception whilst constructing the class * @throws ClassCastException if the constructed object isn't type compatible with {@code T} * @since 2.1 */ public static <T> T newCheckedInstanceOf(final String className, final Class<T> clazz) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { return clazz.cast(newInstanceOf(className)); } private static boolean isIgnoreTccl() { // we need to lazily initialize this, but concurrent access is not an issue if (ignoreTCCL == null) { final String ignoreTccl = PropertiesUtil.getProperties().getStringProperty(IGNORE_TCCL_PROPERTY, null); ignoreTCCL = ignoreTccl != null && !"false".equalsIgnoreCase(ignoreTccl.trim()); } return ignoreTCCL; } /** * Finds classpath {@linkplain URL resources}. * * @param resource the name of the resource to find. * @return a Collection of URLs matching the resource name. If no resources could be found, then this will be empty. * @since 2.1 */ public static Collection<URL> findResources(final String resource) { final Collection<UrlResource> urlResources = findUrlResources(resource); final Collection<URL> resources = new LinkedHashSet<URL>(urlResources.size()); for (final UrlResource urlResource : urlResources) { resources.add(urlResource.getUrl()); } return resources; } static Collection<UrlResource> findUrlResources(final String resource) { final ClassLoader[] candidates = { getThreadContextClassLoader(), LoaderUtil.class.getClassLoader(), ClassLoader.getSystemClassLoader() }; final Collection<UrlResource> resources = new LinkedHashSet<UrlResource>(); for (final ClassLoader cl : candidates) { if (cl != null) { try { final Enumeration<URL> resourceEnum = cl.getResources(resource); while (resourceEnum.hasMoreElements()) { resources.add(new UrlResource(cl, resourceEnum.nextElement())); } } catch (final IOException e) { e.printStackTrace(); } } } return resources; } /** * {@link URL} and {@link ClassLoader} pair. */ static class UrlResource { private final ClassLoader classLoader; private final URL url; public UrlResource(final ClassLoader classLoader, final URL url) { this.classLoader = classLoader; this.url = url; } public ClassLoader getClassLoader() { return classLoader; } public URL getUrl() { return url; } } }
Add equals and hashCode to LoaderUtil.UrlResource
log4j-api/src/main/java/org/apache/logging/log4j/util/LoaderUtil.java
Add equals and hashCode to LoaderUtil.UrlResource
<ide><path>og4j-api/src/main/java/org/apache/logging/log4j/util/LoaderUtil.java <ide> public URL getUrl() { <ide> return url; <ide> } <add> <add> @Override <add> public boolean equals(final Object o) { <add> if (this == o) { <add> return true; <add> } <add> if (o == null || getClass() != o.getClass()) { <add> return false; <add> } <add> <add> final UrlResource that = (UrlResource) o; <add> <add> if (classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) { <add> return false; <add> } <add> if (url != null ? !url.equals(that.url) : that.url != null) { <add> return false; <add> } <add> <add> return true; <add> } <add> <add> @Override <add> public int hashCode() { <add> int result = classLoader != null ? classLoader.hashCode() : 0; <add> result = 31 * result + (url != null ? url.hashCode() : 0); <add> return result; <add> } <ide> } <ide> }
Java
apache-2.0
e43e22ca1e6f8a22cc1b4c53ca2ea2b6614cc153
0
flanglet/kanzi
/* Copyright 2011-2017 Frederic Langlet 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 kanzi.entropy; import kanzi.BitStreamException; import kanzi.EntropyDecoder; import kanzi.InputBitStream; // Uses tables to decode symbols instead of a tree public class HuffmanDecoder implements EntropyDecoder { public static final int DECODING_BATCH_SIZE = 12; // in bits public static final int DECODING_MASK = (1 << DECODING_BATCH_SIZE) - 1; private static final int MAX_DECODING_INDEX = (DECODING_BATCH_SIZE << 8) | 0xFF; private static final int DEFAULT_CHUNK_SIZE = 1 << 16; // 64 KB by default private static final int SYMBOL_ABSENT = Integer.MAX_VALUE; private static final int MAX_SYMBOL_SIZE = 24; private final InputBitStream bs; private final int[] codes; private final int[] alphabet; private final short[] sizes; private final int[] fdTable; // Fast decoding table private final int[] sdTable; // Slow decoding table private final int[] sdtIndexes; // Indexes for slow decoding table private final int chunkSize; private long state; // holds bits read from bitstream private int bits; // holds number of unused bits in 'state' private int minCodeLen; public HuffmanDecoder(InputBitStream bitstream) throws BitStreamException { this(bitstream, DEFAULT_CHUNK_SIZE); } // The chunk size indicates how many bytes are encoded (per block) before // resetting the frequency stats. 0 means that frequencies calculated at the // beginning of the block apply to the whole block. // The default chunk size is 65536 bytes. public HuffmanDecoder(InputBitStream bitstream, int chunkSize) throws BitStreamException { if (bitstream == null) throw new NullPointerException("Invalid null bitstream parameter"); if ((chunkSize != 0) && (chunkSize < 1024)) throw new IllegalArgumentException("The chunk size must be at least 1024"); if (chunkSize > 1<<30) throw new IllegalArgumentException("The chunk size must be at most 2^30"); this.bs = bitstream; this.sizes = new short[256]; this.alphabet = new int[256]; this.codes = new int[256]; this.fdTable = new int[1<<DECODING_BATCH_SIZE]; this.sdTable = new int[256]; this.sdtIndexes = new int[MAX_SYMBOL_SIZE+1]; this.chunkSize = chunkSize; this.minCodeLen = 8; // Default lengths & canonical codes for (int i=0; i<256; i++) { this.sizes[i] = 8; this.codes[i] = i; } } public int readLengths() throws BitStreamException { final int count = EntropyUtils.decodeAlphabet(this.bs, this.alphabet); ExpGolombDecoder egdec = new ExpGolombDecoder(this.bs, true); this.minCodeLen = MAX_SYMBOL_SIZE; // max code length int prevSize = 2; // Read lengths for (int i=0; i<count; i++) { final int r = this.alphabet[i]; if ((r < 0) || (r >= this.codes.length)) { throw new BitStreamException("Invalid bitstream: incorrect Huffman symbol " + r, BitStreamException.INVALID_STREAM); } this.codes[r] = 0; int currSize = prevSize + egdec.decodeByte(); if (currSize <= 0) { throw new BitStreamException("Invalid bitstream: incorrect size " + currSize + " for Huffman symbol " + r, BitStreamException.INVALID_STREAM); } if (currSize > MAX_SYMBOL_SIZE) { throw new BitStreamException("Invalid bitstream: incorrect max size " + currSize + " for Huffman symbol " + r, BitStreamException.INVALID_STREAM); } if (this.minCodeLen > currSize) this.minCodeLen = currSize; this.sizes[r] = (short) currSize; prevSize = currSize; } if (count == 0) return 0; // Create canonical codes if (HuffmanCommon.generateCanonicalCodes(this.sizes, this.codes, this.alphabet, count) < 0) { throw new BitStreamException("Could not generate codes: max code length " + "(" + MAX_SYMBOL_SIZE + " bits) exceeded", BitStreamException.INVALID_STREAM); } // Build decoding tables this.buildDecodingTables(count); return count; } // Build decoding tables // The slow decoding table contains the codes in natural order. // The fast decoding table contains all the prefixes with DECODING_BATCH_SIZE bits. private void buildDecodingTables(int count) { for (int i=this.fdTable.length-1; i>=0; i--) this.fdTable[i] = 0; for (int i=this.sdTable.length-1; i>=0; i--) this.sdTable[i] = 0; for (int i=this.sdtIndexes.length-1; i>=0; i--) this.sdtIndexes[i] = SYMBOL_ABSENT; int len = 0; for (int i=0; i<count; i++) { final int r = this.alphabet[i]; final int code = this.codes[r]; if (this.sizes[r] > len) { len = this.sizes[r]; this.sdtIndexes[len] = i - code; } // Fill slow decoding table final int val = (this.sizes[r] << 8) | r; this.sdTable[i] = val; // Fill fast decoding table // Find location index in table if (len < DECODING_BATCH_SIZE) { int idx = code << (DECODING_BATCH_SIZE - len); final int end = idx + (1 << (DECODING_BATCH_SIZE - len)); // All DECODING_BATCH_SIZE bit values read from the bit stream and // starting with the same prefix point to symbol r while (idx < end) this.fdTable[idx++] = val; } else { final int idx = code >>> (len - DECODING_BATCH_SIZE); this.fdTable[idx] = val; } } } // Use fastDecodeByte until the near end of chunk or block. @Override public int decode(byte[] block, int blkptr, int len) { if ((block == null) || (blkptr + len > block.length) || (blkptr < 0) || (len < 0)) return -1; if (len == 0) return 0; if (this.minCodeLen == 0) return -1; final int sz = (this.chunkSize == 0) ? len : this.chunkSize; int startChunk = blkptr; final int end = blkptr + len; while (startChunk < end) { // Reinitialize the Huffman tables if (this.readLengths() <= 0) return startChunk - blkptr; // Compute minimum number of bits required in bitstream for fast decoding int endPaddingSize = 64 / this.minCodeLen; if (this.minCodeLen * endPaddingSize != 64) endPaddingSize++; final int endChunk = (startChunk + sz < end) ? startChunk + sz : end; final int endChunk8 = (endChunk - endPaddingSize) & -8; int i = startChunk; // Fast decoding (read DECODING_BATCH_SIZE bits at a time) for ( ; i<endChunk8; i+=8) { block[i] = this.fastDecodeByte(); block[i+1] = this.fastDecodeByte(); block[i+2] = this.fastDecodeByte(); block[i+3] = this.fastDecodeByte(); block[i+4] = this.fastDecodeByte(); block[i+5] = this.fastDecodeByte(); block[i+6] = this.fastDecodeByte(); block[i+7] = this.fastDecodeByte(); } // Fallback to regular decoding (read one bit at a time) for ( ; i<endChunk; i++) block[i] = this.slowDecodeByte(0, 0); startChunk = endChunk; } return len; } private byte slowDecodeByte(int code, int codeLen) { while (codeLen < MAX_SYMBOL_SIZE) { codeLen++; code <<= 1; if (this.bits == 0) code |= this.bs.readBit(); else { // Consume remaining bits in 'state' this.bits--; code |= ((this.state >>> this.bits) & 1); } final int idx = this.sdtIndexes[codeLen]; if (idx == SYMBOL_ABSENT) // No code with this length ? continue; if ((this.sdTable[idx+code] >>> 8) == codeLen) return (byte) this.sdTable[idx+code]; } throw new BitStreamException("Invalid bitstream: incorrect Huffman code", BitStreamException.INVALID_STREAM); } // 64 bits must be available in the bitstream private byte fastDecodeByte() { if (this.bits < DECODING_BATCH_SIZE) { // Fetch more bits from bitstream this.state = (this.bits == 0) ? this.bs.readBits(64) : (this.state <<-this.bits) | this.bs.readBits(64-this.bits); this.bits = 64; } // Retrieve symbol from fast decoding table final int idx = (int) (this.state >>> (this.bits-DECODING_BATCH_SIZE)) & DECODING_MASK; final int val = this.fdTable[idx]; if (val > MAX_DECODING_INDEX) { this.bits -= DECODING_BATCH_SIZE; return this.slowDecodeByte(idx, DECODING_BATCH_SIZE); } this.bits -= (val >>> 8); return (byte) (val); } @Override public InputBitStream getBitStream() { return this.bs; } @Override public void dispose() { } }
java/src/main/java/kanzi/entropy/HuffmanDecoder.java
/* Copyright 2011-2017 Frederic Langlet 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 kanzi.entropy; import kanzi.BitStreamException; import kanzi.EntropyDecoder; import kanzi.InputBitStream; // Uses tables to decode symbols instead of a tree public class HuffmanDecoder implements EntropyDecoder { public static final int DECODING_BATCH_SIZE = 12; // in bits public static final int DECODING_MASK = (1 << DECODING_BATCH_SIZE) - 1; private static final int MAX_DECODING_INDEX = (DECODING_BATCH_SIZE << 8) | 0xFF; private static final int DEFAULT_CHUNK_SIZE = 1 << 16; // 64 KB by default private static final int SYMBOL_ABSENT = Integer.MAX_VALUE; private static final int MAX_SYMBOL_SIZE = 24; private final InputBitStream bs; private final int[] codes; private final int[] ranks; private final short[] sizes; private final int[] fdTable; // Fast decoding table private final int[] sdTable; // Slow decoding table private final int[] sdtIndexes; // Indexes for slow decoding table private final int chunkSize; private long state; // holds bits read from bitstream private int bits; // holds number of unused bits in 'state' private int minCodeLen; public HuffmanDecoder(InputBitStream bitstream) throws BitStreamException { this(bitstream, DEFAULT_CHUNK_SIZE); } // The chunk size indicates how many bytes are encoded (per block) before // resetting the frequency stats. 0 means that frequencies calculated at the // beginning of the block apply to the whole block. // The default chunk size is 65536 bytes. public HuffmanDecoder(InputBitStream bitstream, int chunkSize) throws BitStreamException { if (bitstream == null) throw new NullPointerException("Invalid null bitstream parameter"); if ((chunkSize != 0) && (chunkSize < 1024)) throw new IllegalArgumentException("The chunk size must be at least 1024"); if (chunkSize > 1<<30) throw new IllegalArgumentException("The chunk size must be at most 2^30"); this.bs = bitstream; this.sizes = new short[256]; this.ranks = new int[256]; this.codes = new int[256]; this.fdTable = new int[1<<DECODING_BATCH_SIZE]; this.sdTable = new int[256]; this.sdtIndexes = new int[MAX_SYMBOL_SIZE+1]; this.chunkSize = chunkSize; this.minCodeLen = 8; // Default lengths & canonical codes for (int i=0; i<256; i++) { this.sizes[i] = 8; this.codes[i] = i; } } public int readLengths() throws BitStreamException { final int count = EntropyUtils.decodeAlphabet(this.bs, this.ranks); ExpGolombDecoder egdec = new ExpGolombDecoder(this.bs, true); int currSize ; this.minCodeLen = MAX_SYMBOL_SIZE; // max code length int prevSize = 2; // Read lengths for (int i=0; i<count; i++) { final int r = this.ranks[i]; if ((r < 0) || (r >= this.codes.length)) { throw new BitStreamException("Invalid bitstream: incorrect Huffman symbol " + r, BitStreamException.INVALID_STREAM); } this.codes[r] = 0; currSize = prevSize + egdec.decodeByte(); if (currSize <= 0) { throw new BitStreamException("Invalid bitstream: incorrect size " + currSize + " for Huffman symbol " + r, BitStreamException.INVALID_STREAM); } if (currSize > MAX_SYMBOL_SIZE) { throw new BitStreamException("Invalid bitstream: incorrect max size " + currSize + " for Huffman symbol " + r, BitStreamException.INVALID_STREAM); } if (this.minCodeLen > currSize) this.minCodeLen = currSize; this.sizes[r] = (short) currSize; prevSize = currSize; } if (count == 0) return 0; // Create canonical codes if (HuffmanCommon.generateCanonicalCodes(this.sizes, this.codes, this.ranks, count) < 0) { throw new BitStreamException("Could not generate codes: max code length " + "(" + MAX_SYMBOL_SIZE + " bits) exceeded", BitStreamException.INVALID_STREAM); } // Build decoding tables this.buildDecodingTables(count); return count; } // Build decoding tables // The slow decoding table contains the codes in natural order. // The fast decoding table contains all the prefixes with DECODING_BATCH_SIZE bits. private void buildDecodingTables(int count) { for (int i=this.fdTable.length-1; i>=0; i--) this.fdTable[i] = 0; for (int i=this.sdTable.length-1; i>=0; i--) this.sdTable[i] = 0; for (int i=this.sdtIndexes.length-1; i>=0; i--) this.sdtIndexes[i] = SYMBOL_ABSENT; int len = 0; for (int i=0; i<count; i++) { final int r = this.ranks[i]; final int code = this.codes[r]; if (this.sizes[r] > len) { len = this.sizes[r]; this.sdtIndexes[len] = i - code; } // Fill slow decoding table final int val = (this.sizes[r] << 8) | r; this.sdTable[i] = val; // Fill fast decoding table // Find location index in table if (len < DECODING_BATCH_SIZE) { int idx = code << (DECODING_BATCH_SIZE - len); final int end = idx + (1 << (DECODING_BATCH_SIZE - len)); // All DECODING_BATCH_SIZE bit values read from the bit stream and // starting with the same prefix point to symbol r while (idx < end) this.fdTable[idx++] = val; } else { final int idx = code >>> (len - DECODING_BATCH_SIZE); this.fdTable[idx] = val; } } } // Use fastDecodeByte until the near end of chunk or block. @Override public int decode(byte[] block, int blkptr, int len) { if ((block == null) || (blkptr + len > block.length) || (blkptr < 0) || (len < 0)) return -1; if (len == 0) return 0; if (this.minCodeLen == 0) return -1; final int sz = (this.chunkSize == 0) ? len : this.chunkSize; int startChunk = blkptr; final int end = blkptr + len; while (startChunk < end) { // Reinitialize the Huffman tables if (this.readLengths() <= 0) return startChunk - blkptr; // Compute minimum number of bits required in bitstream for fast decoding int endPaddingSize = 64 / this.minCodeLen; if (this.minCodeLen * endPaddingSize != 64) endPaddingSize++; final int endChunk = (startChunk + sz < end) ? startChunk + sz : end; final int endChunk8 = (endChunk - endPaddingSize) & -8; int i = startChunk; // Fast decoding (read DECODING_BATCH_SIZE bits at a time) for ( ; i<endChunk8; i+=8) { block[i] = this.fastDecodeByte(); block[i+1] = this.fastDecodeByte(); block[i+2] = this.fastDecodeByte(); block[i+3] = this.fastDecodeByte(); block[i+4] = this.fastDecodeByte(); block[i+5] = this.fastDecodeByte(); block[i+6] = this.fastDecodeByte(); block[i+7] = this.fastDecodeByte(); } // Fallback to regular decoding (read one bit at a time) for ( ; i<endChunk; i++) block[i] = this.slowDecodeByte(0, 0); startChunk = endChunk; } return len; } private byte slowDecodeByte(int code, int codeLen) { while (codeLen < MAX_SYMBOL_SIZE) { codeLen++; code <<= 1; if (this.bits == 0) code |= this.bs.readBit(); else { // Consume remaining bits in 'state' this.bits--; code |= ((this.state >>> this.bits) & 1); } final int idx = this.sdtIndexes[codeLen]; if (idx == SYMBOL_ABSENT) // No code with this length ? continue; if ((this.sdTable[idx+code] >>> 8) == codeLen) return (byte) this.sdTable[idx+code]; } throw new BitStreamException("Invalid bitstream: incorrect Huffman code", BitStreamException.INVALID_STREAM); } // 64 bits must be available in the bitstream private byte fastDecodeByte() { if (this.bits < DECODING_BATCH_SIZE) { // Fetch more bits from bitstream this.state = (this.bits == 0) ? this.bs.readBits(64) : (this.state <<-this.bits) | this.bs.readBits(64-this.bits); this.bits = 64; } // Retrieve symbol from fast decoding table final int idx = (int) (this.state >>> (this.bits-DECODING_BATCH_SIZE)) & DECODING_MASK; final int val = this.fdTable[idx]; if (val > MAX_DECODING_INDEX) { this.bits -= DECODING_BATCH_SIZE; return this.slowDecodeByte(idx, DECODING_BATCH_SIZE); } this.bits -= (val >>> 8); return (byte) (val); } @Override public InputBitStream getBitStream() { return this.bs; } @Override public void dispose() { } }
Rename field for clarity.
java/src/main/java/kanzi/entropy/HuffmanDecoder.java
Rename field for clarity.
<ide><path>ava/src/main/java/kanzi/entropy/HuffmanDecoder.java <ide> <ide> private final InputBitStream bs; <ide> private final int[] codes; <del> private final int[] ranks; <add> private final int[] alphabet; <ide> private final short[] sizes; <ide> private final int[] fdTable; // Fast decoding table <ide> private final int[] sdTable; // Slow decoding table <ide> <ide> this.bs = bitstream; <ide> this.sizes = new short[256]; <del> this.ranks = new int[256]; <add> this.alphabet = new int[256]; <ide> this.codes = new int[256]; <ide> this.fdTable = new int[1<<DECODING_BATCH_SIZE]; <ide> this.sdTable = new int[256]; <ide> <ide> public int readLengths() throws BitStreamException <ide> { <del> final int count = EntropyUtils.decodeAlphabet(this.bs, this.ranks); <add> final int count = EntropyUtils.decodeAlphabet(this.bs, this.alphabet); <ide> ExpGolombDecoder egdec = new ExpGolombDecoder(this.bs, true); <del> int currSize ; <ide> this.minCodeLen = MAX_SYMBOL_SIZE; // max code length <ide> int prevSize = 2; <ide> <ide> // Read lengths <ide> for (int i=0; i<count; i++) <ide> { <del> final int r = this.ranks[i]; <add> final int r = this.alphabet[i]; <ide> <ide> if ((r < 0) || (r >= this.codes.length)) <ide> { <ide> } <ide> <ide> this.codes[r] = 0; <del> currSize = prevSize + egdec.decodeByte(); <add> int currSize = prevSize + egdec.decodeByte(); <ide> <ide> if (currSize <= 0) <ide> { <ide> return 0; <ide> <ide> // Create canonical codes <del> if (HuffmanCommon.generateCanonicalCodes(this.sizes, this.codes, this.ranks, count) < 0) <add> if (HuffmanCommon.generateCanonicalCodes(this.sizes, this.codes, this.alphabet, count) < 0) <ide> { <ide> throw new BitStreamException("Could not generate codes: max code length " + <ide> "(" + MAX_SYMBOL_SIZE + " bits) exceeded", BitStreamException.INVALID_STREAM); <ide> <ide> for (int i=0; i<count; i++) <ide> { <del> final int r = this.ranks[i]; <add> final int r = this.alphabet[i]; <ide> final int code = this.codes[r]; <ide> <ide> if (this.sizes[r] > len)
Java
apache-2.0
bf4c456ae7371c32c4b2365bb13b25701c1c2d47
0
HubSpot/Blazar,HubSpot/Blazar,HubSpot/Blazar,HubSpot/Blazar
package com.hubspot.blazar.util; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URI; import java.util.Set; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.kohsuke.github.GHRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.collect.ImmutableSet; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import com.hubspot.blazar.base.BranchSetting; import com.hubspot.blazar.base.BuildOptions; import com.hubspot.blazar.base.BuildTrigger; import com.hubspot.blazar.base.GitInfo; import com.hubspot.blazar.data.service.BranchService; import com.hubspot.blazar.data.service.BranchSettingsService; import com.hubspot.blazar.data.service.RepositoryBuildService; import com.hubspot.blazar.github.GitHubProtos.CreateEvent; import com.hubspot.blazar.github.GitHubProtos.DeleteEvent; import com.hubspot.blazar.github.GitHubProtos.PushEvent; import com.hubspot.blazar.github.GitHubProtos.Repository; @Singleton public class GitHubWebhookHandler { private static final Logger LOG = LoggerFactory.getLogger(GitHubWebhookHandler.class); private final BranchService branchService; private final RepositoryBuildService repositoryBuildService; private final BranchSettingsService branchSettingsService; private final GitHubHelper gitHubHelper; private final Set<String> whitelist; private final Set<String> blacklist; @Inject public GitHubWebhookHandler(BranchService branchService, RepositoryBuildService repositoryBuildService, BranchSettingsService branchSettingsService, GitHubHelper gitHubHelper, @Named("whitelist") Set<String> whitelist, @Named("blacklist") Set<String> blacklist, EventBus eventBus) { this.branchService = branchService; this.repositoryBuildService = repositoryBuildService; this.branchSettingsService = branchSettingsService; this.gitHubHelper = gitHubHelper; this.whitelist = whitelist; this.blacklist = blacklist; eventBus.register(this); } @Subscribe public void handleCreateEvent(CreateEvent createEvent) throws IOException { if (!createEvent.hasRepository()) { return; } if (blacklist.contains(createEvent.getRepository().getName())) { LOG.info("Ignoring hook from repo {} because it is in the blacklist.", createEvent.getRepository().getName()); return; } if ("branch".equalsIgnoreCase(createEvent.getRefType())) { GitInfo gitInfo = gitInfo(createEvent); if (isOptedIn(gitInfo)) { branchService.upsert(gitInfo); } } } @Subscribe public void handleDeleteEvent(DeleteEvent deleteEvent) { if (!deleteEvent.hasRepository()) { return; } if (blacklist.contains(deleteEvent.getRepository().getName())) { LOG.info("Ignoring hook from repo {} because it is in the blacklist.", deleteEvent.getRepository().getName()); return; } if ("branch".equalsIgnoreCase(deleteEvent.getRefType())) { branchService.delete(gitInfo(deleteEvent)); } } @Subscribe public void handlePushEvent(PushEvent pushEvent) throws IOException { if (!pushEvent.hasRepository()) { return; } if (blacklist.contains(pushEvent.getRepository().getName())) { LOG.info("Ignoring hook from repo {} because it is in the blacklist.", pushEvent.getRepository().getName()); return; } if (!pushEvent.getRef().startsWith("refs/tags/") && !pushEvent.getDeleted()) { GitInfo gitInfo = gitInfo(pushEvent); if (!gitInfo.isActive()) { String message = "Ignoring push event for inactive branch {}-{}@{}"; LOG.warn(message, gitInfo.getFullRepositoryName(), gitInfo.getBranch(), pushEvent.getAfter()); return; } if (!isOptedIn(gitInfo)) { LOG.debug("Not {}#{} is not opted in to Blazar", gitInfo.getFullRepositoryName(), gitInfo.getBranch()); return; } gitInfo = branchService.upsert(gitInfo); Optional<BranchSetting> branchSetting = branchSettingsService.getByBranchId(gitInfo.getId().get()); if (branchSetting.isPresent() && branchSetting.get().isTriggerInterProjectBuilds()) { BuildOptions options = new BuildOptions(ImmutableSet.<Integer>of(), BuildOptions.BuildDownstreams.INTER_PROJECT, false); repositoryBuildService.enqueue(gitInfo, BuildTrigger.forCommit(pushEvent.getAfter()), options); } else { repositoryBuildService.enqueue(gitInfo, BuildTrigger.forCommit(pushEvent.getAfter()), BuildOptions.defaultOptions()); } } } private boolean isOptedIn(GitInfo gitInfo) throws IOException { return whitelist.contains(gitInfo.getRepository()) || ( whitelist.isEmpty() && blazarConfigExists(gitInfo)); } private boolean blazarConfigExists(GitInfo gitInfo) throws IOException { GHRepository repository = gitHubHelper.repositoryFor(gitInfo); try { gitHubHelper.contentsFor(".blazar-enabled", repository, gitInfo); return true; } catch (FileNotFoundException e) { try { String config = gitHubHelper.contentsFor(".blazar.yaml", repository, gitInfo); return config.contains("enabled: true"); } catch (FileNotFoundException e1) { return false; } } } private GitInfo gitInfo(CreateEvent createEvent) { return gitInfo(createEvent.getRepository(), createEvent.getRef(), true); } private GitInfo gitInfo(DeleteEvent deleteEvent) { return gitInfo(deleteEvent.getRepository(), deleteEvent.getRef(), false); } private GitInfo gitInfo(PushEvent pushEvent) { int repositoryId = pushEvent.getRepository().getId(); String branch = branchFromRef(pushEvent.getRef()); Optional<GitInfo> gitInfo = branchService.getByRepositoryAndBranch(repositoryId, branch); boolean active = !gitInfo.isPresent() || gitInfo.get().isActive(); return gitInfo(pushEvent.getRepository(), pushEvent.getRef(), active); } private GitInfo gitInfo(Repository repository, String ref, boolean active) { String host = URI.create(repository.getUrl()).getHost(); if ("api.github.com".equals(host)) { host = "github.com"; } String fullName = repository.getFullName(); String organization = fullName.substring(0, fullName.indexOf('/')); String repositoryName = fullName.substring(fullName.indexOf('/') + 1); int repositoryId = repository.getId(); String branch = branchFromRef(ref); return new GitInfo(Optional.<Integer>absent(), host, organization, repositoryName, repositoryId, branch, active, System.currentTimeMillis(), System.currentTimeMillis()); } private static String branchFromRef(String ref) { return ref.startsWith("refs/heads/") ? ref.substring("refs/heads/".length()) : ref; } }
BlazarService/src/main/java/com/hubspot/blazar/util/GitHubWebhookHandler.java
package com.hubspot.blazar.util; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URI; import java.util.Set; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.kohsuke.github.GHRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.collect.ImmutableSet; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import com.hubspot.blazar.base.BranchSetting; import com.hubspot.blazar.base.BuildOptions; import com.hubspot.blazar.base.BuildTrigger; import com.hubspot.blazar.base.GitInfo; import com.hubspot.blazar.data.service.BranchService; import com.hubspot.blazar.data.service.BranchSettingsService; import com.hubspot.blazar.data.service.RepositoryBuildService; import com.hubspot.blazar.github.GitHubProtos.CreateEvent; import com.hubspot.blazar.github.GitHubProtos.DeleteEvent; import com.hubspot.blazar.github.GitHubProtos.PushEvent; import com.hubspot.blazar.github.GitHubProtos.Repository; @Singleton public class GitHubWebhookHandler { private static final Logger LOG = LoggerFactory.getLogger(GitHubWebhookHandler.class); private final BranchService branchService; private final RepositoryBuildService repositoryBuildService; private final BranchSettingsService branchSettingsService; private final GitHubHelper gitHubHelper; private final Set<String> whitelist; private final Set<String> blacklist; @Inject public GitHubWebhookHandler(BranchService branchService, RepositoryBuildService repositoryBuildService, BranchSettingsService branchSettingsService, GitHubHelper gitHubHelper, @Named("whitelist") Set<String> whitelist, @Named("blacklist") Set<String> blacklist, EventBus eventBus) { this.branchService = branchService; this.repositoryBuildService = repositoryBuildService; this.branchSettingsService = branchSettingsService; this.gitHubHelper = gitHubHelper; this.whitelist = whitelist; this.blacklist = blacklist; eventBus.register(this); } @Subscribe public void handleCreateEvent(CreateEvent createEvent) throws IOException { if (!createEvent.hasRepository()) { return; } if (blacklist.contains(createEvent.getRepository().getName())) { LOG.info("Ignoring hook from repo {} because it is in the blacklist.", createEvent.getRepository().getName()); return; } if ("branch".equalsIgnoreCase(createEvent.getRefType())) { GitInfo gitInfo = gitInfo(createEvent); if (isOptedIn(gitInfo)) { branchService.upsert(gitInfo); } } } @Subscribe public void handleDeleteEvent(DeleteEvent deleteEvent) { if (!deleteEvent.hasRepository()) { return; } if (blacklist.contains(deleteEvent.getRepository().getName())) { LOG.info("Ignoring hook from repo {} because it is in the blacklist.", deleteEvent.getRepository().getName()); return; } if ("branch".equalsIgnoreCase(deleteEvent.getRefType())) { branchService.delete(gitInfo(deleteEvent)); } } @Subscribe public void handlePushEvent(PushEvent pushEvent) throws IOException { if (!pushEvent.hasRepository()) { return; } if (blacklist.contains(pushEvent.getRepository().getName())) { LOG.info("Ignoring hook from repo {} because it is in the blacklist.", pushEvent.getRepository().getName()); return; } if (!pushEvent.getRef().startsWith("refs/tags/") && !pushEvent.getDeleted()) { GitInfo gitInfo = gitInfo(pushEvent); if (!gitInfo.isActive()) { String message = "Ignoring push event for inactive branch {}-{}@{}"; LOG.warn(message, gitInfo.getFullRepositoryName(), gitInfo.getBranch(), pushEvent.getAfter()); return; } if (!isOptedIn(gitInfo)) { LOG.debug("Not {}#{} is not opted in to Blazar", gitInfo.getFullRepositoryName(), gitInfo.getBranch()); return; } gitInfo = branchService.upsert(gitInfo); Optional<BranchSetting> branchSetting = branchSettingsService.getByBranchId(gitInfo.getId().get()); if (branchSetting.isPresent() && branchSetting.get().isTriggerInterProjectBuilds()) { BuildOptions options = new BuildOptions(ImmutableSet.<Integer>of(), BuildOptions.BuildDownstreams.INTER_PROJECT, false); repositoryBuildService.enqueue(gitInfo, BuildTrigger.forCommit(pushEvent.getAfter()), options); } else { repositoryBuildService.enqueue(gitInfo, BuildTrigger.forCommit(pushEvent.getAfter()), BuildOptions.defaultOptions()); } } } private boolean isOptedIn(GitInfo gitInfo) throws IOException { return whitelist.contains(gitInfo.getRepository()) || blazarConfigExists(gitInfo); } private boolean blazarConfigExists(GitInfo gitInfo) throws IOException { GHRepository repository = gitHubHelper.repositoryFor(gitInfo); try { gitHubHelper.contentsFor(".blazar-enabled", repository, gitInfo); return true; } catch (FileNotFoundException e) { try { String config = gitHubHelper.contentsFor(".blazar.yaml", repository, gitInfo); return config.contains("enabled: true"); } catch (FileNotFoundException e1) { return false; } } } private GitInfo gitInfo(CreateEvent createEvent) { return gitInfo(createEvent.getRepository(), createEvent.getRef(), true); } private GitInfo gitInfo(DeleteEvent deleteEvent) { return gitInfo(deleteEvent.getRepository(), deleteEvent.getRef(), false); } private GitInfo gitInfo(PushEvent pushEvent) { int repositoryId = pushEvent.getRepository().getId(); String branch = branchFromRef(pushEvent.getRef()); Optional<GitInfo> gitInfo = branchService.getByRepositoryAndBranch(repositoryId, branch); boolean active = !gitInfo.isPresent() || gitInfo.get().isActive(); return gitInfo(pushEvent.getRepository(), pushEvent.getRef(), active); } private GitInfo gitInfo(Repository repository, String ref, boolean active) { String host = URI.create(repository.getUrl()).getHost(); if ("api.github.com".equals(host)) { host = "github.com"; } String fullName = repository.getFullName(); String organization = fullName.substring(0, fullName.indexOf('/')); String repositoryName = fullName.substring(fullName.indexOf('/') + 1); int repositoryId = repository.getId(); String branch = branchFromRef(ref); return new GitInfo(Optional.<Integer>absent(), host, organization, repositoryName, repositoryId, branch, active, System.currentTimeMillis(), System.currentTimeMillis()); } private static String branchFromRef(String ref) { return ref.startsWith("refs/heads/") ? ref.substring("refs/heads/".length()) : ref; } }
Change Whitelist behavior For the testing of this in QA we need to have only certain projects build, but since things are mostly opted-in now we don't want to || with whether a project has a `.blazar-enabled` or `.blazar.yaml`. This makes Blazar ONLY handle git-events for things in the white list, if the white-list is non-emtpy. Otherwise it will check for the existance of the files we usually use to determine if a project is `On Blazar`.
BlazarService/src/main/java/com/hubspot/blazar/util/GitHubWebhookHandler.java
Change Whitelist behavior
<ide><path>lazarService/src/main/java/com/hubspot/blazar/util/GitHubWebhookHandler.java <ide> } <ide> <ide> private boolean isOptedIn(GitInfo gitInfo) throws IOException { <del> return whitelist.contains(gitInfo.getRepository()) || blazarConfigExists(gitInfo); <add> return whitelist.contains(gitInfo.getRepository()) || ( whitelist.isEmpty() && blazarConfigExists(gitInfo)); <ide> } <ide> <ide> private boolean blazarConfigExists(GitInfo gitInfo) throws IOException {
Java
apache-2.0
8992c6cf8b2487755bcb1a956446e24a1fa3abd1
0
ptupitsyn/ignite,andrey-kuznetsov/ignite,tkpanther/ignite,nizhikov/ignite,xtern/ignite,amirakhmedov/ignite,agoncharuk/ignite,samaitra/ignite,vsisko/incubator-ignite,gridgain/apache-ignite,gargvish/ignite,apacheignite/ignite,vsisko/incubator-ignite,andrey-kuznetsov/ignite,thuTom/ignite,amirakhmedov/ignite,samaitra/ignite,ashutakGG/incubator-ignite,vsuslov/incubator-ignite,DoudTechData/ignite,StalkXT/ignite,andrey-kuznetsov/ignite,xtern/ignite,wmz7year/ignite,afinka77/ignite,ashutakGG/incubator-ignite,ptupitsyn/ignite,ptupitsyn/ignite,a1vanov/ignite,agoncharuk/ignite,dmagda/incubator-ignite,arijitt/incubator-ignite,a1vanov/ignite,ntikhonov/ignite,sk0x50/ignite,chandresh-pancholi/ignite,leveyj/ignite,xtern/ignite,sk0x50/ignite,SomeFire/ignite,tkpanther/ignite,irudyak/ignite,voipp/ignite,NSAmelchev/ignite,ascherbakoff/ignite,VladimirErshov/ignite,svladykin/ignite,gridgain/apache-ignite,tkpanther/ignite,apache/ignite,gridgain/apache-ignite,wmz7year/ignite,sylentprayer/ignite,avinogradovgg/ignite,andrey-kuznetsov/ignite,ilantukh/ignite,f7753/ignite,thuTom/ignite,BiryukovVA/ignite,nizhikov/ignite,dmagda/incubator-ignite,apacheignite/ignite,endian675/ignite,SomeFire/ignite,f7753/ignite,adeelmahmood/ignite,NSAmelchev/ignite,iveselovskiy/ignite,agura/incubator-ignite,vsuslov/incubator-ignite,akuznetsov-gridgain/ignite,DoudTechData/ignite,chandresh-pancholi/ignite,voipp/ignite,vldpyatkov/ignite,rfqu/ignite,kromulan/ignite,ntikhonov/ignite,ryanzz/ignite,avinogradovgg/ignite,BiryukovVA/ignite,wmz7year/ignite,VladimirErshov/ignite,gargvish/ignite,endian675/ignite,kidaa/incubator-ignite,vsisko/incubator-ignite,amirakhmedov/ignite,zzcclp/ignite,dmagda/incubator-ignite,adeelmahmood/ignite,mcherkasov/ignite,shroman/ignite,leveyj/ignite,agoncharuk/ignite,louishust/incubator-ignite,SharplEr/ignite,ascherbakoff/ignite,vsuslov/incubator-ignite,irudyak/ignite,xtern/ignite,alexzaitzev/ignite,arijitt/incubator-ignite,rfqu/ignite,SomeFire/ignite,ryanzz/ignite,zzcclp/ignite,psadusumilli/ignite,voipp/ignite,ilantukh/ignite,murador/ignite,dream-x/ignite,psadusumilli/ignite,daradurvs/ignite,pperalta/ignite,svladykin/ignite,a1vanov/ignite,irudyak/ignite,amirakhmedov/ignite,apache/ignite,vladisav/ignite,shroman/ignite,ashutakGG/incubator-ignite,psadusumilli/ignite,voipp/ignite,BiryukovVA/ignite,ntikhonov/ignite,vadopolski/ignite,BiryukovVA/ignite,DoudTechData/ignite,f7753/ignite,SharplEr/ignite,adeelmahmood/ignite,shurun19851206/ignite,agoncharuk/ignite,ascherbakoff/ignite,vladisav/ignite,sylentprayer/ignite,shurun19851206/ignite,DoudTechData/ignite,vladisav/ignite,nivanov/ignite,samaitra/ignite,ilantukh/ignite,sylentprayer/ignite,rfqu/ignite,ilantukh/ignite,pperalta/ignite,alexzaitzev/ignite,vsuslov/incubator-ignite,pperalta/ignite,vladisav/ignite,kidaa/incubator-ignite,apacheignite/ignite,ptupitsyn/ignite,voipp/ignite,VladimirErshov/ignite,svladykin/ignite,leveyj/ignite,pperalta/ignite,NSAmelchev/ignite,louishust/incubator-ignite,DoudTechData/ignite,rfqu/ignite,agura/incubator-ignite,daradurvs/ignite,shroman/ignite,SharplEr/ignite,gridgain/apache-ignite,ashutakGG/incubator-ignite,vladisav/ignite,dream-x/ignite,louishust/incubator-ignite,alexzaitzev/ignite,tkpanther/ignite,ryanzz/ignite,zzcclp/ignite,dlnufox/ignite,wmz7year/ignite,avinogradovgg/ignite,agoncharuk/ignite,ilantukh/ignite,SharplEr/ignite,amirakhmedov/ignite,SharplEr/ignite,StalkXT/ignite,nivanov/ignite,gargvish/ignite,SomeFire/ignite,vladisav/ignite,iveselovskiy/ignite,wmz7year/ignite,iveselovskiy/ignite,nivanov/ignite,voipp/ignite,afinka77/ignite,vldpyatkov/ignite,afinka77/ignite,irudyak/ignite,dream-x/ignite,ntikhonov/ignite,a1vanov/ignite,vldpyatkov/ignite,voipp/ignite,tkpanther/ignite,vadopolski/ignite,ascherbakoff/ignite,BiryukovVA/ignite,alexzaitzev/ignite,samaitra/ignite,SomeFire/ignite,dlnufox/ignite,sylentprayer/ignite,svladykin/ignite,mcherkasov/ignite,vsuslov/incubator-ignite,NSAmelchev/ignite,akuznetsov-gridgain/ignite,vldpyatkov/ignite,nivanov/ignite,xtern/ignite,andrey-kuznetsov/ignite,ascherbakoff/ignite,f7753/ignite,murador/ignite,apacheignite/ignite,shroman/ignite,gargvish/ignite,louishust/incubator-ignite,a1vanov/ignite,vsisko/incubator-ignite,rfqu/ignite,apache/ignite,ascherbakoff/ignite,ilantukh/ignite,pperalta/ignite,endian675/ignite,svladykin/ignite,abhishek-ch/incubator-ignite,StalkXT/ignite,daradurvs/ignite,agoncharuk/ignite,samaitra/ignite,dmagda/incubator-ignite,akuznetsov-gridgain/ignite,iveselovskiy/ignite,daradurvs/ignite,dlnufox/ignite,abhishek-ch/incubator-ignite,chandresh-pancholi/ignite,kromulan/ignite,sylentprayer/ignite,daradurvs/ignite,SomeFire/ignite,shurun19851206/ignite,apacheignite/ignite,WilliamDo/ignite,apache/ignite,pperalta/ignite,murador/ignite,dlnufox/ignite,BiryukovVA/ignite,SharplEr/ignite,vldpyatkov/ignite,andrey-kuznetsov/ignite,f7753/ignite,ilantukh/ignite,ryanzz/ignite,murador/ignite,agura/incubator-ignite,leveyj/ignite,ptupitsyn/ignite,StalkXT/ignite,iveselovskiy/ignite,ryanzz/ignite,agoncharuk/ignite,voipp/ignite,WilliamDo/ignite,BiryukovVA/ignite,WilliamDo/ignite,alexzaitzev/ignite,svladykin/ignite,avinogradovgg/ignite,arijitt/incubator-ignite,vadopolski/ignite,afinka77/ignite,chandresh-pancholi/ignite,daradurvs/ignite,louishust/incubator-ignite,ryanzz/ignite,amirakhmedov/ignite,ntikhonov/ignite,shurun19851206/ignite,ptupitsyn/ignite,shurun19851206/ignite,nizhikov/ignite,dream-x/ignite,murador/ignite,thuTom/ignite,dmagda/incubator-ignite,mcherkasov/ignite,ptupitsyn/ignite,vsisko/incubator-ignite,samaitra/ignite,dream-x/ignite,kromulan/ignite,vadopolski/ignite,arijitt/incubator-ignite,leveyj/ignite,abhishek-ch/incubator-ignite,dream-x/ignite,dlnufox/ignite,thuTom/ignite,amirakhmedov/ignite,samaitra/ignite,shroman/ignite,vsisko/incubator-ignite,sk0x50/ignite,mcherkasov/ignite,andrey-kuznetsov/ignite,chandresh-pancholi/ignite,WilliamDo/ignite,adeelmahmood/ignite,chandresh-pancholi/ignite,irudyak/ignite,adeelmahmood/ignite,xtern/ignite,NSAmelchev/ignite,WilliamDo/ignite,ascherbakoff/ignite,ryanzz/ignite,mcherkasov/ignite,kromulan/ignite,afinka77/ignite,sk0x50/ignite,VladimirErshov/ignite,samaitra/ignite,ptupitsyn/ignite,ntikhonov/ignite,vadopolski/ignite,SharplEr/ignite,apache/ignite,agoncharuk/ignite,shroman/ignite,a1vanov/ignite,gridgain/apache-ignite,SharplEr/ignite,dmagda/incubator-ignite,apache/ignite,zzcclp/ignite,shroman/ignite,gargvish/ignite,svladykin/ignite,leveyj/ignite,endian675/ignite,ntikhonov/ignite,endian675/ignite,murador/ignite,zzcclp/ignite,mcherkasov/ignite,vadopolski/ignite,akuznetsov-gridgain/ignite,irudyak/ignite,adeelmahmood/ignite,ascherbakoff/ignite,nivanov/ignite,mcherkasov/ignite,rfqu/ignite,murador/ignite,ilantukh/ignite,psadusumilli/ignite,gridgain/apache-ignite,avinogradovgg/ignite,tkpanther/ignite,andrey-kuznetsov/ignite,psadusumilli/ignite,VladimirErshov/ignite,gridgain/apache-ignite,psadusumilli/ignite,andrey-kuznetsov/ignite,sylentprayer/ignite,alexzaitzev/ignite,WilliamDo/ignite,amirakhmedov/ignite,sylentprayer/ignite,shroman/ignite,shroman/ignite,kromulan/ignite,avinogradovgg/ignite,ntikhonov/ignite,chandresh-pancholi/ignite,abhishek-ch/incubator-ignite,pperalta/ignite,nizhikov/ignite,nivanov/ignite,NSAmelchev/ignite,irudyak/ignite,kidaa/incubator-ignite,nizhikov/ignite,samaitra/ignite,StalkXT/ignite,BiryukovVA/ignite,StalkXT/ignite,kromulan/ignite,tkpanther/ignite,sk0x50/ignite,apache/ignite,zzcclp/ignite,agura/incubator-ignite,apache/ignite,alexzaitzev/ignite,alexzaitzev/ignite,akuznetsov-gridgain/ignite,nizhikov/ignite,ryanzz/ignite,avinogradovgg/ignite,vsuslov/incubator-ignite,StalkXT/ignite,akuznetsov-gridgain/ignite,sk0x50/ignite,pperalta/ignite,agura/incubator-ignite,rfqu/ignite,SharplEr/ignite,NSAmelchev/ignite,shroman/ignite,agura/incubator-ignite,kromulan/ignite,vladisav/ignite,sk0x50/ignite,endian675/ignite,NSAmelchev/ignite,nizhikov/ignite,ashutakGG/incubator-ignite,shurun19851206/ignite,apache/ignite,endian675/ignite,f7753/ignite,a1vanov/ignite,xtern/ignite,wmz7year/ignite,ptupitsyn/ignite,apacheignite/ignite,wmz7year/ignite,a1vanov/ignite,leveyj/ignite,ilantukh/ignite,SomeFire/ignite,abhishek-ch/incubator-ignite,BiryukovVA/ignite,endian675/ignite,WilliamDo/ignite,xtern/ignite,ascherbakoff/ignite,amirakhmedov/ignite,zzcclp/ignite,louishust/incubator-ignite,agura/incubator-ignite,psadusumilli/ignite,thuTom/ignite,dream-x/ignite,adeelmahmood/ignite,andrey-kuznetsov/ignite,agura/incubator-ignite,vadopolski/ignite,thuTom/ignite,sk0x50/ignite,afinka77/ignite,arijitt/incubator-ignite,abhishek-ch/incubator-ignite,shurun19851206/ignite,StalkXT/ignite,sylentprayer/ignite,daradurvs/ignite,ilantukh/ignite,irudyak/ignite,murador/ignite,kidaa/incubator-ignite,thuTom/ignite,thuTom/ignite,f7753/ignite,iveselovskiy/ignite,zzcclp/ignite,adeelmahmood/ignite,SomeFire/ignite,afinka77/ignite,kidaa/incubator-ignite,SomeFire/ignite,dlnufox/ignite,mcherkasov/ignite,VladimirErshov/ignite,vladisav/ignite,rfqu/ignite,arijitt/incubator-ignite,gargvish/ignite,nizhikov/ignite,VladimirErshov/ignite,gargvish/ignite,sk0x50/ignite,kidaa/incubator-ignite,nivanov/ignite,daradurvs/ignite,dream-x/ignite,vldpyatkov/ignite,NSAmelchev/ignite,vldpyatkov/ignite,afinka77/ignite,psadusumilli/ignite,DoudTechData/ignite,apacheignite/ignite,dlnufox/ignite,VladimirErshov/ignite,dlnufox/ignite,nivanov/ignite,DoudTechData/ignite,tkpanther/ignite,dmagda/incubator-ignite,vadopolski/ignite,ashutakGG/incubator-ignite,kromulan/ignite,vsisko/incubator-ignite,nizhikov/ignite,BiryukovVA/ignite,xtern/ignite,StalkXT/ignite,shurun19851206/ignite,f7753/ignite,voipp/ignite,SomeFire/ignite,WilliamDo/ignite,daradurvs/ignite,irudyak/ignite,daradurvs/ignite,dmagda/incubator-ignite,DoudTechData/ignite,samaitra/ignite,wmz7year/ignite,gargvish/ignite,vldpyatkov/ignite,alexzaitzev/ignite,leveyj/ignite,vsisko/incubator-ignite,ptupitsyn/ignite,chandresh-pancholi/ignite,apacheignite/ignite,chandresh-pancholi/ignite
/* * 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 org.apache.ignite.internal.processors.cache.distributed.near; import org.apache.ignite.*; import org.apache.ignite.cache.*; import org.apache.ignite.cache.affinity.*; import org.apache.ignite.cache.store.*; import org.apache.ignite.cluster.*; import org.apache.ignite.configuration.*; import org.apache.ignite.internal.*; import org.apache.ignite.internal.processors.cache.distributed.*; import org.apache.ignite.internal.processors.cache.distributed.dht.*; import org.apache.ignite.internal.util.typedef.*; import org.apache.ignite.internal.util.typedef.internal.*; import org.apache.ignite.spi.discovery.tcp.*; import org.apache.ignite.spi.discovery.tcp.ipfinder.*; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.*; import org.apache.ignite.testframework.junits.common.*; import org.apache.ignite.transactions.*; import org.jetbrains.annotations.*; import javax.cache.configuration.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import java.util.concurrent.locks.*; import static org.apache.ignite.cache.CacheAtomicityMode.*; import static org.apache.ignite.cache.CacheDistributionMode.*; import static org.apache.ignite.cache.CacheMode.*; import static org.apache.ignite.internal.processors.cache.GridCachePeekMode.*; import static org.apache.ignite.transactions.IgniteTxConcurrency.*; import static org.apache.ignite.transactions.IgniteTxIsolation.*; /** * Multi node test for near cache. */ public class GridCacheNearMultiNodeSelfTest extends GridCommonAbstractTest { /** Grid count. */ private static final int GRID_CNT = 2; /** */ private static final int BACKUPS = 1; /** Cache store. */ private static TestStore store = new TestStore(); /** */ private TcpDiscoveryIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true); /** Grid counter. */ private AtomicInteger cntr = new AtomicInteger(0); /** Affinity based on node index mode. */ private CacheAffinityFunction aff = new GridCacheModuloAffinityFunction(GRID_CNT, BACKUPS); /** Debug flag for mappings. */ private boolean mapDebug = true; /** * */ public GridCacheNearMultiNodeSelfTest() { super(false /* don't start grid. */); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); TcpDiscoverySpi spi = new TcpDiscoverySpi(); spi.setIpFinder(ipFinder); spi.setMaxMissedHeartbeats(Integer.MAX_VALUE); cfg.setDiscoverySpi(spi); CacheConfiguration cacheCfg = defaultCacheConfiguration(); cacheCfg.setCacheMode(PARTITIONED); cacheCfg.setCacheStoreFactory(new FactoryBuilder.SingletonFactory(store)); cacheCfg.setReadThrough(true); cacheCfg.setWriteThrough(true); cacheCfg.setLoadPreviousValue(true); cacheCfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC); cacheCfg.setAffinity(aff); cacheCfg.setAtomicityMode(atomicityMode()); cacheCfg.setBackups(BACKUPS); cacheCfg.setDistributionMode(NEAR_PARTITIONED); cfg.setCacheConfiguration(cacheCfg); cfg.setUserAttributes(F.asMap(GridCacheModuloAffinityFunction.IDX_ATTR, cntr.getAndIncrement())); return cfg; } /** * @return Atomicity mode. */ protected CacheAtomicityMode atomicityMode() { return TRANSACTIONAL; } /** * @return {@code True} if tests transactional cache. */ protected boolean transactional() { return atomicityMode() == TRANSACTIONAL; } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { startGrids(GRID_CNT); } /** {@inheritDoc} */ @Override protected void afterTestsStopped() throws Exception { stopAllGrids(); assert G.allGrids().isEmpty(); } /** {@inheritDoc} */ @SuppressWarnings({"SizeReplaceableByIsEmpty"}) @Override protected void beforeTest() throws Exception { for (int i = 0; i < GRID_CNT; i++) { assert jcache(i).localSize() == 0 : "Near cache size is not zero for grid: " + i; assert dht(grid(i)).size() == 0 : "DHT cache size is not zero for grid: " + i; assert jcache(i).localSize() == 0 : "Near cache is not empty for grid: " + i; assert dht(grid(i)).isEmpty() : "DHT cache is not empty for grid: " + i; } } /** {@inheritDoc} */ @SuppressWarnings({"SizeReplaceableByIsEmpty"}) @Override protected void afterTest() throws Exception { for (int i = 0; i < GRID_CNT; i++) { jcache(i).removeAll(); assertEquals("Near cache size is not zero for grid: " + i, 0, jcache(i).localSize()); assertEquals("DHT cache size is not zero for grid: " + i, 0, dht(grid(i)).size()); assert jcache(i).localSize() == 0 : "Near cache is not empty for grid: " + i; assert dht(grid(i)).isEmpty() : "DHT cache is not empty for grid: " + i; } store.reset(); for (int i = 0; i < GRID_CNT; i++) { IgniteTx tx = grid(i).cache(null).tx(); if (tx != null) { error("Ending zombie transaction: " + tx); tx.close(); } } } /** * @param g Grid. * @return Dht cache. */ @SuppressWarnings({"unchecked", "TypeMayBeWeakened"}) private GridDhtCacheAdapter<Integer, String> dht(Ignite g) { return ((GridNearCacheAdapter)((IgniteKernal)g).internalCache()).dht(); } /** * @param g Grid. * @return Dht cache. */ @SuppressWarnings({"unchecked", "TypeMayBeWeakened"}) private GridNearCacheAdapter<Integer, String> near(Ignite g) { return (GridNearCacheAdapter)((IgniteKernal)g).internalCache(); } /** * @param idx Index. * @return Affinity. */ private CacheAffinity<Object> affinity(int idx) { return grid(idx).cache(null).affinity(); } /** @param cnt Count. */ private Map<UUID, T2<Set<Integer>, Set<Integer>>> mapKeys(int cnt) { CacheAffinity<Object> aff = affinity(0); //Mapping primary and backup keys on node Map<UUID, T2<Set<Integer>, Set<Integer>>> map = new HashMap<>(); for (int i = 0; i < GRID_CNT; i++) { IgniteEx grid = grid(i); map.put(grid.cluster().localNode().id(), new T2<Set<Integer>, Set<Integer>>(new HashSet<Integer>(), new HashSet<Integer>())); } for (int key = 1; key <= cnt; key++) { Integer part = aff.partition(key); assert part != null; Collection<ClusterNode> nodes = aff.mapPartitionToPrimaryAndBackups(part); ClusterNode primary = F.first(nodes); map.get(primary.id()).get1().add(key); if (mapDebug) info("Mapped key to primary node [key=" + key + ", node=" + U.toShortString(primary)); for (ClusterNode n : nodes) { if (n != primary) { map.get(n.id()).get2().add(key); if (mapDebug) info("Mapped key to backup node [key=" + key + ", node=" + U.toShortString(n)); } } } return map; } /** Test mappings. */ public void testMappings() { mapDebug = false; int cnt = 100000; Map<UUID, T2<Set<Integer>, Set<Integer>>> map = mapKeys(cnt); for (ClusterNode n : grid(0).nodes()) { Set<Integer> primary = map.get(n.id()).get1(); Set<Integer> backups = map.get(n.id()).get2(); if (backups == null) backups = Collections.emptySet(); info("Grid node [primaries=" + primary.size() + ", backups=" + backups.size() + ']'); assert !F.isEmpty(primary); assertEquals(backups.size(), cnt - primary.size()); } } /** * @param key Key. * @return Primary node for the key. */ @Nullable private ClusterNode primaryNode(Integer key) { return affinity(0).mapKeyToNode(key); } /** * @param key Key. * @return Primary node for the key. */ @Nullable private Ignite primaryGrid(Integer key) { ClusterNode n = affinity(0).mapKeyToNode(key); assert n != null; return G.ignite(n.id()); } /** * @param key Key. * @return Primary node for the key. */ @Nullable private Collection<Ignite> backupGrids(Integer key) { Collection<ClusterNode> nodes = affinity(0).mapKeyToPrimaryAndBackups(key); Collection<ClusterNode> backups = CU.backups(nodes); return F.viewReadOnly(backups, new C1<ClusterNode, Ignite>() { @Override public Ignite apply(ClusterNode node) { return G.ignite(node.id()); } }); } /** @throws Exception If failed. */ public void testReadThroughAndPut() throws Exception { Integer key = 100000; Ignite primary; Ignite backup; if (grid(0) == primaryGrid(key)) { primary = grid(0); backup = grid(1); } else { primary = grid(1); backup = grid(0); } assertEquals(String.valueOf(key), backup.cache(null).get(key)); primary.cache(null).put(key, "a"); assertEquals("a", backup.cache(null).get(key)); } /** @throws Exception If failed. */ public void testReadThrough() throws Exception { ClusterNode loc = grid(0).localNode(); info("Local node: " + U.toShortString(loc)); IgniteCache<Integer, String> near = jcache(0); int cnt = 10; Map<UUID, T2<Set<Integer>, Set<Integer>>> mapKeys = mapKeys(cnt); for (int key = 1; key <= cnt; key++) { String s = near.get(key); info("Read key [key=" + key + ", val=" + s + ']'); assert s != null; } info("Read all keys."); for (int key = 1; key <= cnt; key++) { ClusterNode n = primaryNode(key); info("Primary node for key [key=" + key + ", node=" + U.toShortString(n) + ']'); assert n != null; assert mapKeys.get(n.id()).get1().contains(key); GridCache<Integer, String> dhtCache = dht(G.ignite(n.id())); String s = dhtCache.peek(key); assert s != null : "Value is null for key: " + key; assertEquals(s, Integer.toString(key)); } } /** * Test Optimistic repeatable read write-through. * * @throws Exception If failed. */ @SuppressWarnings({"ConstantConditions"}) public void testOptimisticWriteThrough() throws Exception { IgniteCache<Integer, String> near = jcache(0); if (transactional()) { try (IgniteTx tx = grid(0).transactions().txStart(OPTIMISTIC, REPEATABLE_READ, 0, 0)) { near.put(2, "2"); String s = near.getAndPut(3, "3"); assertNotNull(s); assertEquals("3", s); assertEquals("2", near.get(2)); assertEquals("3", near.get(3)); GridDhtCacheEntry<Integer, String> entry = dht(primaryGrid(2)).peekExx(2); if (entry != null) assertNull("Unexpected entry: " + entry, entry.rawGetOrUnmarshal(false)); assertNotNull(dht(primaryGrid(3)).peek(3)); tx.commit(); } } else { near.put(2, "2"); String s = near.getAndPut(3, "3"); assertNotNull(s); assertEquals("3", s); } assertEquals("2", near.localPeek(2, CachePeekMode.ONHEAP)); assertEquals("3", near.localPeek(3, CachePeekMode.ONHEAP)); assertEquals("2", dht(primaryGrid(2)).peek(2)); assertEquals("3", dht(primaryGrid(3)).peek(3)); assertEquals(2, near.localSize()); assertEquals(2, near.localSize()); } /** @throws Exception If failed. */ public void testNoTransactionSinglePutx() throws Exception { IgniteCache<Integer, String> near = jcache(0); near.put(2, "2"); assertEquals("2", near.localPeek(2, CachePeekMode.ONHEAP)); assertEquals("2", near.get(2)); assertEquals("2", dht(primaryGrid(2)).peek(2)); assertEquals(1, near.localSize()); assertEquals(1, near.localSize()); assertEquals(1, dht(primaryGrid(2)).size()); } /** @throws Exception If failed. */ public void testNoTransactionSinglePut() throws Exception { IgniteCache<Integer, String> near = jcache(0); // There should be a not-null previously mapped value because // we use a store implementation that just returns values which // are string representations of requesting integer keys. String s = near.getAndPut(3, "3"); assertNotNull(s); assertEquals("3", s); assertEquals("3", near.localPeek(3, CachePeekMode.ONHEAP)); assertEquals("3", near.get(3)); Ignite primaryIgnite = primaryGrid(3); assert primaryIgnite != null; info("Primary grid for key 3: " + U.toShortString(primaryIgnite.cluster().localNode())); assertEquals("3", dht(primaryIgnite).peek(3)); assertEquals(1, near.localSize()); assertEquals(1, near.localSize()); assertEquals(1, dht(primaryIgnite).size()); // Check backup nodes. Collection<Ignite> backups = backupGrids(3); assert backups != null; for (Ignite b : backups) { info("Backup grid for key 3: " + U.toShortString(b.cluster().localNode())); assertEquals("3", dht(b).peek(3)); assertEquals(1, dht(b).size()); } } /** @throws Exception If failed. */ public void testNoTransactionWriteThrough() throws Exception { IgniteCache<Integer, String> near = jcache(0); near.put(2, "2"); String s = near.getAndPut(3, "3"); assertNotNull(s); assertEquals("3", s); assertEquals("2", near.localPeek(2, CachePeekMode.ONHEAP)); assertEquals("3", near.localPeek(3, CachePeekMode.ONHEAP)); assertEquals("2", near.get(2)); assertEquals("3", near.get(3)); assertEquals("2", dht(primaryGrid(2)).peek(2)); assertEquals("3", dht(primaryGrid(3)).peek(3)); assertEquals(2, near.localSize()); assertEquals(2, near.localSize()); } /** * Test Optimistic repeatable read write-through. * * @throws Exception If failed. */ @SuppressWarnings({"ConstantConditions"}) public void testPessimisticWriteThrough() throws Exception { IgniteCache<Integer, String> near = jcache(0); if (transactional()) { try (IgniteTx tx = grid(0).transactions().txStart(PESSIMISTIC, REPEATABLE_READ, 0, 0)) { near.put(2, "2"); String s = near.getAndPut(3, "3"); assertEquals("3", s); assertEquals("2", near.localPeek(2, CachePeekMode.ONHEAP)); assertEquals("3", near.get(3)); assertNotNull(dht(primaryGrid(3)).peek(3, F.asList(GLOBAL))); // This assertion no longer makes sense as we bring the value over whenever // there is a version mismatch. // assertNull(dht(primaryGrid(2)).peek(2, new GridCachePeekMode[]{GLOBAL})); tx.commit(); } } else { near.put(2, "2"); String s = near.getAndPut(3, "3"); assertNotNull(s); assertEquals("3", s); } assertEquals("2", near.localPeek(2, CachePeekMode.ONHEAP)); assertEquals("3", near.localPeek(3, CachePeekMode.ONHEAP)); assertEquals("2", dht(primaryGrid(2)).peek(2)); assertEquals("3", dht(primaryGrid(3)).peek(3)); assertEquals(2, near.localSize()); assertEquals(2, near.localSize()); } /** @throws Exception If failed. */ public void testConcurrentOps() throws Exception { // Don't create missing values. store.create(false); IgniteCache<Integer, String> near = jcache(0); int key = 1; assertTrue(near.putIfAbsent(key, "1")); assertFalse(near.putIfAbsent(key, "1")); assertEquals("1", near.getAndPutIfAbsent(key, "2")); assertEquals("1", near.localPeek(key, CachePeekMode.ONHEAP)); assertEquals(1, near.localSize()); assertEquals(1, near.localSize()); assertEquals("1", near.getAndReplace(key, "2")); assertEquals("2", near.localPeek(key, CachePeekMode.ONHEAP)); assertTrue(near.replace(key, "2")); assertEquals("2", near.localPeek(key, CachePeekMode.ONHEAP)); assertEquals(1, near.localSize()); assertEquals(1, near.localSize()); assertTrue(near.remove(key, "2")); assertEquals(0, near.localSize()); } /** @throws Exception If failed. */ public void testBackupsLocalAffinity() throws Exception { checkBackupConsistency(2); } /** @throws Exception If failed. */ public void testBackupsRemoteAffinity() throws Exception { checkBackupConsistency(1); } /** * @param key Key to check. * @throws Exception If failed. */ private void checkBackupConsistency(int key) throws Exception { IgniteCache<Integer, String> cache = jcache(0); String val = Integer.toString(key); cache.put(key, val); GridNearCacheAdapter<Integer, String> near0 = near(0); GridNearCacheAdapter<Integer, String> near1 = near(1); GridDhtCacheAdapter<Integer, String> dht0 = dht(0); GridDhtCacheAdapter<Integer, String> dht1 = dht(1); assertNull(near0.peekNearOnly(key)); assertNull(near1.peekNearOnly(key)); assertEquals(val, dht0.peek(key)); assertEquals(val, dht1.peek(key)); } /** @throws Exception If failed. */ public void testSingleLockLocalAffinity() throws Exception { checkSingleLock(2); } /** @throws Exception If failed. */ public void testSingleLockRemoteAffinity() throws Exception { checkSingleLock(1); } /** * @param idx Grid index. * @param key Key. * @return Near entry. */ @Nullable private GridNearCacheEntry<Integer, String> nearEntry(int idx, int key) { return this.<Integer, String>near(idx).peekExx(key); } /** * @param o Object. * @return Hash value. */ private int hash(Object o) { return System.identityHashCode(o); } /** * @param key Key. * @throws Exception If failed. */ private void checkSingleLock(int key) throws Exception { if (!transactional()) return; IgniteCache<Integer, String> cache = jcache(0); String val = Integer.toString(key); Collection<ClusterNode> affNodes = grid(0).affinity(null).mapKeyToPrimaryAndBackups(key); info("Affinity for key [nodeId=" + U.nodeIds(affNodes) + ", key=" + key + ']'); assertEquals(2, affNodes.size()); ClusterNode primary = F.first(affNodes); assertNotNull(primary); info("Primary local: " + primary.isLocal()); Lock lock = cache.lock(key); lock.lock(); try { long topVer = grid(0).topologyVersion(); GridNearCacheEntry<Integer, String> nearEntry1 = nearEntry(0, key); info("Peeked entry after lock [hash=" + hash(nearEntry1) + ", nearEntry=" + nearEntry1 + ']'); assertNotNull(nearEntry1); assertTrue("Invalid near entry: " + nearEntry1, nearEntry1.valid(topVer)); assertTrue(cache.isLocalLocked(key, false)); assertTrue(cache.isLocalLocked(key, true)); cache.put(key, val); GridNearCacheEntry<Integer, String> nearEntry2 = nearEntry(0, key); info("Peeked entry after put [hash=" + hash(nearEntry1) + ", nearEntry=" + nearEntry2 + ']'); assert nearEntry1 == nearEntry2; assertNotNull(nearEntry2); assertTrue("Invalid near entry [hash=" + nearEntry2, nearEntry2.valid(topVer)); assertEquals(val, cache.localPeek(key, CachePeekMode.ONHEAP)); assertEquals(val, dht(0).peek(key)); assertEquals(val, dht(1).peek(key)); GridNearCacheEntry<Integer, String> nearEntry3 = nearEntry(0, key); info("Peeked entry after peeks [hash=" + hash(nearEntry1) + ", nearEntry=" + nearEntry3 + ']'); assert nearEntry2 == nearEntry3; assertNotNull(nearEntry3); assertTrue("Invalid near entry: " + nearEntry3, nearEntry3.valid(topVer)); assertNotNull(near(0).peekNearOnly(key)); assertNull(near(1).peekNearOnly(key)); assertEquals(val, cache.get(key)); assertEquals(val, cache.getAndRemove(key)); assertNull(cache.localPeek(key, CachePeekMode.ONHEAP)); assertNull(dht(primaryGrid(key)).peek(key)); assertTrue(cache.isLocalLocked(key, false)); assertTrue(cache.isLocalLocked(key, true)); } finally { lock.unlock(); } assertNull(near(0).peekNearOnly(key)); assertNull(near(1).peekNearOnly(key)); assertFalse(near(0).isLockedNearOnly(key)); assertFalse(cache.isLocalLocked(key, true)); } /** @throws Throwable If failed. */ public void testSingleLockReentryLocalAffinity() throws Throwable { checkSingleLockReentry(2); } /** @throws Throwable If failed. */ public void testSingleLockReentryRemoteAffinity() throws Throwable { checkSingleLockReentry(1); } /** * @param key Key. * @throws Exception If failed. */ private void checkSingleLockReentry(int key) throws Throwable { if (!transactional()) return; IgniteCache<Integer, String> near = jcache(0); String val = Integer.toString(key); Lock lock = near.lock(key); lock.lock(); try { near.put(key, val); assertEquals(val, near.localPeek(key, CachePeekMode.ONHEAP)); assertEquals(val, dht(primaryGrid(key)).peek(key)); assertTrue(near.isLocalLocked(key, false)); assertTrue(near.isLocalLocked(key, true)); lock.lock(); // Reentry. try { assertEquals(val, near.get(key)); assertEquals(val, near.getAndRemove(key)); assertNull(near.localPeek(key, CachePeekMode.ONHEAP)); assertNull(dht(primaryGrid(key)).peek(key)); assertTrue(near.isLocalLocked(key, false)); assertTrue(near.isLocalLocked(key, true)); } finally { lock.unlock(); } assertTrue(near.isLocalLocked(key, false)); assertTrue(near.isLocalLocked(key, true)); } catch (Throwable t) { error("Test failed.", t); throw t; } finally { lock.unlock(); } assertFalse(near(0).isLockedNearOnly(key)); assertFalse(near.isLocalLocked(key, true)); } /** @throws Exception If failed. */ public void testTransactionSingleGetLocalAffinity() throws Exception { checkTransactionSingleGet(2); } /** @throws Exception If failed. */ public void testTransactionSingleGetRemoteAffinity() throws Exception { checkTransactionSingleGet(1); } /** * @param key Key. * @throws Exception If failed. */ private void checkTransactionSingleGet(int key) throws Exception { IgniteCache<Integer, String> cache = jcache(0); String val = Integer.toString(key); cache.put(key, val); assertEquals(val, dht(0).peek(key)); assertEquals(val, dht(1).peek(key)); assertNull(near(0).peekNearOnly(key)); assertNull(near(1).peekNearOnly(key)); if (transactional()) { try (IgniteTx tx = grid(0).transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) { // Simple transaction get. assertEquals(val, cache.get(key)); tx.commit(); } } else assertEquals(val, cache.get(key)); assertEquals(val, dht(0).peek(key)); assertEquals(val, dht(1).peek(key)); assertNull(near(0).peekNearOnly(key)); assertNull(near(1).peekNearOnly(key)); } /** @throws Exception If failed. */ public void testTransactionSingleGetRemoveLocalAffinity() throws Exception { checkTransactionSingleGetRemove(2); } /** @throws Exception If failed. */ public void testTransactionSingleGetRemoveRemoteAffinity() throws Exception { checkTransactionSingleGetRemove(1); } /** * @param key Key * @throws Exception If failed. */ public void checkTransactionSingleGetRemove(int key) throws Exception { IgniteCache<Object, Object> cache = jcache(0); String val = Integer.toString(key); cache.put(key, val); assertEquals(val, dht(0).peek(key)); assertEquals(val, dht(1).peek(key)); assertNull(near(0).peekNearOnly(key)); assertNull(near(1).peekNearOnly(key)); if (transactional()) { try (IgniteTx tx = grid(0).transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) { // Read. assertEquals(val, cache.get(key)); // Remove. assertTrue(cache.remove(key)); tx.commit(); } } else { // Read. assertEquals(val, cache.get(key)); // Remove. assertTrue(cache.remove(key)); } assertNull(dht(0).peek(key)); assertNull(dht(1).peek(key)); assertNull(near(0).peekNearOnly(key)); assertNull(near(1).peekNearOnly(key)); } /** * */ private static class TestStore extends CacheStoreAdapter<Integer, String> { /** Map. */ private ConcurrentMap<Integer, String> map = new ConcurrentHashMap<>(); /** Create flag. */ private volatile boolean create = true; /** * */ void reset() { map.clear(); create = true; } /** @param create Create flag. */ void create(boolean create) { this.create = create; } /** @return Create flag. */ boolean isCreate() { return create; } /** * @param key Key. * @return Value. */ String value(Integer key) { return map.get(key); } /** * @param key Key. * @return {@code True} if has value. */ boolean hasValue(Integer key) { return map.containsKey(key); } /** @return {@code True} if empty. */ boolean isEmpty() { return map.isEmpty(); } /** {@inheritDoc} */ @Override public String load(Integer key) { if (!create) return map.get(key); String s = map.putIfAbsent(key, key.toString()); return s == null ? key.toString() : s; } /** {@inheritDoc} */ @Override public void write(javax.cache.Cache.Entry<? extends Integer, ? extends String> e) { map.put(e.getKey(), e.getValue()); } /** {@inheritDoc} */ @Override public void delete(Object key) { map.remove(key); } } }
modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/near/GridCacheNearMultiNodeSelfTest.java
/* * 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 org.apache.ignite.internal.processors.cache.distributed.near; import org.apache.ignite.*; import org.apache.ignite.cache.*; import org.apache.ignite.cache.affinity.*; import org.apache.ignite.cache.store.*; import org.apache.ignite.cluster.*; import org.apache.ignite.configuration.*; import org.apache.ignite.internal.*; import org.apache.ignite.internal.processors.cache.distributed.*; import org.apache.ignite.internal.processors.cache.distributed.dht.*; import org.apache.ignite.internal.util.typedef.*; import org.apache.ignite.internal.util.typedef.internal.*; import org.apache.ignite.spi.discovery.tcp.*; import org.apache.ignite.spi.discovery.tcp.ipfinder.*; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.*; import org.apache.ignite.testframework.junits.common.*; import org.apache.ignite.transactions.*; import org.jetbrains.annotations.*; import javax.cache.configuration.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import java.util.concurrent.locks.*; import static org.apache.ignite.cache.CacheAtomicityMode.*; import static org.apache.ignite.cache.CacheDistributionMode.*; import static org.apache.ignite.cache.CacheMode.*; import static org.apache.ignite.internal.processors.cache.GridCachePeekMode.*; import static org.apache.ignite.transactions.IgniteTxConcurrency.*; import static org.apache.ignite.transactions.IgniteTxIsolation.*; /** * Multi node test for near cache. */ public class GridCacheNearMultiNodeSelfTest extends GridCommonAbstractTest { /** Grid count. */ private static final int GRID_CNT = 2; /** */ private static final int BACKUPS = 1; /** Cache store. */ private static TestStore store = new TestStore(); /** */ private TcpDiscoveryIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true); /** Grid counter. */ private AtomicInteger cntr = new AtomicInteger(0); /** Affinity based on node index mode. */ private CacheAffinityFunction aff = new GridCacheModuloAffinityFunction(GRID_CNT, BACKUPS); /** Debug flag for mappings. */ private boolean mapDebug = true; /** * */ public GridCacheNearMultiNodeSelfTest() { super(false /* don't start grid. */); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); TcpDiscoverySpi spi = new TcpDiscoverySpi(); spi.setIpFinder(ipFinder); spi.setMaxMissedHeartbeats(Integer.MAX_VALUE); cfg.setDiscoverySpi(spi); CacheConfiguration cacheCfg = defaultCacheConfiguration(); cacheCfg.setCacheMode(PARTITIONED); cacheCfg.setCacheStoreFactory(new FactoryBuilder.SingletonFactory(store)); cacheCfg.setReadThrough(true); cacheCfg.setWriteThrough(true); cacheCfg.setLoadPreviousValue(true); cacheCfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC); cacheCfg.setAffinity(aff); cacheCfg.setAtomicityMode(atomicityMode()); cacheCfg.setBackups(BACKUPS); cacheCfg.setDistributionMode(NEAR_PARTITIONED); cfg.setCacheConfiguration(cacheCfg); cfg.setUserAttributes(F.asMap(GridCacheModuloAffinityFunction.IDX_ATTR, cntr.getAndIncrement())); return cfg; } /** * @return Atomicity mode. */ protected CacheAtomicityMode atomicityMode() { return TRANSACTIONAL; } /** * @return {@code True} if tests transactional cache. */ protected boolean transactional() { return atomicityMode() == TRANSACTIONAL; } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { startGrids(GRID_CNT); } /** {@inheritDoc} */ @Override protected void afterTestsStopped() throws Exception { stopAllGrids(); assert G.allGrids().isEmpty(); } /** {@inheritDoc} */ @SuppressWarnings({"SizeReplaceableByIsEmpty"}) @Override protected void beforeTest() throws Exception { for (int i = 0; i < GRID_CNT; i++) { assert jcache(i).localSize() == 0 : "Near cache size is not zero for grid: " + i; assert dht(grid(i)).size() == 0 : "DHT cache size is not zero for grid: " + i; assert jcache(i).localSize() == 0 : "Near cache is not empty for grid: " + i; assert dht(grid(i)).isEmpty() : "DHT cache is not empty for grid: " + i; } } /** {@inheritDoc} */ @SuppressWarnings({"SizeReplaceableByIsEmpty"}) @Override protected void afterTest() throws Exception { for (int i = 0; i < GRID_CNT; i++) { jcache(i).removeAll(); assertEquals("Near cache size is not zero for grid: " + i, 0, jcache(i).localSize()); assertEquals("DHT cache size is not zero for grid: " + i, 0, dht(grid(i)).size()); assert jcache(i).localSize() == 0 : "Near cache is not empty for grid: " + i; assert dht(grid(i)).isEmpty() : "DHT cache is not empty for grid: " + i; } store.reset(); for (int i = 0; i < GRID_CNT; i++) { IgniteTx tx = grid(i).cache(null).tx(); if (tx != null) { error("Ending zombie transaction: " + tx); tx.close(); } } } /** * @param g Grid. * @return Dht cache. */ @SuppressWarnings({"unchecked", "TypeMayBeWeakened"}) private GridDhtCacheAdapter<Integer, String> dht(Ignite g) { return ((GridNearCacheAdapter)((IgniteKernal)g).internalCache()).dht(); } /** * @param g Grid. * @return Dht cache. */ @SuppressWarnings({"unchecked", "TypeMayBeWeakened"}) private GridNearCacheAdapter<Integer, String> near(Ignite g) { return (GridNearCacheAdapter)((IgniteKernal)g).internalCache(); } /** * @param idx Index. * @return Affinity. */ private CacheAffinity<Object> affinity(int idx) { return grid(idx).cache(null).affinity(); } /** @param cnt Count. */ private Map<UUID, T2<Set<Integer>, Set<Integer>>> mapKeys(int cnt) { CacheAffinity<Object> aff = affinity(0); //Mapping primary and backup keys on node Map<UUID, T2<Set<Integer>, Set<Integer>>> map = new HashMap<>(); for (int i = 0; i < GRID_CNT; i++) { IgniteEx grid = grid(i); map.put(grid.cluster().localNode().id(), new T2<Set<Integer>, Set<Integer>>(new HashSet<Integer>(), new HashSet<Integer>())); } for (int key = 1; key <= cnt; key++) { Integer part = aff.partition(key); assert part != null; Collection<ClusterNode> nodes = aff.mapPartitionToPrimaryAndBackups(part); ClusterNode primary = F.first(nodes); map.get(primary.id()).get1().add(key); if (mapDebug) info("Mapped key to primary node [key=" + key + ", node=" + U.toShortString(primary)); for (ClusterNode n : nodes) { if (n != primary) { map.get(n.id()).get2().add(key); if (mapDebug) info("Mapped key to backup node [key=" + key + ", node=" + U.toShortString(n)); } } } return map; } /** Test mappings. */ public void testMappings() { mapDebug = false; int cnt = 100000; Map<UUID, T2<Set<Integer>, Set<Integer>>> map = mapKeys(cnt); for (ClusterNode n : grid(0).nodes()) { Set<Integer> primary = map.get(n.id()).get1(); Set<Integer> backups = map.get(n.id()).get2(); if (backups == null) backups = Collections.emptySet(); info("Grid node [primaries=" + primary.size() + ", backups=" + backups.size() + ']'); assert !F.isEmpty(primary); assertEquals(backups.size(), cnt - primary.size()); } } /** * @param key Key. * @return Primary node for the key. */ @Nullable private ClusterNode primaryNode(Integer key) { return affinity(0).mapKeyToNode(key); } /** * @param key Key. * @return Primary node for the key. */ @Nullable private Ignite primaryGrid(Integer key) { ClusterNode n = affinity(0).mapKeyToNode(key); assert n != null; return G.ignite(n.id()); } /** * @param key Key. * @return Primary node for the key. */ @Nullable private Collection<Ignite> backupGrids(Integer key) { Collection<ClusterNode> nodes = affinity(0).mapKeyToPrimaryAndBackups(key); Collection<ClusterNode> backups = CU.backups(nodes); return F.viewReadOnly(backups, new C1<ClusterNode, Ignite>() { @Override public Ignite apply(ClusterNode node) { return G.ignite(node.id()); } }); } /** @throws Exception If failed. */ public void testReadThroughAndPut() throws Exception { Integer key = 100000; Ignite primary; Ignite backup; if (grid(0) == primaryGrid(key)) { primary = grid(0); backup = grid(1); } else { primary = grid(1); backup = grid(0); } assertEquals(String.valueOf(key), backup.cache(null).get(key)); primary.cache(null).put(key, "a"); assertEquals("a", backup.cache(null).get(key)); } /** @throws Exception If failed. */ public void testReadThrough() throws Exception { ClusterNode loc = grid(0).localNode(); info("Local node: " + U.toShortString(loc)); IgniteCache<Integer, String> near = jcache(0); int cnt = 10; Map<UUID, T2<Set<Integer>, Set<Integer>>> mapKeys = mapKeys(cnt); for (int key = 1; key <= cnt; key++) { String s = near.get(key); info("Read key [key=" + key + ", val=" + s + ']'); assert s != null; } info("Read all keys."); for (int key = 1; key <= cnt; key++) { ClusterNode n = primaryNode(key); info("Primary node for key [key=" + key + ", node=" + U.toShortString(n) + ']'); assert n != null; assert mapKeys.get(n.id()).get1().contains(key); GridCache<Integer, String> dhtCache = dht(G.ignite(n.id())); String s = dhtCache.peek(key); assert s != null : "Value is null for key: " + key; assertEquals(s, Integer.toString(key)); } } /** * Test Optimistic repeatable read write-through. * * @throws Exception If failed. */ @SuppressWarnings({"ConstantConditions"}) public void testOptimisticWriteThrough() throws Exception { IgniteCache<Integer, String> near = jcache(0); if (transactional()) { try (IgniteTx tx = grid(0).transactions().txStart(OPTIMISTIC, REPEATABLE_READ, 0, 0)) { near.put(2, "2"); String s = near.getAndPut(3, "3"); assertNotNull(s); assertEquals("3", s); assertEquals("2", near.get(2)); assertEquals("3", near.get(3)); GridDhtCacheEntry<Integer, String> entry = dht(primaryGrid(2)).peekExx(2); if (entry != null) assertNull("Unexpected entry: " + entry, entry.rawGetOrUnmarshal(false)); assertNotNull(dht(primaryGrid(3)).peek(3)); tx.commit(); } } else { near.put(2, "2"); String s = near.getAndPut(3, "3"); assertNotNull(s); assertEquals("3", s); } assertEquals("2", near.localPeek(2, CachePeekMode.ONHEAP)); assertEquals("3", near.localPeek(3, CachePeekMode.ONHEAP)); assertEquals("2", dht(primaryGrid(2)).peek(2)); assertEquals("3", dht(primaryGrid(3)).peek(3)); assertEquals(2, near.localSize()); assertEquals(2, near.localSize()); } /** @throws Exception If failed. */ public void testNoTransactionSinglePutx() throws Exception { IgniteCache<Integer, String> near = jcache(0); near.put(2, "2"); assertEquals("2", near.localPeek(2, CachePeekMode.ONHEAP)); assertEquals("2", near.get(2)); assertEquals("2", dht(primaryGrid(2)).peek(2)); assertEquals(1, near.localSize()); assertEquals(1, near.localSize()); assertEquals(1, dht(primaryGrid(2)).size()); } /** @throws Exception If failed. */ public void testNoTransactionSinglePut() throws Exception { IgniteCache<Integer, String> near = jcache(0); // There should be a not-null previously mapped value because // we use a store implementation that just returns values which // are string representations of requesting integer keys. String s = near.getAndPut(3, "3"); assertNotNull(s); assertEquals("3", s); assertEquals("3", near.localPeek(3, CachePeekMode.ONHEAP)); assertEquals("3", near.get(3)); Ignite primaryIgnite = primaryGrid(3); assert primaryIgnite != null; info("Primary grid for key 3: " + U.toShortString(primaryIgnite.cluster().localNode())); assertEquals("3", dht(primaryIgnite).peek(3)); assertEquals(1, near.localSize()); assertEquals(1, near.localSize()); assertEquals(1, dht(primaryIgnite).size()); // Check backup nodes. Collection<Ignite> backups = backupGrids(3); assert backups != null; for (Ignite b : backups) { info("Backup grid for key 3: " + U.toShortString(b.cluster().localNode())); assertEquals("3", dht(b).peek(3)); assertEquals(1, dht(b).size()); } } /** @throws Exception If failed. */ public void testNoTransactionWriteThrough() throws Exception { IgniteCache<Integer, String> near = jcache(0); near.put(2, "2"); String s = near.getAndPut(3, "3"); assertNotNull(s); assertEquals("3", s); assertEquals("2", near.localPeek(2, CachePeekMode.ONHEAP)); assertEquals("3", near.localPeek(3, CachePeekMode.ONHEAP)); assertEquals("2", near.get(2)); assertEquals("3", near.get(3)); assertEquals("2", dht(primaryGrid(2)).peek(2)); assertEquals("3", dht(primaryGrid(3)).peek(3)); assertEquals(2, near.localSize()); assertEquals(2, near.localSize()); } /** * Test Optimistic repeatable read write-through. * * @throws Exception If failed. */ @SuppressWarnings({"ConstantConditions"}) public void testPessimisticWriteThrough() throws Exception { IgniteCache<Integer, String> near = jcache(0); if (transactional()) { try (IgniteTx tx = grid(0).transactions().txStart(PESSIMISTIC, REPEATABLE_READ, 0, 0)) { near.put(2, "2"); String s = near.getAndPut(3, "3"); assertNotNull(s); assertEquals("3", s); assertEquals("2", near.localPeek(2, CachePeekMode.ONHEAP)); assertEquals("3", near.localPeek(3, CachePeekMode.ONHEAP)); assertNotNull(dht(primaryGrid(3)).peek(3, F.asList(GLOBAL))); // This assertion no longer makes sense as we bring the value over whenever // there is a version mismatch. // assertNull(dht(primaryGrid(2)).peek(2, new GridCachePeekMode[]{GLOBAL})); tx.commit(); } } else { near.put(2, "2"); String s = near.getAndPut(3, "3"); assertNotNull(s); assertEquals("3", s); } assertEquals("2", near.localPeek(2, CachePeekMode.ONHEAP)); assertEquals("3", near.localPeek(3, CachePeekMode.ONHEAP)); assertEquals("2", dht(primaryGrid(2)).peek(2)); assertEquals("3", dht(primaryGrid(3)).peek(3)); assertEquals(2, near.localSize()); assertEquals(2, near.localSize()); } /** @throws Exception If failed. */ public void testConcurrentOps() throws Exception { // Don't create missing values. store.create(false); IgniteCache<Integer, String> near = jcache(0); int key = 1; assertTrue(near.putIfAbsent(key, "1")); assertFalse(near.putIfAbsent(key, "1")); assertEquals("1", near.getAndPutIfAbsent(key, "2")); assertEquals("1", near.localPeek(key, CachePeekMode.ONHEAP)); assertEquals(1, near.localSize()); assertEquals(1, near.localSize()); assertEquals("1", near.getAndReplace(key, "2")); assertEquals("2", near.localPeek(key, CachePeekMode.ONHEAP)); assertTrue(near.replace(key, "2")); assertEquals("2", near.localPeek(key, CachePeekMode.ONHEAP)); assertEquals(1, near.localSize()); assertEquals(1, near.localSize()); assertTrue(near.remove(key, "2")); assertEquals(0, near.localSize()); } /** @throws Exception If failed. */ public void testBackupsLocalAffinity() throws Exception { checkBackupConsistency(2); } /** @throws Exception If failed. */ public void testBackupsRemoteAffinity() throws Exception { checkBackupConsistency(1); } /** * @param key Key to check. * @throws Exception If failed. */ private void checkBackupConsistency(int key) throws Exception { IgniteCache<Integer, String> cache = jcache(0); String val = Integer.toString(key); cache.put(key, val); GridNearCacheAdapter<Integer, String> near0 = near(0); GridNearCacheAdapter<Integer, String> near1 = near(1); GridDhtCacheAdapter<Integer, String> dht0 = dht(0); GridDhtCacheAdapter<Integer, String> dht1 = dht(1); assertNull(near0.peekNearOnly(key)); assertNull(near1.peekNearOnly(key)); assertEquals(val, dht0.peek(key)); assertEquals(val, dht1.peek(key)); } /** @throws Exception If failed. */ public void testSingleLockLocalAffinity() throws Exception { checkSingleLock(2); } /** @throws Exception If failed. */ public void testSingleLockRemoteAffinity() throws Exception { checkSingleLock(1); } /** * @param idx Grid index. * @param key Key. * @return Near entry. */ @Nullable private GridNearCacheEntry<Integer, String> nearEntry(int idx, int key) { return this.<Integer, String>near(idx).peekExx(key); } /** * @param o Object. * @return Hash value. */ private int hash(Object o) { return System.identityHashCode(o); } /** * @param key Key. * @throws Exception If failed. */ private void checkSingleLock(int key) throws Exception { if (!transactional()) return; IgniteCache<Integer, String> cache = jcache(0); String val = Integer.toString(key); Collection<ClusterNode> affNodes = grid(0).affinity(null).mapKeyToPrimaryAndBackups(key); info("Affinity for key [nodeId=" + U.nodeIds(affNodes) + ", key=" + key + ']'); assertEquals(2, affNodes.size()); ClusterNode primary = F.first(affNodes); assertNotNull(primary); info("Primary local: " + primary.isLocal()); Lock lock = cache.lock(key); lock.lock(); try { long topVer = grid(0).topologyVersion(); GridNearCacheEntry<Integer, String> nearEntry1 = nearEntry(0, key); info("Peeked entry after lock [hash=" + hash(nearEntry1) + ", nearEntry=" + nearEntry1 + ']'); assertNotNull(nearEntry1); assertTrue("Invalid near entry: " + nearEntry1, nearEntry1.valid(topVer)); assertTrue(cache.isLocalLocked(key, false)); assertTrue(cache.isLocalLocked(key, true)); cache.put(key, val); GridNearCacheEntry<Integer, String> nearEntry2 = nearEntry(0, key); info("Peeked entry after put [hash=" + hash(nearEntry1) + ", nearEntry=" + nearEntry2 + ']'); assert nearEntry1 == nearEntry2; assertNotNull(nearEntry2); assertTrue("Invalid near entry [hash=" + nearEntry2, nearEntry2.valid(topVer)); assertEquals(val, cache.localPeek(key, CachePeekMode.ONHEAP)); assertEquals(val, dht(0).peek(key)); assertEquals(val, dht(1).peek(key)); GridNearCacheEntry<Integer, String> nearEntry3 = nearEntry(0, key); info("Peeked entry after peeks [hash=" + hash(nearEntry1) + ", nearEntry=" + nearEntry3 + ']'); assert nearEntry2 == nearEntry3; assertNotNull(nearEntry3); assertTrue("Invalid near entry: " + nearEntry3, nearEntry3.valid(topVer)); assertNotNull(near(0).peekNearOnly(key)); assertNull(near(1).peekNearOnly(key)); assertEquals(val, cache.get(key)); assertEquals(val, cache.getAndRemove(key)); assertNull(cache.localPeek(key, CachePeekMode.ONHEAP)); assertNull(dht(primaryGrid(key)).peek(key)); assertTrue(cache.isLocalLocked(key, false)); assertTrue(cache.isLocalLocked(key, true)); } finally { lock.unlock(); } assertNull(near(0).peekNearOnly(key)); assertNull(near(1).peekNearOnly(key)); assertFalse(near(0).isLockedNearOnly(key)); assertFalse(cache.isLocalLocked(key, true)); } /** @throws Throwable If failed. */ public void testSingleLockReentryLocalAffinity() throws Throwable { checkSingleLockReentry(2); } /** @throws Throwable If failed. */ public void testSingleLockReentryRemoteAffinity() throws Throwable { checkSingleLockReentry(1); } /** * @param key Key. * @throws Exception If failed. */ private void checkSingleLockReentry(int key) throws Throwable { if (!transactional()) return; IgniteCache<Integer, String> near = jcache(0); String val = Integer.toString(key); Lock lock = near.lock(key); lock.lock(); try { near.put(key, val); assertEquals(val, near.localPeek(key, CachePeekMode.ONHEAP)); assertEquals(val, dht(primaryGrid(key)).peek(key)); assertTrue(near.isLocalLocked(key, false)); assertTrue(near.isLocalLocked(key, true)); lock.lock(); // Reentry. try { assertEquals(val, near.get(key)); assertEquals(val, near.getAndRemove(key)); assertNull(near.localPeek(key, CachePeekMode.ONHEAP)); assertNull(dht(primaryGrid(key)).peek(key)); assertTrue(near.isLocalLocked(key, false)); assertTrue(near.isLocalLocked(key, true)); } finally { lock.unlock(); } assertTrue(near.isLocalLocked(key, false)); assertTrue(near.isLocalLocked(key, true)); } catch (Throwable t) { error("Test failed.", t); throw t; } finally { lock.unlock(); } assertFalse(near(0).isLockedNearOnly(key)); assertFalse(near.isLocalLocked(key, true)); } /** @throws Exception If failed. */ public void testTransactionSingleGetLocalAffinity() throws Exception { checkTransactionSingleGet(2); } /** @throws Exception If failed. */ public void testTransactionSingleGetRemoteAffinity() throws Exception { checkTransactionSingleGet(1); } /** * @param key Key. * @throws Exception If failed. */ private void checkTransactionSingleGet(int key) throws Exception { IgniteCache<Integer, String> cache = jcache(0); String val = Integer.toString(key); cache.put(key, val); assertEquals(val, dht(0).peek(key)); assertEquals(val, dht(1).peek(key)); assertNull(near(0).peekNearOnly(key)); assertNull(near(1).peekNearOnly(key)); if (transactional()) { try (IgniteTx tx = grid(0).transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) { // Simple transaction get. assertEquals(val, cache.get(key)); tx.commit(); } } else assertEquals(val, cache.get(key)); assertEquals(val, dht(0).peek(key)); assertEquals(val, dht(1).peek(key)); assertNull(near(0).peekNearOnly(key)); assertNull(near(1).peekNearOnly(key)); } /** @throws Exception If failed. */ public void testTransactionSingleGetRemoveLocalAffinity() throws Exception { checkTransactionSingleGetRemove(2); } /** @throws Exception If failed. */ public void testTransactionSingleGetRemoveRemoteAffinity() throws Exception { checkTransactionSingleGetRemove(1); } /** * @param key Key * @throws Exception If failed. */ public void checkTransactionSingleGetRemove(int key) throws Exception { IgniteCache<Object, Object> cache = jcache(0); String val = Integer.toString(key); cache.put(key, val); assertEquals(val, dht(0).peek(key)); assertEquals(val, dht(1).peek(key)); assertNull(near(0).peekNearOnly(key)); assertNull(near(1).peekNearOnly(key)); if (transactional()) { try (IgniteTx tx = grid(0).transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) { // Read. assertEquals(val, cache.get(key)); // Remove. assertTrue(cache.remove(key)); tx.commit(); } } else { // Read. assertEquals(val, cache.get(key)); // Remove. assertTrue(cache.remove(key)); } assertNull(dht(0).peek(key)); assertNull(dht(1).peek(key)); assertNull(near(0).peekNearOnly(key)); assertNull(near(1).peekNearOnly(key)); } /** * */ private static class TestStore extends CacheStoreAdapter<Integer, String> { /** Map. */ private ConcurrentMap<Integer, String> map = new ConcurrentHashMap<>(); /** Create flag. */ private volatile boolean create = true; /** * */ void reset() { map.clear(); create = true; } /** @param create Create flag. */ void create(boolean create) { this.create = create; } /** @return Create flag. */ boolean isCreate() { return create; } /** * @param key Key. * @return Value. */ String value(Integer key) { return map.get(key); } /** * @param key Key. * @return {@code True} if has value. */ boolean hasValue(Integer key) { return map.containsKey(key); } /** @return {@code True} if empty. */ boolean isEmpty() { return map.isEmpty(); } /** {@inheritDoc} */ @Override public String load(Integer key) { if (!create) return map.get(key); String s = map.putIfAbsent(key, key.toString()); return s == null ? key.toString() : s; } /** {@inheritDoc} */ @Override public void write(javax.cache.Cache.Entry<? extends Integer, ? extends String> e) { map.put(e.getKey(), e.getValue()); } /** {@inheritDoc} */ @Override public void delete(Object key) { map.remove(key); } } }
# IGNITE-56 Fix GridCacheNearMultiNodeSelfTest.testPessimisticWriteThrough().
modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/near/GridCacheNearMultiNodeSelfTest.java
# IGNITE-56 Fix GridCacheNearMultiNodeSelfTest.testPessimisticWriteThrough().
<ide><path>odules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/near/GridCacheNearMultiNodeSelfTest.java <ide> <ide> String s = near.getAndPut(3, "3"); <ide> <del> assertNotNull(s); <ide> assertEquals("3", s); <ide> <ide> assertEquals("2", near.localPeek(2, CachePeekMode.ONHEAP)); <del> assertEquals("3", near.localPeek(3, CachePeekMode.ONHEAP)); <add> assertEquals("3", near.get(3)); <ide> <ide> assertNotNull(dht(primaryGrid(3)).peek(3, F.asList(GLOBAL))); <ide>