answer stringlengths 17 10.2M |
|---|
package org.xwiki.localization.script.internal;
import java.util.Collection;
import java.util.Collections;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.localization.LocalizationContext;
import org.xwiki.localization.LocalizationManager;
import org.xwiki.localization.Translation;
import org.xwiki.rendering.block.Block;
import org.xwiki.rendering.renderer.BlockRenderer;
import org.xwiki.rendering.renderer.printer.DefaultWikiPrinter;
import org.xwiki.rendering.syntax.Syntax;
import org.xwiki.script.service.ScriptService;
/**
* Provides Component-specific Scripting APIs.
*
* @version $Id$
* @since 4.3M2
*/
@Component
@Named("localization")
@Singleton
public class LocalizationScriptService implements ScriptService
{
/**
* Used to access translations.
*/
@Inject
private LocalizationManager localization;
/**
* Used to access current {@link java.util.Locale}.
*/
@Inject
private LocalizationContext locallizationContext;
/**
* Used to lookup renderers.
*/
@Inject
@Named("context")
private Provider<ComponentManager> componentManager;
/**
* @param key the translation key
* @return the translation, null if none can be found
*/
public Translation get(String key)
{
return this.localization.getTranslation(key, this.locallizationContext.getCurrentLocale());
}
// Helpers
/**
* @param key the translation key
* @return the rendered translation message
*/
public String render(String key)
{
return render(key, Collections.EMPTY_LIST);
}
/**
* @param key the translation key
* @param parameters the translation parameters
* @return the rendered translation message
*/
public String render(String key, Collection< ? > parameters)
{
return render(key, Syntax.PLAIN_1_0, parameters);
}
/**
* @param key the translation key
* @param syntax the syntax in which to render the translation message
* @param parameters the translation parameters
* @return the rendered translation message, the key if no translation can be found and null if the rendering failed
*/
public String render(String key, Syntax syntax, Collection< ? > parameters)
{
String result = null;
Translation translation = this.localization.getTranslation(key, this.locallizationContext.getCurrentLocale());
if (translation != null) {
Block block = translation.render(parameters);
// Render the block
try {
BlockRenderer renderer =
this.componentManager.get().getInstance(BlockRenderer.class, syntax.toIdString());
DefaultWikiPrinter wikiPrinter = new DefaultWikiPrinter();
renderer.render(block, wikiPrinter);
result = wikiPrinter.toString();
} catch (ComponentLookupException e) {
// TODO set current error
}
} else {
result = key;
}
return result;
}
} |
package org.redmine.ta;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import org.redmine.ta.RedmineManager.INCLUDE;
import org.redmine.ta.beans.*;
import org.redmine.ta.internal.RedmineXMLGenerator;
import org.redmine.ta.internal.logging.Logger;
import org.redmine.ta.internal.logging.LoggerFactory;
public class Simple {
private static Logger logger = LoggerFactory.getLogger(Simple.class);
private static String projectKey = "test";
private static Integer queryId = null; // any
public static void main(String[] args) {
String redmineHost = "http://ta-dev.dyndns.biz:8099/redmine-1.3.1";
String apiAccessKey = "e665eabdddfa3744e3cbea0f122445d098f2f4b2";
RedmineManager mgr = new RedmineManager(redmineHost, apiAccessKey);
try {
// getIssueWithRelations(mgr);
// tryCreateIssue(mgr);
// tryGetIssues(mgr);
// tryGetAllIssues(mgr);
// printCurrentUser(mgr);
// generateXMLForUser();
// generateXMLForTimeEntry();
// getSavedQueries(mgr);
// getProjects(mgr);
// tryCreateRelation(mgr);
// tryGetNews(mgr);
getProject(mgr);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void getProject(RedmineManager mgr) throws IOException, AuthenticationException, RedmineException, NotFoundException {
Project test = mgr.getProjectByKey("test");
System.out.println(test);
}
private static void tryGetNews(RedmineManager mgr) throws IOException, AuthenticationException, RedmineException, NotFoundException {
List<News> news = mgr.getNews(null);
for (News aNew : news) {
System.out.println(aNew);
}
}
private static void tryCreateRelation(RedmineManager mgr) throws IOException, AuthenticationException, NotFoundException, RedmineException {
IssueRelation r = mgr.createRelation(49, 50, IssueRelation.TYPE.precedes.toString());
logger.debug("Created relation " + r);
}
private static void getProjects(RedmineManager mgr) throws IOException, AuthenticationException, RedmineException {
List<Project> projects = mgr.getProjects();
logger.debug("Retrieved projects " + projects);
}
private static void getSavedQueries(RedmineManager mgr) throws IOException, AuthenticationException, NotFoundException, RedmineException {
List<SavedQuery> savedQueries = mgr.getSavedQueries("test");
logger.debug("Retrieved queries " + savedQueries);
}
private static void getIssueWithRelations(RedmineManager mgr) throws IOException, AuthenticationException, NotFoundException, RedmineException {
Issue issue = mgr.getIssueById(24580, INCLUDE.relations);
List<IssueRelation> r = issue.getRelations();
logger.debug("Retrieved relations " + r);
}
private static void tryCreateIssue(RedmineManager mgr) throws IOException, AuthenticationException, NotFoundException, RedmineException {
Issue issue = new Issue();
issue.setSubject("test123");
mgr.createIssue(projectKey, issue);
}
private static void generateXMLForTimeEntry() {
TimeEntry o = new TimeEntry();
o.setId(13);
o.setIssueId(45);
o.setActivityId(3);
o.setProjectId(55);
o.setUserId(66);
o.setHours(123f);
o.setComment("text here");
o.setSpentOn(new Date());
String xml = RedmineXMLGenerator.toXML(o);
logger.debug(xml);
}
private static void generateXMLForUser() {
User u = new User();
u.setLogin("newlogin");
String xml = RedmineXMLGenerator.toXML(u);
logger.debug(xml);
}
private static void tryGetIssues(RedmineManager mgr) throws Exception {
List<Issue> issues = mgr.getIssues(projectKey, queryId);
for (Issue issue : issues) {
logger.debug(issue.toString());
}
}
private static void tryGetAllIssues(RedmineManager mgr) throws Exception {
List<Issue> issues = mgr.getIssues(projectKey, null);
for (Issue issue : issues) {
logger.debug(issue.toString());
}
}
private static void printCurrentUser(RedmineManager mgr) throws Exception {
User currentUser = mgr.getCurrentUser();
logger.debug("user=" + currentUser.getMail());
currentUser.setMail("ne@com123.com");
mgr.update(currentUser);
logger.debug("updated user");
User currentUser2 = mgr.getCurrentUser();
logger.debug("updated user's mail: " + currentUser2.getMail());
}
} |
/**
* (TMS)
*/
package com.lhjz.portal.controller;
import com.lhjz.portal.base.BaseController;
import com.lhjz.portal.component.MailSender;
import com.lhjz.portal.constant.SysConstant;
import com.lhjz.portal.entity.Chat;
import com.lhjz.portal.entity.ChatAt;
import com.lhjz.portal.entity.ChatStow;
import com.lhjz.portal.entity.Label;
import com.lhjz.portal.entity.Log;
import com.lhjz.portal.entity.security.Group;
import com.lhjz.portal.entity.security.GroupMember;
import com.lhjz.portal.entity.security.User;
import com.lhjz.portal.model.Mail;
import com.lhjz.portal.model.RespBody;
import com.lhjz.portal.pojo.Enum.Action;
import com.lhjz.portal.pojo.Enum.ChatType;
import com.lhjz.portal.pojo.Enum.Prop;
import com.lhjz.portal.pojo.Enum.Status;
import com.lhjz.portal.pojo.Enum.Target;
import com.lhjz.portal.pojo.Enum.VoteType;
import com.lhjz.portal.repository.ChatAtRepository;
import com.lhjz.portal.repository.ChatRepository;
import com.lhjz.portal.repository.ChatStowRepository;
import com.lhjz.portal.repository.GroupMemberRepository;
import com.lhjz.portal.repository.GroupRepository;
import com.lhjz.portal.repository.LabelRepository;
import com.lhjz.portal.util.CollectionUtil;
import com.lhjz.portal.util.DateUtil;
import com.lhjz.portal.util.MapUtil;
import com.lhjz.portal.util.StringUtil;
import com.lhjz.portal.util.TemplateUtil;
import com.lhjz.portal.util.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
/**
* @author xi
* @date 2015328 1:19:05
*/
@Controller
@RequestMapping("admin/chat")
public class ChatController extends BaseController {
public static final int INT_50 = 50;
@Autowired
ChatRepository chatRepository;
@Autowired
GroupRepository groupRepository;
@Autowired
GroupMemberRepository groupMemberRepository;
@Autowired
ChatAtRepository chatAtRepository;
@Autowired
ChatStowRepository chatStowRepository;
@Autowired
LabelRepository labelRepository;
@Autowired
MailSender mailSender;
String dynamicAction = "admin/dynamic";
@RequestMapping(value = "create", method = RequestMethod.POST)
@ResponseBody
public RespBody create(
@RequestParam("baseURL") String baseURL,
@RequestParam(value = "usernames", required = false) String usernames,
@RequestParam(value = "groups", required = false) String groups,
@RequestParam("content") String content,
@RequestParam(value = "preMore", defaultValue = "true") Boolean preMore,
@RequestParam("lastId") Long lastId,
@RequestParam("contentHtml") String contentHtml) {
if (StringUtil.isEmpty(content)) {
return RespBody.failed("!");
}
final User loginUser = getLoginUser();
Chat chat = new Chat();
chat.setContent(content);
chat.setCreateDate(new Date());
chat.setCreator(loginUser);
chat.setStatus(Status.New);
chat.setType(ChatType.Msg);
Chat chat2 = chatRepository.saveAndFlush(chat);
log(Action.Create, Target.Chat, chat2.getId());
final String href = baseURL + dynamicAction + "?id=" + chat2.getId();
final Mail mail = Mail.instance();
if (StringUtil.isNotEmpty(usernames) || StringUtil.isNotEmpty(groups)) {
Map<String, User> atUserMap = new HashMap<>();
if (StringUtil.isNotEmpty(usernames)) {
String[] usernameArr = usernames.split(",");
Arrays.asList(usernameArr).forEach((username) -> {
User user = getUser(username);
if (user != null) {
mail.addUsers(user);
atUserMap.put(user.getUsername(), user);
}
});
}
if (StringUtil.isNotEmpty(groups)) {
String[] groupArr = groups.split(",");
Arrays.asList(groupArr)
.forEach(
(group) -> {
List<Group> groupList = groupRepository
.findByGroupName(group);
if (groupList.size() > 0) {
List<GroupMember> groupMembers = groupMemberRepository
.findByGroup(groupList.get(0));
groupMembers.forEach(
gm -> {
User user = getUser(gm
.getUsername());
if (user != null) {
mail.addUsers(user);
atUserMap.put(user
.getUsername(),
user);
}
});
}
});
}
List<ChatAt> chatAtList = new ArrayList<>();
// chatAt
atUserMap.values().forEach((user) -> {
ChatAt chatAt = new ChatAt();
chatAt.setChat(chat2);
chatAt.setAtUser(user);
chatAt.setCreateDate(new Date());
chatAt.setCreator(loginUser);
chatAtList.add(chatAt);
});
chatAtRepository.save(chatAtList);
chatAtRepository.flush();
try {
mailSender.sendHtmlByQueue(
String.format("TMS-@_%s", DateUtil.format(new Date(), DateUtil.FORMAT7)),
TemplateUtil.process("templates/mail/mail-dynamic", MapUtil.objArr2Map("user", loginUser,
"date", new Date(), "href", href, "title", "@", "content", contentHtml)),
getLoginUserName(loginUser), mail.get());
} catch (Exception e) {
e.printStackTrace();
}
}
if (Boolean.FALSE.equals(preMore) && chatRepository.countQueryRecent(lastId) <= INT_50) {
List<Chat> chats = chatRepository.queryRecent(lastId);
return RespBody.succeed(chats);
}
return RespBody.succeed(chat2);
}
@RequestMapping(value = "update", method = RequestMethod.POST)
@ResponseBody
public RespBody update(
@RequestParam("id") Long id,
@RequestParam("version") Long version,
@RequestParam("content") String content,
@RequestParam("baseURL") String baseURL,
@RequestParam(value = "usernames", required = false) String usernames,
@RequestParam(value = "groups", required = false) String groups,
@RequestParam(value = "diff", required = false) String diff,
@RequestParam(value = "contentHtmlOld", required = false) String contentHtmlOld,
@RequestParam(value = "contentHtml", required = false) String contentHtml) {
if (StringUtil.isEmpty(content)) {
return RespBody.failed("!");
}
final User loginUser = getLoginUser();
Chat chat = chatRepository.findOne(id);
boolean isOpenEdit = Boolean.TRUE.equals(chat.getOpenEdit());
if (!isSuperOrCreator(chat.getCreator().getUsername()) && !isOpenEdit) {
return RespBody.failed("!");
}
if (chat.getVersion() != version) {
return RespBody.failed(",!");
}
if (content.equals(chat.getContent())) {
return RespBody.failed("!");
}
chat.setContent(content);
chat.setUpdateDate(new Date());
chat.setUpdater(loginUser);
chat.setStatus(Status.Updated);
Chat chat2 = chatRepository.saveAndFlush(chat);
log(Action.Update, Target.Chat, chat2.getId());
final String href = baseURL + dynamicAction + "?id=" + chat2.getId();
final String html;
if (StringUtil.isNotEmpty(diff)) {
html = "<h3>(Markdown):</h3><b>:</b> <a href=\"" + href + "\">" + href + "</a><hr/>" + diff;
} else {
html = "<h3>:</h3>" + contentHtml + "<hr/><h3>:</h3>" + contentHtmlOld;
}
final Mail mail = Mail.instance();
if (StringUtil.isNotEmpty(usernames) || StringUtil.isNotEmpty(groups)) {
Map<String, User> atUserMap = new HashMap<>();
if (StringUtil.isNotEmpty(usernames)) {
String[] usernameArr = usernames.split(",");
Arrays.asList(usernameArr).forEach((username) -> {
User user = getUser(username);
if (user != null) {
mail.addUsers(user);
atUserMap.put(user.getUsername(), user);
}
});
}
if (StringUtil.isNotEmpty(groups)) {
String[] groupArr = groups.split(",");
Arrays.asList(groupArr)
.forEach(
(group) -> {
List<Group> groupList = groupRepository
.findByGroupName(group);
if (groupList.size() > 0) {
List<GroupMember> groupMembers = groupMemberRepository
.findByGroup(groupList.get(0));
groupMembers.forEach(
gm -> {
User user = getUser(gm
.getUsername());
if (user != null) {
mail.addUsers(user);
atUserMap.put(user
.getUsername(),
user);
}
});
}
});
}
List<ChatAt> chatAtList = new ArrayList<>();
// chatAt
atUserMap.values().forEach(
(user) -> {
ChatAt chatAt2 = chatAtRepository
.findOneByChatAndAtUser(chat2, user);
if (chatAt2 == null) {
ChatAt chatAt = new ChatAt();
chatAt.setChat(chat2);
chatAt.setAtUser(user);
chatAtList.add(chatAt);
} else {
chatAt2.setStatus(Status.New);
chatAtList.add(chatAt2);
}
});
chatAtRepository.save(chatAtList);
chatAtRepository.flush();
try {
mailSender.sendHtmlByQueue(
String.format("TMS-@_%s", DateUtil.format(new Date(), DateUtil.FORMAT7)),
TemplateUtil.process("templates/mail/mail-dynamic", MapUtil.objArr2Map("user", loginUser,
"date", new Date(), "href", href, "title", "@", "content", html)),
getLoginUserName(loginUser), mail.get());
} catch (Exception e) {
e.printStackTrace();
}
}
return RespBody.succeed(chat2);
}
@RequestMapping(value = "delete", method = RequestMethod.POST)
@ResponseBody
public RespBody delete(@RequestParam("id") Long id) {
Chat chat = chatRepository.findOne(id);
if (chat == null) {
return RespBody.failed("!");
}
if (!isSuperOrCreator(chat.getCreator().getUsername())) {
return RespBody.failed("!");
}
List<ChatAt> chatAts = chatAtRepository.findByChat(chat);
chatAtRepository.delete(chatAts);
chatAtRepository.flush();
List<ChatStow> chatStows = chatStowRepository.findByChat(chat);
chatStowRepository.delete(chatStows);
chatStowRepository.flush();
chatRepository.delete(chat);
chatRepository.flush();
log(Action.Delete, Target.Chat, chat.getId(), chat);
return RespBody.succeed(id);
}
@RequestMapping(value = {"get", "get/unmask"}, method = RequestMethod.GET)
@ResponseBody
public RespBody get(@RequestParam("id") Long id) {
Chat chat = chatRepository.findOne(id);
if (chat == null) {
return RespBody.failed("!");
}
return RespBody.succeed(chat);
}
@RequestMapping(value = {"poll", "poll/unmask"}, method = RequestMethod.GET)
@ResponseBody
public RespBody poll(
@RequestParam("lastId") Long lastId,
@RequestParam("lastEvtId") Long lastEvtId,
@RequestParam(value = "isAt", required = false, defaultValue = "false") Boolean isAt) {
long cnt = Boolean.TRUE.equals(isAt) ? chatRepository.countQueryRecentAt(
WebUtil.getUsername(), lastId) : chatRepository
.countQueryRecent(lastId);
long cntLogs = logRepository.countQueryRecent(lastEvtId);
long cntAtUserNew = chatAtRepository.countChatAtUserNew(WebUtil
.getUsername());
Long[] data = new Long[]{lastId, cnt, lastEvtId, cntLogs,
cntAtUserNew};
List<Log> logs = logRepository.queryRecent(lastEvtId);
return RespBody.succeed(data).addMsg(logs);
}
@RequestMapping(value = {"getNews", "getNews/unmask"}, method = RequestMethod.GET)
@ResponseBody
public RespBody getNews(@RequestParam("lastId") Long lastId) {
List<Chat> chats = chatRepository.queryRecent(lastId);
return RespBody.succeed(chats);
}
@RequestMapping(value = "more", method = RequestMethod.GET)
@ResponseBody
public RespBody more(
@PageableDefault(sort = {"createDate"}, direction = Direction.DESC) Pageable pageable) {
Page<Chat> chats = chatRepository.findAll(pageable);
chats = new PageImpl<>(CollectionUtil.reverseList(chats
.getContent()), pageable, chats.getTotalElements());
return RespBody.succeed(chats);
}
@RequestMapping(value = "more/old", method = RequestMethod.GET)
@ResponseBody
public RespBody moreOld(
@RequestParam("startId") Long startId,
@RequestParam(value = "size", required = false, defaultValue = "10") int size) {
List<Chat> chats = chatRepository.queryMoreOld(startId, size);
long countAllOld = chatRepository.countAllOld(startId);
Map<String, Object> map = new HashMap<>();
map.put("content", CollectionUtil.reverseList(chats));
map.put("hasMore", countAllOld > chats.size());
map.put("countMore", countAllOld - chats.size());
map.put("numberOfElements", chats.size());
map.put("size", size);
return RespBody.succeed(map);
}
@RequestMapping(value = "more/new", method = RequestMethod.GET)
@ResponseBody
public RespBody moreNew(
@RequestParam("startId") Long startId,
@RequestParam(value = "size", required = false, defaultValue = "10") int size) {
List<Chat> chats = chatRepository.queryMoreNew(startId, size);
long countAllNew = chatRepository.countAllNew(startId);
Map<String, Object> map = new HashMap<>();
map.put("content", chats);
map.put("hasMore", countAllNew > chats.size());
map.put("countMore", countAllNew - chats.size());
map.put("numberOfElements", chats.size());
map.put("size", size);
return RespBody.succeed(map);
}
@RequestMapping(value = "moreLogs", method = RequestMethod.GET)
@ResponseBody
public RespBody moreLogs(
@PageableDefault(sort = {"createDate"}, direction = Direction.DESC) Pageable pageable) {
Page<Log> logs = logRepository.findByTarget(Target.Translate, pageable);
return RespBody.succeed(logs);
}
@RequestMapping(value = {"search", "search/unmask"}, method = RequestMethod.GET)
@ResponseBody
public RespBody search(
@PageableDefault(sort = {"createDate"}, direction = Direction.DESC) Pageable pageable,
@RequestParam(value = "search") String search) {
Page<Chat> chats;
if (search.startsWith(SysConstant.FILTER_PRE)) {
String query = search.substring(SysConstant.FILTER_PRE.length());
String[] querys = query.split(":");
final List<User> users = new ArrayList<>();
String searchContent = null;
if (querys.length > 0) {
Stream.of(querys[0].split("&")).filter((name) -> StringUtil.isNotEmpty(name.trim())).forEach((name) -> {
User user = getUser(name);
if (user != null) {
users.add(user);
}
});
}
if (querys.length > 1) {
searchContent = querys[1].trim();
}
if (CollectionUtil.isNotEmpty(users)) {
if (StringUtil.isNotEmpty(searchContent)) {
chats = chatRepository.findByCreatorInAndContentContainingIgnoreCase(
users, searchContent, pageable);
} else {
chats = chatRepository.findByCreatorIn(users, pageable);
}
} else {
return RespBody.failed("!");
}
} else {
chats = chatRepository.findByContentLike("%" + search + "%",
pageable);
}
return RespBody.succeed(chats);
}
@RequestMapping(value = {"searchBy", "searchBy/unmask"}, method = RequestMethod.GET)
@ResponseBody
public RespBody searchBy(
@RequestParam(value = "id") Long id,
@PageableDefault(sort = {"createDate"}, direction = Direction.DESC) Pageable pageable) {
long cntGtId = chatRepository.countGtId(id);
int size = pageable.getPageSize();
long page = cntGtId / size;
if (cntGtId % size == 0) {
page
}
pageable = new PageRequest(page > -1 ? (int) page : 0, size,
Direction.DESC, "createDate");
Page<Chat> chats = chatRepository.findAll(pageable);
chats = new PageImpl<>(CollectionUtil.reverseList(chats
.getContent()), pageable, chats.getTotalElements());
return RespBody.succeed(chats);
}
private boolean isVoterExists(String voters) {
boolean isExits = false;
if (voters != null) {
String loginUsername = WebUtil.getUsername();
String[] voterArr = voters.split(",");
for (String voter : voterArr) {
if (voter.equals(loginUsername)) {
isExits = true;
break;
}
}
}
return isExits;
}
@RequestMapping(value = {"vote", "vote/unmask"}, method = RequestMethod.POST)
@ResponseBody
public RespBody vote(@RequestParam("id") Long id,
@RequestParam("baseURL") String baseURL,
@RequestParam("contentHtml") String contentHtml,
@RequestParam(value = "type", required = false) String type) {
Chat chat = chatRepository.findOne(id);
if (chat == null) {
return RespBody.failed("!");
}
String loginUsername = WebUtil.getUsername();
Chat chat2;
String title;
final User loginUser = getLoginUser();
if (VoteType.Zan.name().equalsIgnoreCase(type)) {
String voteZan = chat.getVoteZan();
if (isVoterExists(voteZan)) {
return RespBody.failed("[]");
} else {
chat.setVoteZan(voteZan == null ? loginUsername : voteZan + ','
+ loginUsername);
Integer voteZanCnt = chat.getVoteZanCnt();
if (voteZanCnt == null) {
voteZanCnt = 0;
}
chat.setVoteZanCnt(++voteZanCnt);
chat2 = chatRepository.saveAndFlush(chat);
title = loginUser.getName() + "[" + loginUsername
+ "]!";
}
} else {
String voteCai = chat.getVoteCai();
if (isVoterExists(voteCai)) {
return RespBody.failed("[]");
} else {
chat.setVoteCai(voteCai == null ? loginUsername : voteCai + ','
+ loginUsername);
Integer voteCaiCnt = chat.getVoteCaiCnt();
if (voteCaiCnt == null) {
voteCaiCnt = 0;
}
chat.setVoteCaiCnt(++voteCaiCnt);
chat2 = chatRepository.saveAndFlush(chat);
title = loginUser.getName() + "[" + loginUsername
+ "]!";
}
}
final String href = baseURL + dynamicAction + "?id=" + id;
final String titleHtml = title;
final Mail mail = Mail.instance().addUsers(chat.getCreator());
final String html = "<h3>:</h3><hr/>" + contentHtml;
try {
mailSender
.sendHtmlByQueue(String.format("TMS-@_%s", DateUtil.format(new Date(), DateUtil.FORMAT7)),
TemplateUtil.process("templates/mail/mail-dynamic", MapUtil.objArr2Map("user", loginUser,
"date", new Date(), "href", href, "title", titleHtml, "content", html)),
getLoginUserName(loginUser), mail.get());
} catch (Exception e) {
e.printStackTrace();
}
log(Action.Vote, Target.Chat, chat.getId(), chat2);
return RespBody.succeed(chat2);
}
@RequestMapping(value = {"getAtChats", "getAtChats/unmask"}, method = RequestMethod.GET)
@ResponseBody
public RespBody getAtChats(
@PageableDefault(sort = {"createDate"}, direction = Direction.DESC) Pageable pageable) {
Page<ChatAt> chatAts = chatAtRepository.findByChatNotNullAndAtUserAndStatus(
getLoginUser(), Status.New, pageable);
return RespBody.succeed(chatAts);
}
@RequestMapping(value = {"markAsReaded", "markAsReaded/unmask"}, method = RequestMethod.POST)
@ResponseBody
public RespBody markAsReaded(@RequestParam("chatAtId") Long chatAtId) {
ChatAt chatAt = chatAtRepository.findOne(chatAtId);
if (chatAt == null) {
return RespBody.failed("@,!");
}
chatAt.setStatus(Status.Readed);
chatAtRepository.saveAndFlush(chatAt);
return RespBody.succeed(chatAt);
}
@RequestMapping(value = {"markAsReadedByChat", "markAsReadedByChat/unmask"}, method = RequestMethod.POST)
@ResponseBody
public RespBody markAsReadedByChat(@RequestParam("chatId") Long chatId) {
Chat chat = chatRepository.findOne(chatId);
if (chat == null) {
return RespBody.failed("@,!");
}
int cnt = chatAtRepository.markChatAsReaded(chat, getLoginUser());
return RespBody.succeed(cnt);
}
@RequestMapping(value = {"markAllAsReaded",
"markAllAsReaded/unmask"}, method = RequestMethod.POST)
@ResponseBody
public RespBody markAllAsReaded() {
int cnt = chatAtRepository.markChatAllAsReaded(getLoginUser());
return RespBody.succeed(cnt);
}
@RequestMapping(value = {"stow", "stow/unmask"}, method = RequestMethod.POST)
@ResponseBody
public RespBody stow(@RequestParam("id") Long id) {
Chat chat = chatRepository.findOne(id);
if (chat == null) {
return RespBody.failed(",!");
}
User loginUser = getLoginUser();
ChatStow chatStow = chatStowRepository.findOneByChatAndStowUser(chat,
loginUser);
if (chatStow != null) {
return RespBody.failed("!");
}
ChatStow chatStow2 = new ChatStow();
chatStow2.setChat(chat);
chatStow2.setStowUser(loginUser);
ChatStow chatStow3 = chatStowRepository.saveAndFlush(chatStow2);
return RespBody.succeed(chatStow3);
}
@RequestMapping(value = {"removeStow", "removeStow/unmask"}, method = RequestMethod.POST)
@ResponseBody
public RespBody removeStow(@RequestParam("id") Long id) {
chatStowRepository.delete(id);
return RespBody.succeed(id);
}
@RequestMapping(value = {"getStows", "getStows/unmask"}, method = RequestMethod.GET)
@ResponseBody
public RespBody getStows() {
List<ChatStow> chatStows = chatStowRepository.findByChatNotNullAndStowUserAndStatus(
getLoginUser(), Status.New);
return RespBody.succeed(chatStows);
}
@RequestMapping(value = "getReplies", method = RequestMethod.GET)
@ResponseBody
public RespBody getReplies(@RequestParam("id") Long id) {
String query = StringUtil.replaceByKV(
"%[#{id}](%/admin/dynamic?id={id})%", "id", id);
List<Chat> chats = chatRepository.queryReplies(id, query);
return RespBody.succeed(chats);
}
@RequestMapping(value = "openEdit", method = RequestMethod.POST)
@ResponseBody
public RespBody openEdit(@RequestParam("id") Long id,
@RequestParam("open") Boolean open) {
Chat chat = chatRepository.findOne(id);
if (chat == null) {
return RespBody.failed(",!");
}
chat.setOpenEdit(open);
chatRepository.saveAndFlush(chat);
return RespBody.succeed();
}
@RequestMapping(value = {"asWiki", "asWiki/unmask"}, method = RequestMethod.POST)
@ResponseBody
public RespBody asWiki(@RequestParam("id") Long id,
@RequestParam("title") String title,
@RequestParam(value = "privated", required = false) Boolean privated,
@RequestParam(value = "labels", required = false) String labels) {
if (StringUtil.isEmpty(title)) {
return RespBody.failed("!");
}
Chat chat = chatRepository.findOne(id);
if (chat == null) {
return RespBody.failed("!");
}
chat.setTitle(title);
chat.setType(ChatType.Wiki);
chat.setPrivated(Boolean.TRUE.equals(privated));
Chat chat2 = chatRepository.saveAndFlush(chat);
if (StringUtil.isNotEmpty(labels)) {
List<Label> labelList = new ArrayList<>();
String[] labelArr = labels.split(SysConstant.COMMA);
Stream.of(labelArr).forEach((lbl) -> {
Label label = new Label();
label.setCreateDate(new Date());
label.setCreator(WebUtil.getUsername());
label.setName(lbl);
label.setStatus(Status.New);
label.setChat(chat2);
labelList.add(label);
});
labelRepository.save(labelList);
labelRepository.flush();
}
logWithProperties(Action.Update, Target.Chat, chat2.getId(),
Prop.Title.name(), title);
return RespBody.succeed(id);
}
@RequestMapping(value = {"updateWiki", "updateWiki/unmask"}, method = RequestMethod.POST)
@ResponseBody
public RespBody updateWiki(@RequestParam("id") Long id,
@RequestParam("title") String title,
@RequestParam(value = "privated", required = false) Boolean privated,
@RequestParam(value = "labels", required = false) String labels) {
if (StringUtil.isEmpty(title)) {
return RespBody.failed("!");
}
Chat chat = chatRepository.findOne(id);
if (chat == null) {
return RespBody.failed("!");
}
if (!isSuperOrCreator(chat.getCreator().getUsername())) {
return RespBody.failed("!");
}
String oldTitle = chat.getTitle();
chat.setTitle(title);
if (privated != null) {
chat.setPrivated(privated);
}
Chat chat2 = chatRepository.saveAndFlush(chat);
if (StringUtil.isNotEmpty(labels)) {
List<Label> labelList2 = labelRepository.findByChat(chat2);
labelRepository.delete(labelList2);
labelRepository.flush();
List<Label> labelList = new ArrayList<>();
String[] labelArr = labels.split(SysConstant.COMMA);
Stream.of(labelArr).forEach((lbl) -> {
Label label = new Label();
label.setCreateDate(new Date());
label.setCreator(WebUtil.getUsername());
label.setName(lbl);
label.setStatus(Status.New);
label.setChat(chat2);
labelList.add(label);
});
labelRepository.save(labelList);
labelRepository.flush();
}
logWithProperties(Action.Update, Target.Chat, chat2.getId(),
Prop.Title.name(), title, oldTitle);
return RespBody.succeed(id);
}
@RequestMapping(value = "deleteWiki", method = RequestMethod.POST)
@ResponseBody
public RespBody deleteWiki(@RequestParam("id") Long id) {
Chat chat = chatRepository.findOne(id);
if (chat == null) {
return RespBody.failed("!");
}
if (!isSuperOrCreator(chat.getCreator().getUsername())) {
return RespBody.failed("!");
}
chat.setType(ChatType.Msg);
chatRepository.saveAndFlush(chat);
return RespBody.succeed(id);
}
@RequestMapping(value = {"addLabel", "addLabel/unmask"}, method = RequestMethod.POST)
@ResponseBody
public RespBody addLabel(@RequestParam("id") Long id,
@RequestParam("label") String label) {
if (StringUtil.isEmpty(label)) {
return RespBody.failed("!");
}
Chat chat = chatRepository.findOne(id);
if (chat == null) {
return RespBody.failed("!");
}
Label label2 = new Label();
label2.setCreateDate(new Date());
label2.setCreator(WebUtil.getUsername());
label2.setName(label);
label2.setStatus(Status.New);
label2.setChat(chat);
labelRepository.save(label2);
labelRepository.flush();
logWithProperties(Action.Update, Target.Chat, chat.getId(),
Prop.Labels.name(), label);
return RespBody.succeed(id);
}
@RequestMapping(value = {"deleteLabel", "deleteLabel/unmask"}, method = RequestMethod.POST)
@ResponseBody
public RespBody deleteLabel(@RequestParam("labelId") Long labelId) {
Label label = labelRepository.findOne(labelId);
if (!isSuperOrCreator(label.getCreator())) {
return RespBody.failed("!");
}
labelRepository.delete(labelId);
log(Action.Delete, Target.Label, labelId);
return RespBody.succeed(labelId);
}
} |
/**
* (TMS)
*/
package com.lhjz.portal.controller;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.lhjz.portal.base.BaseController;
import com.lhjz.portal.component.MailSender2;
import com.lhjz.portal.entity.Chat;
import com.lhjz.portal.entity.Log;
import com.lhjz.portal.entity.security.User;
import com.lhjz.portal.model.Mail;
import com.lhjz.portal.model.RespBody;
import com.lhjz.portal.pojo.Enum.Action;
import com.lhjz.portal.pojo.Enum.Status;
import com.lhjz.portal.pojo.Enum.Target;
import com.lhjz.portal.repository.ChatRepository;
import com.lhjz.portal.repository.LogRepository;
import com.lhjz.portal.util.CollectionUtil;
import com.lhjz.portal.util.DateUtil;
import com.lhjz.portal.util.MapUtil;
import com.lhjz.portal.util.StringUtil;
import com.lhjz.portal.util.TemplateUtil;
import com.lhjz.portal.util.ThreadUtil;
/**
*
* @author xi
*
* @date 2015328 1:19:05
*
*/
@Controller
@RequestMapping("admin/chat")
public class ChatController extends BaseController {
static Logger logger = LoggerFactory.getLogger(ChatController.class);
@Autowired
ChatRepository chatRepository;
@Autowired
LogRepository logRepository;
@Autowired
MailSender2 mailSender;
String dynamicAction = "admin/dynamic";
@RequestMapping(value = "create", method = RequestMethod.POST)
@ResponseBody
public RespBody create(@RequestParam("baseURL") String baseURL,
@RequestParam(value = "usernames", required = false) String usernames,
@RequestParam("content") String content,
@RequestParam(value = "preMore", defaultValue = "true") Boolean preMore,
@RequestParam("lastId") Long lastId,
@RequestParam("contentHtml") String contentHtml) {
if (StringUtil.isEmpty(content)) {
return RespBody.failed("!");
}
Chat chat = new Chat();
chat.setContent(content);
chat.setCreateDate(new Date());
chat.setCreator(getLoginUser());
chat.setStatus(Status.New);
Chat chat2 = chatRepository.saveAndFlush(chat);
log(Action.Create, Target.Chat, chat2.getId());
final User loginUser = getLoginUser();
final String href = baseURL + dynamicAction + "?id=" + chat2.getId();
final String html = contentHtml;
final Mail mail = Mail.instance();
if (StringUtil.isNotEmpty(usernames)) {
String[] usernameArr = usernames.split(",");
Arrays.asList(usernameArr).stream().forEach((username) -> {
mail.addUsers(getUser(username));
});
ThreadUtil.exec(() -> {
try {
Thread.sleep(3000);
mailSender.sendHtml(String.format("TMS-@_%s",
DateUtil.format(new Date(), DateUtil.FORMAT7)),
TemplateUtil.process("templates/mail/mail-dynamic",
MapUtil.objArr2Map("user", loginUser,
"date", new Date(), "href", href,
"title", "@", "content",
html)),
mail.get());
logger.info("");
} catch (Exception e) {
e.printStackTrace();
logger.error("");
}
});
}
if (!preMore && chatRepository.countQueryRecent(lastId) <= 50) {
List<Chat> chats = chatRepository.queryRecent(lastId);
return RespBody.succeed(chats);
}
return RespBody.succeed(chat2);
}
@RequestMapping(value = "update", method = RequestMethod.POST)
@ResponseBody
public RespBody update(@RequestParam("id") Long id,
@RequestParam("content") String content,
@RequestParam("baseURL") String baseURL,
@RequestParam(value = "usernames", required = false) String usernames,
@RequestParam("contentHtmlOld") String contentHtmlOld,
@RequestParam("contentHtml") String contentHtml) {
if (StringUtil.isEmpty(content)) {
return RespBody.failed("!");
}
Chat chat = chatRepository.findOne(id);
chat.setContent(content);
chat.setUpdateDate(new Date());
chat.setUpdater(getLoginUser());
chat.setStatus(Status.Updated);
Chat chat2 = chatRepository.saveAndFlush(chat);
log(Action.Update, Target.Chat, chat2.getId());
final User loginUser = getLoginUser();
final String href = baseURL + dynamicAction + "?id=" + chat2.getId();
final String html = "<h3>:</h3>" + contentHtml
+ "<hr/><h3>:</h3>" + contentHtmlOld;
final Mail mail = Mail.instance();
if (StringUtil.isNotEmpty(usernames)) {
String[] usernameArr = usernames.split(",");
Arrays.asList(usernameArr).stream().forEach((username) -> {
mail.addUsers(getUser(username));
});
ThreadUtil.exec(() -> {
try {
Thread.sleep(3000);
mailSender.sendHtml(String.format("TMS-@_%s",
DateUtil.format(new Date(), DateUtil.FORMAT7)),
TemplateUtil.process("templates/mail/mail-dynamic",
MapUtil.objArr2Map("user", loginUser,
"date", new Date(), "href", href,
"title", "@",
"content", html)),
mail.get());
logger.info("");
} catch (Exception e) {
e.printStackTrace();
logger.error("");
}
});
}
return RespBody.succeed(chat2);
}
@RequestMapping(value = "delete", method = RequestMethod.POST)
@ResponseBody
public RespBody delete(@RequestParam("id") Long id) {
Chat chat = chatRepository.findOne(id);
if (chat == null) {
return RespBody.failed("!");
}
chatRepository.delete(chat);
chatRepository.flush();
log(Action.Delete, Target.Chat, chat.getId(), chat);
return RespBody.succeed(id);
}
@RequestMapping(value = { "get", "get/unmask" }, method = RequestMethod.GET)
@ResponseBody
public RespBody get(@RequestParam("id") Long id) {
Chat chat = chatRepository.findOne(id);
if (chat == null) {
return RespBody.failed("!");
}
return RespBody.succeed(chat);
}
@RequestMapping(value = { "poll", "poll/unmask" }, method = RequestMethod.GET)
@ResponseBody
public RespBody poll(@RequestParam("lastId") Long lastId,
@RequestParam("lastEvtId") Long lastEvtId) {
long cnt = chatRepository.countQueryRecent(lastId);
long cntLogs = logRepository.countQueryRecent(lastEvtId);
Long[] data = new Long[] { lastId, cnt, lastEvtId, cntLogs };
List<Log> logs = logRepository.queryRecent(lastEvtId);
return RespBody.succeed(data).addMsg(logs);
}
@RequestMapping(value = "getNews", method = RequestMethod.GET)
@ResponseBody
public RespBody getNews(@RequestParam("lastId") Long lastId) {
List<Chat> chats = chatRepository.queryRecent(lastId);
return RespBody.succeed(chats);
}
@RequestMapping(value = "more", method = RequestMethod.GET)
@ResponseBody
public RespBody more(@PageableDefault(sort = {
"createDate" }, direction = Direction.DESC) Pageable pageable) {
Page<Chat> chats = chatRepository.findAll(pageable);
chats = new PageImpl<Chat>(
CollectionUtil.reverseList(chats.getContent()), pageable,
chats.getTotalElements());
return RespBody.succeed(chats);
}
@RequestMapping(value = "moreLogs", method = RequestMethod.GET)
@ResponseBody
public RespBody moreLogs(@PageableDefault(sort = {
"createDate" }, direction = Direction.DESC) Pageable pageable) {
Page<Log> logs = logRepository.findByTarget(Target.Translate, pageable);
return RespBody.succeed(logs);
}
} |
package com.myjeeva.digitalocean.common;
import com.myjeeva.digitalocean.pojo.Account;
import com.myjeeva.digitalocean.pojo.Action;
import com.myjeeva.digitalocean.pojo.Actions;
import com.myjeeva.digitalocean.pojo.Backups;
import com.myjeeva.digitalocean.pojo.Delete;
import com.myjeeva.digitalocean.pojo.Domain;
import com.myjeeva.digitalocean.pojo.DomainRecord;
import com.myjeeva.digitalocean.pojo.DomainRecords;
import com.myjeeva.digitalocean.pojo.Domains;
import com.myjeeva.digitalocean.pojo.Droplet;
import com.myjeeva.digitalocean.pojo.Droplets;
import com.myjeeva.digitalocean.pojo.FloatingIP;
import com.myjeeva.digitalocean.pojo.FloatingIPs;
import com.myjeeva.digitalocean.pojo.Image;
import com.myjeeva.digitalocean.pojo.Images;
import com.myjeeva.digitalocean.pojo.Kernels;
import com.myjeeva.digitalocean.pojo.Key;
import com.myjeeva.digitalocean.pojo.Keys;
import com.myjeeva.digitalocean.pojo.Neighbors;
import com.myjeeva.digitalocean.pojo.Regions;
import com.myjeeva.digitalocean.pojo.Response;
import com.myjeeva.digitalocean.pojo.Sizes;
import com.myjeeva.digitalocean.pojo.Snapshots;
import com.myjeeva.digitalocean.pojo.Tag;
import com.myjeeva.digitalocean.pojo.Tags;
/**
* Enumeration of DigitalOcean RESTful resource information.
*
* @author Jeevanandam M. (jeeva@myjeeva.com)
*
* @since v2.0
*/
public enum ApiAction {
// Droplet
AVAILABLE_DROPLETS("/droplets", "droplets", RequestMethod.GET, Droplets.class),
AVAILABLE_DROPLETS_KERNELS("/droplets/%s/kernels", "kernels", RequestMethod.GET, Kernels.class),
GET_DROPLET_SNAPSHOTS("/droplets/%s/snapshots", "snapshots", RequestMethod.GET, Snapshots.class),
GET_DROPLET_BACKUPS("/droplets/%s/backups", "backups", RequestMethod.GET, Backups.class),
GET_DROPLET_NEIGHBORS("/droplets/%s/neighbors", "droplets", RequestMethod.GET, Droplets.class),
GET_DROPLET_INFO("/droplets/%s", "droplet", RequestMethod.GET, Droplet.class),
CREATE_DROPLET("/droplets", "droplet", RequestMethod.POST, Droplet.class),
CREATE_DROPLETS("/droplets", "droplets", RequestMethod.POST, Droplets.class),
DELETE_DROPLET("/droplets/%s", "response", RequestMethod.DELETE, Delete.class),
REBOOT_DROPLET("/droplets/%s/actions", "action", RequestMethod.POST, Action.class),
POWER_CYCLE_DROPLET("/droplets/%s/actions", "action", RequestMethod.POST, Action.class),
SHUTDOWN_DROPLET("/droplets/%s/actions", "action", RequestMethod.POST, Action.class),
POWER_OFF_DROPLET("/droplets/%s/actions", "action", RequestMethod.POST, Action.class),
POWER_ON_DROPLET("/droplets/%s/actions", "action", RequestMethod.POST, Action.class),
RESET_DROPLET_PASSWORD("/droplets/%s/actions", "action", RequestMethod.POST, Action.class),
RESIZE_DROPLET("/droplets/%s/actions", "action", RequestMethod.POST, Action.class),
RESTORE_DROPLET("/droplets/%s/actions", "action", RequestMethod.POST, Action.class),
REBUILD_DROPLET("/droplets/%s/actions", "action", RequestMethod.POST, Action.class),
RENAME_DROPLET("/droplets/%s/actions", "action", RequestMethod.POST, Action.class),
CHANGE_DROPLET_KERNEL("/droplets/%s/actions", "action", RequestMethod.POST, Action.class),
ENABLE_DROPLET_IPV6("/droplets/%s/actions", "action", RequestMethod.POST, Action.class),
ENABLE_DROPLET_BACKUPS("/droplets/%s/actions", "action", RequestMethod.POST, Action.class),
DISABLE_DROPLET_BACKUPS("/droplets/%s/actions", "action", RequestMethod.POST, Action.class),
ENABLE_DROPLET_PRIVATE_NETWORKING("/droplets/%s/actions", "action", RequestMethod.POST, Action.class),
SNAPSHOT_DROPLET("/droplets/%s/actions", "action", RequestMethod.POST, Action.class),
// Account
GET_ACCOUNT_INFO("/account", "account", RequestMethod.GET, Account.class),
// Reports
ALL_DROPLET_NEIGHBORS("/reports/droplet_neighbors", "neighbors", RequestMethod.GET, Neighbors.class),
// Action
AVAILABLE_ACTIONS("/actions", "actions", RequestMethod.GET, Actions.class),
GET_ACTION_INFO("/actions/%s", "action", RequestMethod.GET, Action.class),
GET_DROPLET_ACTIONS("/droplets/%s/actions", "actions", RequestMethod.GET, Actions.class),
GET_IMAGE_ACTIONS("/images/%s/actions", "actions", RequestMethod.GET, Actions.class),
GET_FLOATING_IP_ACTIONS("/floating_ips/%s/actions", "actions", RequestMethod.GET, Actions.class),
GET_FLOATING_IP_ACTION_INFO("/floating_ips/%s/actions/%s", "action", RequestMethod.GET, Action.class),
// Image
AVAILABLE_IMAGES("/images", "images", RequestMethod.GET, Images.class),
GET_IMAGE_INFO("/images/%s", "image", RequestMethod.GET, Image.class),
UPDATE_IMAGE_INFO("/images/%s", "image", RequestMethod.PUT, Image.class),
DELETE_IMAGE("/images/%s", "response", RequestMethod.DELETE, Delete.class),
TRANSFER_IMAGE("/images/%s/actions", "action", RequestMethod.POST, Action.class),
CONVERT_IMAGE("/images/%s/actions", "action", RequestMethod.POST, Action.class),
// Region
AVAILABLE_REGIONS("/regions", "regions", RequestMethod.GET, Regions.class),
// Size
AVAILABLE_SIZES("/sizes", "sizes", RequestMethod.GET, Sizes.class),
// Domain
AVAILABLE_DOMAINS("/domains", "domains", RequestMethod.GET, Domains.class),
GET_DOMAIN_INFO("/domains/%s", "domain", RequestMethod.GET, Domain.class),
CREATE_DOMAIN("/domains", "domain", RequestMethod.POST, Domain.class),
DELETE_DOMAIN("/domains/%s", "response", RequestMethod.DELETE, Delete.class),
// Domain Record
GET_DOMAIN_RECORDS("/domains/%s/records", "domain_records", RequestMethod.GET, DomainRecords.class),
GET_DOMAIN_RECORD_INFO("/domains/%s/records/%s", "domain_record", RequestMethod.GET, DomainRecord.class),
CREATE_DOMAIN_RECORD("/domains/%s/records", "domain_record", RequestMethod.POST, DomainRecord.class),
UPDATE_DOMAIN_RECORD("/domains/%s/records/%s", "domain_record", RequestMethod.PUT, DomainRecord.class),
DELETE_DOMAIN_RECORD("/domains/%s/records/%s", "response", RequestMethod.DELETE, Delete.class),
// Key
AVAILABLE_KEYS("/account/keys", "ssh_keys", RequestMethod.GET, Keys.class),
GET_KEY_INFO("/account/keys/%s", "ssh_key", RequestMethod.GET, Key.class),
CREATE_KEY("/account/keys", "ssh_key", RequestMethod.POST, Key.class),
UPDATE_KEY("/account/keys/%s", "ssh_key", RequestMethod.PUT, Key.class),
DELETE_KEY("/account/keys/%s", "response", RequestMethod.DELETE, Delete.class),
// Floating IP
FLOATING_IPS("/floating_ips", "floating_ips", RequestMethod.GET, FloatingIPs.class),
CREATE_FLOATING_IP("/floating_ips", "floating_ip", RequestMethod.POST, FloatingIP.class),
GET_FLOATING_IP_INFO("/floating_ips/%s", "floating_ip", RequestMethod.GET, FloatingIP.class),
DELETE_FLOATING_IP("/floating_ips/%s", "response", RequestMethod.DELETE, Delete.class),
ASSIGN_FLOATING_IP("/floating_ips/%s/actions", "action", RequestMethod.POST, Action.class),
UNASSIGN_FLOATING_IP("/floating_ips/%s/actions", "action", RequestMethod.POST, Action.class),
// Tags
AVAILABLE_TAGS("/tags", "tags", RequestMethod.GET, Tags.class),
CREATE_TAG("/tags", "tag", RequestMethod.POST, Tag.class),
GET_TAG("/tags/%s", "tag", RequestMethod.GET, Tag.class),
UPDATE_TAG("/tags/%s", "tag", RequestMethod.PUT, Tag.class),
DELETE_TAG("/tags/%s", "response", RequestMethod.DELETE, Delete.class),
TAG_RESOURCE("/tags/%s/resources", "response", RequestMethod.POST, Response.class),
UNTAG_RESOURCE("/tags/%s/resources", "response", RequestMethod.DELETE, Response.class);
private String path;
private String elementName;
private RequestMethod method;
private Class<?> clazz;
ApiAction(String path, RequestMethod method) {
this(path, null, method);
}
ApiAction(String path, String elementName) {
this(path, elementName, RequestMethod.GET);
}
ApiAction(String path, String elementName, RequestMethod method) {
this(path, elementName, method, null);
}
ApiAction(String path, String elementName, RequestMethod method, Class<?> clazz) {
this.path = path;
this.elementName = elementName;
this.method = method;
this.clazz = clazz;
}
/**
* @return the path
*/
public String getPath() {
return path;
}
/**
* @return the elementName
*/
public String getElementName() {
return elementName;
}
/**
* @return the method
*/
public RequestMethod getMethod() {
return method;
}
/**
* @return the clazz
*/
public Class<?> getClazz() {
return clazz;
}
} |
package com.netflix.imflibrary.app;
import com.netflix.imflibrary.IMFConstraints;
import com.netflix.imflibrary.IMFErrorLogger;
import com.netflix.imflibrary.IMFErrorLoggerImpl;
import com.netflix.imflibrary.MXFOperationalPattern1A;
import com.netflix.imflibrary.RESTfulInterfaces.IMPValidator;
import com.netflix.imflibrary.RESTfulInterfaces.PayloadRecord;
import com.netflix.imflibrary.exceptions.IMFException;
import com.netflix.imflibrary.exceptions.MXFException;
import com.netflix.imflibrary.st0377.HeaderPartition;
import com.netflix.imflibrary.st0377.header.GenericPackage;
import com.netflix.imflibrary.st0377.header.Preface;
import com.netflix.imflibrary.st0377.header.SourcePackage;
import com.netflix.imflibrary.st0429_8.PackingList;
import com.netflix.imflibrary.st0429_9.AssetMap;
import com.netflix.imflibrary.st0429_9.BasicMapProfileV2MappedFileSet;
import com.netflix.imflibrary.st2067_2.Composition;
import com.netflix.imflibrary.st2067_2.IMFEssenceComponentVirtualTrack;
import com.netflix.imflibrary.utils.*;
import com.netflix.imflibrary.writerTools.CompositionPlaylistBuilder_2016;
import com.netflix.imflibrary.writerTools.IMPBuilder;
import com.netflix.imflibrary.writerTools.utils.IMFUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
import javax.annotation.Nullable;
import javax.xml.bind.JAXBException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import static com.netflix.imflibrary.RESTfulInterfaces.IMPValidator.*;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
public class PhotonIMPFixer {
private static final String CONFORMANCE_LOGGER_PREFIX = "Virtual Track Conformance";
private static final Logger logger = LoggerFactory.getLogger(PhotonIMPAnalyzer.class);
private static UUID getTrackFileId(PayloadRecord headerPartitionPayloadRecord) throws
IOException {
IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl();
UUID packageUUID = null;
if (headerPartitionPayloadRecord.getPayloadAssetType() != PayloadRecord.PayloadAssetType.EssencePartition) {
imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMP_VALIDATOR_PAYLOAD_ERROR,
IMFErrorLogger.IMFErrors.ErrorLevels.FATAL,
String.format("Payload asset type is %s, expected asset type %s", headerPartitionPayloadRecord.getPayloadAssetType(),
PayloadRecord.PayloadAssetType.EssencePartition.toString()));
return packageUUID;
}
try {
HeaderPartition headerPartition = new HeaderPartition(new ByteArrayDataProvider(headerPartitionPayloadRecord.getPayload()),
0L,
(long) headerPartitionPayloadRecord.getPayload().length,
imfErrorLogger);
/**
* Add the Top Level Package UUID to the set of TrackFileIDs, this is required to validate that the essences header partition that were passed in
* are in fact from the constituent resources of the VirtualTack
*/
MXFOperationalPattern1A.HeaderPartitionOP1A headerPartitionOP1A = MXFOperationalPattern1A.checkOperationalPattern1ACompliance(headerPartition, imfErrorLogger);
IMFConstraints.HeaderPartitionIMF headerPartitionIMF = IMFConstraints.checkIMFCompliance(headerPartitionOP1A, imfErrorLogger);
Preface preface = headerPartitionIMF.getHeaderPartitionOP1A().getHeaderPartition().getPreface();
GenericPackage genericPackage = preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage();
SourcePackage filePackage = (SourcePackage) genericPackage;
packageUUID = filePackage.getPackageMaterialNumberasUUID();
} catch (IMFException e) {
imfErrorLogger.addAllErrors(e.getErrors());
} catch (MXFException e) {
imfErrorLogger.addAllErrors(e.getErrors());
}
return packageUUID;
}
private static Map<UUID, PayloadRecord> getTrackFileIdToHeaderPartitionPayLoadMap(List<PayloadRecord>
headerPartitionPayloadRecords) throws
IOException {
IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl();
Map<UUID, PayloadRecord> trackFileIDMap = new HashMap<>();
for (PayloadRecord payloadRecord : headerPartitionPayloadRecords) {
if (payloadRecord.getPayloadAssetType() != PayloadRecord.PayloadAssetType.EssencePartition) {
imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMP_VALIDATOR_PAYLOAD_ERROR,
IMFErrorLogger.IMFErrors.ErrorLevels.FATAL,
String.format("Payload asset type is %s, expected asset type %s", payloadRecord.getPayloadAssetType(),
PayloadRecord.PayloadAssetType.EssencePartition.toString()));
continue;
}
try {
HeaderPartition headerPartition = new HeaderPartition(new ByteArrayDataProvider(payloadRecord.getPayload()),
0L,
(long) payloadRecord.getPayload().length,
imfErrorLogger);
/**
* Add the Top Level Package UUID to the set of TrackFileIDs, this is required to validate that the essences header partition that were passed in
* are in fact from the constituent resources of the VirtualTack
*/
MXFOperationalPattern1A.HeaderPartitionOP1A headerPartitionOP1A = MXFOperationalPattern1A.checkOperationalPattern1ACompliance(headerPartition, imfErrorLogger);
IMFConstraints.HeaderPartitionIMF headerPartitionIMF = IMFConstraints.checkIMFCompliance(headerPartitionOP1A, imfErrorLogger);
Preface preface = headerPartitionIMF.getHeaderPartitionOP1A().getHeaderPartition().getPreface();
GenericPackage genericPackage = preface.getContentStorage().getEssenceContainerDataList().get(0).getLinkedPackage();
SourcePackage filePackage = (SourcePackage) genericPackage;
UUID packageUUID = filePackage.getPackageMaterialNumberasUUID();
trackFileIDMap.put(packageUUID, payloadRecord);
} catch (IMFException e) {
imfErrorLogger.addAllErrors(e.getErrors());
} catch (MXFException e) {
imfErrorLogger.addAllErrors(e.getErrors());
}
}
return Collections.unmodifiableMap(trackFileIDMap);
}
private static Boolean isCompositionComplete(Composition composition, Set<UUID> trackFileIDsSet, IMFErrorLogger imfErrorLogger) throws IOException {
Boolean bComplete = true;
for (IMFEssenceComponentVirtualTrack virtualTrack : composition.getEssenceVirtualTracks()) {
for (UUID uuid : virtualTrack.getTrackResourceIds()) {
if (!trackFileIDsSet.contains(uuid)) {
imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes
.IMF_CPL_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.WARNING,
String.format("CPL resource %s is not present in the package", uuid.toString()));
bComplete &= false;
}
}
}
return bComplete;
}
@Nullable
private static PayloadRecord getHeaderPartitionPayloadRecord(ResourceByteRangeProvider resourceByteRangeProvider, IMFErrorLogger imfErrorLogger) throws IOException {
long archiveFileSize = resourceByteRangeProvider.getResourceSize();
long rangeEnd = archiveFileSize - 1;
long rangeStart = archiveFileSize - 4;
if(rangeStart < 0 ) {
return null;
}
byte[] bytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd);
PayloadRecord payloadRecord = new PayloadRecord(bytes, PayloadRecord.PayloadAssetType.EssenceFooter4Bytes, rangeStart, rangeEnd);
Long randomIndexPackSize = IMPValidator.getRandomIndexPackSize(payloadRecord);
rangeStart = archiveFileSize - randomIndexPackSize;
rangeEnd = archiveFileSize - 1;
if(rangeStart < 0 ) {
return null;
}
byte[] randomIndexPackBytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd);
PayloadRecord randomIndexPackPayload = new PayloadRecord(randomIndexPackBytes, PayloadRecord.PayloadAssetType.EssencePartition, rangeStart, rangeEnd);
List<Long> partitionByteOffsets = IMPValidator.getEssencePartitionOffsets(randomIndexPackPayload, randomIndexPackSize);
if (partitionByteOffsets.size() >= 2) {
rangeStart = partitionByteOffsets.get(0);
rangeEnd = partitionByteOffsets.get(1) - 1;
byte[] headerPartitionBytes = resourceByteRangeProvider.getByteRangeAsBytes(rangeStart, rangeEnd);
PayloadRecord headerParitionPayload = new PayloadRecord(headerPartitionBytes, PayloadRecord.PayloadAssetType.EssencePartition, rangeStart, rangeEnd);
return headerParitionPayload;
}
return null;
}
public static List<ErrorLogger.ErrorObject> analyzePackageAndWrite(File rootFile, File targetFile, String versionCPLSchema, Boolean copyTrackfile, Boolean generateHash) throws
IOException, ParserConfigurationException, SAXException, JAXBException, URISyntaxException, NoSuchAlgorithmException {
IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl();
List<PayloadRecord> headerPartitionPayloadRecords = new ArrayList<>();
BasicMapProfileV2MappedFileSet mapProfileV2MappedFileSet = new BasicMapProfileV2MappedFileSet(rootFile);
AssetMap assetMap = new AssetMap(new File(mapProfileV2MappedFileSet.getAbsoluteAssetMapURI()));
for (AssetMap.Asset packingListAsset : assetMap.getPackingListAssets()) {
PackingList packingList = new PackingList(new File(rootFile, packingListAsset.getPath().toString()));
Map<UUID, IMPBuilder.IMFTrackFileMetadata> imfTrackFileMetadataMap = new HashMap<>();
for (PackingList.Asset asset : packingList.getAssets()) {
File assetFile = new File(rootFile, assetMap.getPath(asset.getUUID()).toString());
ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(assetFile);
if (asset.getType().equals(PackingList.Asset.APPLICATION_MXF_TYPE)) {
PayloadRecord headerPartitionPayloadRecord = getHeaderPartitionPayloadRecord(resourceByteRangeProvider, new IMFErrorLoggerImpl());
headerPartitionPayloadRecords.add(headerPartitionPayloadRecord);
byte[] bytes = headerPartitionPayloadRecord.getPayload();
byte[] hash = asset.getHash();
if( generateHash) {
hash = IMFUtils.generateSHA1Hash(resourceByteRangeProvider);
}
imfTrackFileMetadataMap.put(getTrackFileId(headerPartitionPayloadRecord),
new IMPBuilder.IMFTrackFileMetadata(bytes,
hash,
CompositionPlaylistBuilder_2016.defaultHashAlgorithm,
assetFile.getName(),
resourceByteRangeProvider.getResourceSize())
);
if(copyTrackfile) {
File outputFile = new File(targetFile.toString() + File.separator + assetFile.getName());
Files.copy(assetFile.toPath(), outputFile.toPath(), REPLACE_EXISTING);
}
}
}
Map<UUID, PayloadRecord> trackFileIDToHeaderPartitionPayLoadMap =
getTrackFileIdToHeaderPartitionPayLoadMap(headerPartitionPayloadRecords);
for (PackingList.Asset asset : packingList.getAssets()) {
File assetFile = new File(rootFile, assetMap.getPath(asset.getUUID()).toString());
ResourceByteRangeProvider resourceByteRangeProvider = new FileByteRangeProvider(assetFile);
if (asset.getType().equals(PackingList.Asset.TEXT_XML_TYPE) && Composition.isCompositionPlaylist(resourceByteRangeProvider)) {
Composition composition = new Composition(resourceByteRangeProvider);
Set<UUID> trackFileIDsSet = trackFileIDToHeaderPartitionPayLoadMap.keySet();
if(versionCPLSchema.equals(""))
{
if (composition.getCoreConstraintsVersion().contains("st2067_2_2013")) {
versionCPLSchema = "2013";
}
else if (composition.getCoreConstraintsVersion().contains("st2067_2_2016")) {
versionCPLSchema = "2016";
}
else {
imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR,
IMFErrorLogger.IMFErrors.ErrorLevels.FATAL,
String.format("Input package CoreConstraintsVersion %s not supported", composition.getCoreConstraintsVersion().toString()));
}
}
if(versionCPLSchema.equals("2016"))
{
imfErrorLogger.addAllErrors(IMPBuilder.buildIMP_2016("IMP",
"Netflix",
composition.getVirtualTracks(),
composition.getEditRate(),
imfTrackFileMetadataMap,
targetFile));
}
else if(versionCPLSchema.equals("2013")) {
imfErrorLogger.addAllErrors(IMPBuilder.buildIMP_2013("IMP",
"Netflix",
composition.getVirtualTracks(),
composition.getEditRate(),
imfTrackFileMetadataMap,
targetFile));
}
else {
imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_CORE_CONSTRAINTS_ERROR,
IMFErrorLogger.IMFErrors.ErrorLevels.FATAL,
String.format("Invalid CPL schema %s for output", versionCPLSchema.equals("2013")));
}
}
}
}
return imfErrorLogger.getErrors();
}
public static List<ErrorLogger.ErrorObject> validateEssencePartition(ResourceByteRangeProvider resourceByteRangeProvider) throws IOException {
IMFErrorLogger trackFileErrorLogger = new IMFErrorLoggerImpl();
PayloadRecord headerPartitionPayload = getHeaderPartitionPayloadRecord(resourceByteRangeProvider, trackFileErrorLogger);
if(headerPartitionPayload == null) {
trackFileErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMP_VALIDATOR_PAYLOAD_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.FATAL,
String.format("Failed to get header partition"));
}
else {
List<PayloadRecord> payloadRecords = new ArrayList<>();
payloadRecords.add(headerPartitionPayload);
trackFileErrorLogger.addAllErrors(IMPValidator.validateIMFTrackFileHeaderMetadata(payloadRecords));
}
return trackFileErrorLogger.getErrors();
}
private static String usage() {
StringBuilder sb = new StringBuilder();
sb.append(String.format("Usage:%n"));
sb.append(String.format("%s input_package_directory output_package_directory [options]%n", PhotonIMPAnalyzer.class.getName()));
sb.append(String.format("options: %n"));
sb.append(String.format("-cs, --cpl-schema=VERSION CPL schema version for output IMP, supported values are 2013 or 2016%n"));
sb.append(String.format("-nc, --no-copy don't copy track files %n"));
sb.append(String.format("-nh, --no-hash No update for trackfile hash in PKL %n"));
return sb.toString();
}
public static void main(String args[]) throws
IOException, ParserConfigurationException, SAXException, JAXBException, URISyntaxException, NoSuchAlgorithmException {
if (args.length < 2) {
logger.error(usage());
System.exit(-1);
}
String inputFileName = args[0];
File inputFile = new File(inputFileName);
if (!inputFile.exists()) {
logger.error(String.format("File %s does not exist", inputFile.getAbsolutePath()));
System.exit(-1);
}
String outputFileName = args[1];
File outputFile = new File(outputFileName);
if (!outputFile.exists() && !outputFile.mkdir()) {
logger.error(String.format("Directory %s cannot be created", outputFile.getAbsolutePath()));
System.exit(-1);
}
String versionCPLSchema = "";
Boolean copyTrackFile = true;
Boolean generateHash = true;
for(int argIdx = 2; argIdx < args.length; ++argIdx)
{
String curArg = args[argIdx];
String nextArg = argIdx < args.length - 1 ? args[argIdx + 1] : "";
if(curArg.equalsIgnoreCase("--cpl-schema") || curArg.equalsIgnoreCase("-cs")) {
if(nextArg.length() == 0 || nextArg.charAt(0) == '-') {
logger.error(usage());
System.exit(-1);
}
versionCPLSchema = nextArg;
}
else if(curArg.equalsIgnoreCase("--no-copy") || curArg.equalsIgnoreCase("-nc")) {
copyTrackFile = false;
}
else if(curArg.equalsIgnoreCase("--no-hash") || curArg.equalsIgnoreCase("-nh")) {
generateHash = false;
}
else {
logger.error(usage());
System.exit(-1);
}
}
if (!inputFile.exists() || !inputFile.isDirectory()) {
logger.error(String.format("Invalid input package path"));
}
else
{
List<ErrorLogger.ErrorObject> errors = analyzePackageAndWrite(inputFile, outputFile, versionCPLSchema, copyTrackFile, generateHash);
if (errors.size() > 0) {
logger.info(String.format("IMPWriter encountered errors:"));
for (ErrorLogger.ErrorObject errorObject : errors) {
if (errorObject.getErrorLevel() != IMFErrorLogger.IMFErrors.ErrorLevels.WARNING) {
logger.error(errorObject.toString());
} else if (errorObject.getErrorLevel() == IMFErrorLogger.IMFErrors.ErrorLevels.WARNING) {
logger.warn(errorObject.toString());
}
}
} else {
logger.info(String.format("Created %s IMP successfully", outputFile.getName()));
}
}
}
} |
package com.nhn.hippo.web.service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.nhn.hippo.web.calltree.span.SpanAlign;
import com.nhn.hippo.web.calltree.span.SpanAligner2;
import com.nhn.hippo.web.dao.AgentInfoDao;
import com.nhn.hippo.web.dao.ApiMetaDataDao;
import com.nhn.hippo.web.dao.SqlMetaDataDao;
import com.nhn.hippo.web.dao.TraceDao;
import com.nhn.hippo.web.vo.RequestMetadataQuery;
import com.profiler.common.AnnotationNames;
import com.profiler.common.bo.AgentInfoBo;
import com.profiler.common.bo.AnnotationBo;
import com.profiler.common.bo.ApiMetaDataBo;
import com.profiler.common.bo.SpanBo;
import com.profiler.common.bo.SqlMetaDataBo;
import com.profiler.common.mapping.ApiMappingTable;
import com.profiler.common.mapping.ApiUtils;
import com.profiler.common.mapping.MethodMapping;
import com.profiler.common.util.OutputParameterParser;
import com.profiler.common.util.SqlParser;
@Service
public class SpanServiceImpl implements SpanService {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private TraceDao traceDao;
@Autowired
private SqlMetaDataDao sqlMetaDataDao;
@Autowired
private ApiMetaDataDao apiMetaDataDao;
@Autowired
private AgentInfoDao agentInfoDao;
private SqlParser sqlParser = new SqlParser();
private OutputParameterParser outputParameterParser = new OutputParameterParser();
@Override
public List<SpanAlign> selectSpan(String uuid) {
UUID id = UUID.fromString(uuid);
List<SpanBo> spans = traceDao.selectSpanAndAnnotation(id);
if (spans == null || spans.isEmpty()) {
return Collections.emptyList();
}
List<SpanAlign> order = order(spans);
transitionApiId(order);
transitionDynamicApiId(order);
transitionSqlId(order);
// TODO root span not found row data .
return order;
}
private void transitionAnnotation(List<SpanAlign> spans, AnnotationReplacementCallback annotationReplacementCallback) {
for (SpanAlign spanAlign : spans) {
List<AnnotationBo> annotationBoList;
if (spanAlign.isSpan()) {
annotationBoList = spanAlign.getSpanBo().getAnnotationBoList();
annotationReplacementCallback.replacement(spanAlign, annotationBoList);
} else {
annotationBoList = spanAlign.getSubSpanBo().getAnnotationBoList();
annotationReplacementCallback.replacement(spanAlign, annotationBoList);
}
}
}
private void transitionSqlId(final List<SpanAlign> spans) {
this.transitionAnnotation(spans, new AnnotationReplacementCallback() {
@Override
public void replacement(SpanAlign spanAlign, List<AnnotationBo> annotationBoList) {
AnnotationBo sqlIdAnnotation = findAnnotation(annotationBoList, AnnotationNames.SQL_ID.getCode());
if (sqlIdAnnotation == null) {
return;
}
AgentInfoBo agentInfoBo = null;
try {
agentInfoBo = findAgentInfoBoBeforeStartTime(spanAlign);
logger.info("{} Agent StartTime found:{}", agentInfoBo.getAgentId(), agentInfoBo);
} catch (AgentIdNotFoundException ex) {
AnnotationBo agentInfoNotFound = new AnnotationBo();
agentInfoNotFound.setKey(AnnotationNames.SQL.getCode());
agentInfoNotFound.setValue("SQL-ID not found. Cause:agentInfo not found. agentId:" + ex.getAgentId() + " startTime:" + ex.getStartTime());
annotationBoList.add(agentInfoNotFound);
return;
}
// TODO .
// sqlMetaDataList indentifier .
int hashCode = (Integer) sqlIdAnnotation.getValue();
List<SqlMetaDataBo> sqlMetaDataList = sqlMetaDataDao.getSqlMetaData(agentInfoBo.getAgentId(), agentInfoBo.getIdentifier(), hashCode, agentInfoBo.getTimestamp());
int size = sqlMetaDataList.size();
if (size == 0) {
AnnotationBo api = new AnnotationBo();
api.setKey(AnnotationNames.SQL.getCode());
api.setValue("SQL-ID not found hashCode:" + hashCode);
annotationBoList.add(api);
} else if (size == 1) {
AnnotationBo sqlParamAnnotationBo = findAnnotation(annotationBoList, AnnotationNames.SQL_PARAM.getCode());
final SqlMetaDataBo sqlMetaDataBo = sqlMetaDataList.get(0);
if (sqlParamAnnotationBo == null) {
AnnotationBo sqlMeta = new AnnotationBo();
sqlMeta.setKey(AnnotationNames.SQL_METADATA.getCode());
sqlMeta.setValue(sqlMetaDataBo.getSql());
annotationBoList.add(sqlMeta);
AnnotationBo checkFail = checkIdentifier (spanAlign, sqlMetaDataBo);
if (checkFail != null) {
annotationBoList.add(checkFail);
return;
}
AnnotationBo sql = new AnnotationBo();
sql.setKey(AnnotationNames.SQL.getCode());
sql.setValue(sqlMetaDataBo.getSql());
annotationBoList.add(sql);
} else {
logger.debug("sqlMetaDataBo:{}", sqlMetaDataBo);
String outputParams = (String) sqlParamAnnotationBo.getValue();
List<String> parsedOutputParams = outputParameterParser.parseOutputParameter(outputParams);
logger.debug("outputPrams:{}, parsedOutputPrams:{}", outputParams, parsedOutputParams);
String originalSql = sqlParser.combineOutputParams(sqlMetaDataBo.getSql(), parsedOutputParams);
logger.debug("outputPrams{}, originalSql:{}", outputParams, originalSql);
AnnotationBo sqlMeta = new AnnotationBo();
sqlMeta.setKey(AnnotationNames.SQL_METADATA.getCode());
sqlMeta.setValue(sqlMetaDataBo.getSql());
annotationBoList.add(sqlMeta);
AnnotationBo checkFail = checkIdentifier (spanAlign, sqlMetaDataBo);
if (checkFail != null) {
annotationBoList.add(checkFail);
return;
}
AnnotationBo sql = new AnnotationBo();
sql.setKey(AnnotationNames.SQL.getCode());
sql.setValue(originalSql);
annotationBoList.add(sql);
}
} else {
// TODO .
AnnotationBo api = new AnnotationBo();
api.setKey(AnnotationNames.SQL.getCode());
api.setValue(collisionSqlHashCodeMessage(hashCode, sqlMetaDataList));
annotationBoList.add(api);
}
}
private AnnotationBo checkIdentifier(SpanAlign spanAlign, SqlMetaDataBo sqlMetaDataBo) {
short agentIdentifier = getAgentIdentifier(spanAlign);
short sqlIdentifier = sqlMetaDataBo.getIdentifier();
if (agentIdentifier == sqlIdentifier) {
return null;
}
AnnotationBo identifierCheckFail = new AnnotationBo();
identifierCheckFail.setKey(AnnotationNames.SQL.getCode());
identifierCheckFail.setValue("invalid SqlMetaInfo:" + sqlMetaDataBo);
return identifierCheckFail;
}
});
}
private AnnotationBo findAnnotation(List<AnnotationBo> annotationBoList, int key) {
for (AnnotationBo annotationBo : annotationBoList) {
if (key == annotationBo.getKey()) {
return annotationBo;
}
}
return null;
}
private String collisionSqlHashCodeMessage(int hashCode, List<SqlMetaDataBo> sqlMetaDataList) {
// TODO . hashCode .
StringBuilder sb = new StringBuilder(64);
sb.append("Collision Sql hashCode:");
sb.append(hashCode);
sb.append('\n');
for (int i = 0; i < sqlMetaDataList.size(); i++) {
if (i != 0) {
sb.append("or\n");
}
SqlMetaDataBo sqlMetaDataBo = sqlMetaDataList.get(i);
sb.append(sqlMetaDataBo.getSql());
}
return sb.toString();
}
private String getAgentId(SpanAlign spanAlign) {
if (spanAlign.isSpan()) {
return spanAlign.getSpanBo().getAgentId();
} else {
return spanAlign.getSubSpanBo().getAgentId();
}
}
private short getAgentIdentifier(SpanAlign spanAlign) {
if (spanAlign.isSpan()) {
return spanAlign.getSpanBo().getAgentIdentifier();
} else {
return spanAlign.getSubSpanBo().getAgentIdentifier();
}
}
private void transitionDynamicApiId(List<SpanAlign> spans) {
this.transitionAnnotation(spans, new AnnotationReplacementCallback() {
@Override
public void replacement(SpanAlign spanAlign, List<AnnotationBo> annotationBoList) {
AnnotationBo apiIdAnnotation = findAnnotation(annotationBoList, AnnotationNames.API_DID.getCode());
if (apiIdAnnotation == null) {
return;
}
AgentInfoBo agentInfoBo = null;
try {
agentInfoBo = findAgentInfoBoBeforeStartTime(spanAlign);
logger.info("{} Agent StartTime found:{}", agentInfoBo.getAgentId(), agentInfoBo);
} catch (AgentIdNotFoundException ex) {
AnnotationBo agentInfoNotFound = new AnnotationBo();
agentInfoNotFound.setKey(AnnotationNames.API.getCode());
agentInfoNotFound.setValue("API-DynamicID not found. Cause:agentInfo not found. agentId:" + ex.getAgentId() + " startTime:" + ex.getStartTime());
annotationBoList.add(agentInfoNotFound);
return;
}
int apiId = (Integer) apiIdAnnotation.getValue();
List<ApiMetaDataBo> apiMetaDataList = apiMetaDataDao.getApiMetaData(agentInfoBo.getAgentId(), agentInfoBo.getIdentifier(), apiId, agentInfoBo.getTimestamp());
int size = apiMetaDataList.size();
if (size == 0) {
AnnotationBo api = new AnnotationBo();
api.setKey(AnnotationNames.API.getCode());
api.setValue("API-DID not found. api:" + apiId);
annotationBoList.add(api);
} else if (size == 1) {
ApiMetaDataBo apiMetaDataBo = apiMetaDataList.get(0);
AnnotationBo apiMetaData = new AnnotationBo();
apiMetaData.setKey(AnnotationNames.API_METADATA.getCode());
apiMetaData.setValue(apiMetaDataBo);
annotationBoList.add(apiMetaData);
AnnotationBo checkFail = checkIdentifier (spanAlign, apiMetaDataBo);
if (checkFail != null) {
annotationBoList.add(checkFail);
return;
}
AnnotationBo apiAnnotation = new AnnotationBo();
apiAnnotation.setKey(AnnotationNames.API.getCode());
String apiInfo = getApiInfo(apiMetaDataBo);
apiAnnotation.setValue(apiInfo);
annotationBoList.add(apiAnnotation);
} else {
AnnotationBo apiAnnotation = new AnnotationBo();
apiAnnotation.setKey(AnnotationNames.API.getCode());
String collisonMessage = collisionApiDidMessage(apiId, apiMetaDataList);
apiAnnotation.setValue(collisonMessage);
annotationBoList.add(apiAnnotation);
}
}
private AnnotationBo checkIdentifier(SpanAlign spanAlign, ApiMetaDataBo apiMetaDataBo) {
short agentIdentifier = getAgentIdentifier(spanAlign);
short sqlIdentifier = apiMetaDataBo.getIdentifier();
if (agentIdentifier == sqlIdentifier) {
return null;
}
AnnotationBo identifierCheckFail = new AnnotationBo();
identifierCheckFail.setKey(AnnotationNames.API.getCode());
identifierCheckFail.setValue("invalid ApiMetaInfo:" + apiMetaDataBo);
return identifierCheckFail;
}
});
}
private AgentInfoBo findAgentInfoBoBeforeStartTime(SpanAlign spanAlign) {
String agentId = getAgentId(spanAlign);
long startTime = spanAlign.getSpanBo().getStartTime();
AgentInfoBo agentInfoBeforeStartTime = agentInfoDao.findAgentInfoBeforeStartTime(agentId, startTime);
if (agentInfoBeforeStartTime == null) {
throw new AgentIdNotFoundException(agentId, startTime);
}
return agentInfoBeforeStartTime;
}
private String collisionApiDidMessage(int apidId, List<ApiMetaDataBo> apiMetaDataList) {
// TODO . hashCode .
StringBuilder sb = new StringBuilder(64);
sb.append("Collision Api DynamicId:");
sb.append(apidId);
sb.append('\n');
for (int i = 0; i < apiMetaDataList.size(); i++) {
if (i != 0) {
sb.append("or\n");
}
ApiMetaDataBo apiMetaDataBo = apiMetaDataList.get(i);
sb.append(getApiInfo(apiMetaDataBo));
}
return sb.toString();
}
private String getApiInfo(ApiMetaDataBo apiMetaDataBo) {
if (apiMetaDataBo.getLineNumber() != -1) {
return apiMetaDataBo.getApiInfo() + ":" + apiMetaDataBo.getLineNumber();
} else {
return apiMetaDataBo.getApiInfo();
}
}
private void transitionApiId(List<SpanAlign> spans) {
this.transitionAnnotation(spans, new AnnotationReplacementCallback() {
@Override
public void replacement(SpanAlign spanAlign, List<AnnotationBo> annotationBoList) {
AnnotationBo apiIdAnnotation = findAnnotation(annotationBoList, AnnotationNames.API_ID.getCode());
if (apiIdAnnotation == null) {
return;
}
MethodMapping methodMapping = ApiMappingTable.findMethodMapping((Integer) apiIdAnnotation.getValue());
if (methodMapping == null) {
return;
}
String className = methodMapping.getClassMapping().getClassName();
String methodName = methodMapping.getMethodName();
String[] parameterType = methodMapping.getParameterType();
String[] parameterName = methodMapping.getParameterName();
String args = ApiUtils.mergeParameterVariableNameDescription(parameterType, parameterName);
AnnotationBo api = new AnnotationBo();
api.setKey(AnnotationNames.API.getCode());
api.setValue(className + "." + methodName + args);
annotationBoList.add(api);
}
});
}
public static interface AnnotationReplacementCallback {
void replacement(SpanAlign spanAlign, List<AnnotationBo> annotationBoList);
}
private List<SpanAlign> order(List<SpanBo> spans) {
SpanAligner2 spanAligner = new SpanAligner2(spans);
return spanAligner.sort();
/*
* SpanAligner spanAligner = new SpanAligner(spans); List<SpanAlign> sort = spanAligner.sort(); if (sort.size() != spans.size()) { // TODO ? ? logger.warn("span node not complete! spans:{}, sort{}", spans, sort); } SpanPopulator spanPopulator = new SpanPopulator(sort); List<SpanAlign> populatedList = spanPopulator.populateSubSpan(); return populatedList;
*/
}
@Override
public List<SpanBo> selectRequestMetadata(RequestMetadataQuery query) {
List<List<SpanBo>> selectedSpans = traceDao.selectSpans(query.getTraceIds());
List<SpanBo> result = new ArrayList<SpanBo>(query.size());
// UUID, starttime, responseTime .
for (List<SpanBo> spans : selectedSpans) {
for (SpanBo span : spans) {
// check UUID and time
if (query.isExists(span.getMostTraceId(), span.getLeastTraceId(), span.getStartTime(), span.getElapsed())) {
result.add(span);
}
}
}
// TODO ...
Collections.sort(result, new Comparator<SpanBo>() {
@Override
public int compare(SpanBo o1, SpanBo o2) {
if (o1.getException() != 0 && o2.getException() != 0) {
return o2.getElapsed() - o1.getElapsed();
} else if (o1.getException() != 0) {
return 1;
} else if (o2.getException() != 0) {
return -1;
} else {
return o2.getElapsed() - o1.getElapsed();
}
}
});
return result;
}
} |
package com.ociweb.pronghorn.iot.i2c;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ociweb.iot.hardware.HardwareImpl;
import com.ociweb.iot.hardware.I2CConnection;
import com.ociweb.pronghorn.iot.AbstractTrafficOrderedStage;
import com.ociweb.pronghorn.iot.schema.I2CCommandSchema;
import com.ociweb.pronghorn.iot.schema.I2CResponseSchema;
import com.ociweb.pronghorn.iot.schema.TrafficAckSchema;
import com.ociweb.pronghorn.iot.schema.TrafficReleaseSchema;
import com.ociweb.pronghorn.pipe.Pipe;
import com.ociweb.pronghorn.pipe.PipeReader;
import com.ociweb.pronghorn.pipe.PipeWriter;
import com.ociweb.pronghorn.stage.scheduling.GraphManager;
import com.ociweb.pronghorn.stage.scheduling.ThreadPerStageScheduler;
import com.ociweb.pronghorn.util.Appendables;
import com.ociweb.pronghorn.util.math.ScriptedSchedule;
public class I2CJFFIStage extends AbstractTrafficOrderedStage {
private final I2CBacking i2c;
private final Pipe<I2CCommandSchema>[] fromCommandChannels;
private final Pipe<I2CResponseSchema> i2cResponsePipe;
private static final Logger logger = LoggerFactory.getLogger(I2CJFFIStage.class);
private ScriptedSchedule schedule;
private I2CConnection[] inputs = null;
private byte[] workingBuffer;
private int inProgressIdx = 0;
private int scheduleIdx = 0;
private long blockStartTime = 0;
private boolean awaitingResponse = false;
private static final int MAX_ADDR = 127;
private final boolean processInputs;
private Number rate;
private long timeOut = 0;
private final int writeTime = 10; //it often takes 1 full ms just to contact the linux driver so this value must be a minimum of 3ms.
//NOTE: on the pi without any RATE value this stage is run every .057 ms, this is how long 1 run takes to complete for the clock., 2 analog sensors.
public static final AtomicBoolean instanceCreated = new AtomicBoolean(false);
public I2CJFFIStage(GraphManager graphManager, Pipe<TrafficReleaseSchema>[] goPipe,
Pipe<I2CCommandSchema>[] i2cPayloadPipes,
Pipe<TrafficAckSchema>[] ackPipe,
Pipe<I2CResponseSchema> i2cResponsePipe,
HardwareImpl hardware) {
super(graphManager, hardware, i2cPayloadPipes, goPipe, ackPipe, i2cResponsePipe);
assert(!instanceCreated.getAndSet(true)) : "Only one i2c manager can be running at a time";
this.i2c = hardware.i2cBacking;
this.fromCommandChannels = i2cPayloadPipes;
this.i2cResponsePipe = i2cResponsePipe;
//force all commands to happen upon publish and release
this.supportsBatchedPublish = false;
this.supportsBatchedRelease = false;
this.inputs = hardware.getI2CInputs();
if (this.hardware.hasI2CInputs()) {
this.schedule = this.hardware.buildI2CPollSchedule();
} else {
logger.debug("skipped buildI2CPollSchedule has no i2c inputs" );
}
if (null!=this.schedule) {
//The fastest message that can ever be sent on I2C 100K is once every 1.6MS
int divisor = 20; //TODO: review this later by checking less often the CPU usage should go down.
assert(0==(this.schedule.commonClock%divisor)) : "must be divisible by "+divisor;
GraphManager.addNota(graphManager, GraphManager.SCHEDULE_RATE, (this.schedule.commonClock)/divisor , this);
logger.debug("setting JFFI to pol every: {} with schedule {}",((this.schedule.commonClock)/divisor),this.schedule);
}else{
logger.debug("Schedule is null");
}
rate = (Number)graphManager.getNota(graphManager, this.stageId, GraphManager.SCHEDULE_RATE, null);
processInputs = hardware.hasI2CInputs() && hasListeners();
}
@Override
public void startup(){
super.startup();
workingBuffer = new byte[2048];
logger.debug("Polling "+this.inputs.length+" i2cInput(s)");
for (int i = 0; i < inputs.length; i++) {
timeOut = hardware.currentTimeMillis() + writeTime;
while(!i2c.write(inputs[i].address, inputs[i].setup, inputs[i].setup.length) && hardware.currentTimeMillis()<timeOut){};
logger.debug("I2C setup {} complete",inputs[i].address);
}
if (null!=schedule) {
logger.debug("proposed schedule: {} ",schedule);
}
blockStartTime = hardware.nanoTime();//critical Pronghorn contract ensure this start is called by the same thread as run
if (!hasListeners()) {
logger.debug("No listeners are attached to I2C");
}
}
@Override
public void run() {
long prcRelease = hardware.nanoTime();
//never run poll if we have nothing to poll, in that case the array will have a single -1
if (processInputs) {
do {
long waitTime = blockStartTime - hardware.nanoTime();
//logger.info("wait time before continue {},",waitTime);
if(waitTime>0){
if (null==rate || (waitTime > rate.longValue())) {
if (hardware.nanoTime()>prcRelease) {
processReleasedCommands(waitTime);
}
return; //Enough time has not elapsed to start next block on schedule
} else {
long blockMS = (hardware.nanoTime()-blockStartTime) / 1_000_000;
if (blockMS > 1) {
try {
Thread.sleep(blockMS - 1);
} catch (InterruptedException e) {
requestShutdown();
return;
}//leave ourselves 1 MS
}
while (hardware.nanoTime()<blockStartTime){
Thread.yield();
}
}
}
do{
inProgressIdx = schedule.script[scheduleIdx];
if(inProgressIdx != -1) {
if (!PipeWriter.hasRoomForWrite(i2cResponsePipe)) {
if (hardware.nanoTime()>prcRelease) {
//we are going to miss the schedule due to backup in the pipes, this is common when the unit tests run or the user has put in a break point.
processReleasedCommands(rate.longValue());//if this backup runs long term we never release the commands so we must do it now.
}
logger.warn("outgoing pipe is backed up, unable to read new data {}"+i2cResponsePipe);
return;//oops the pipe is full so we can not read, postpone this work until the pipe is cleared.
}
I2CConnection connection = this.inputs[inProgressIdx];
timeOut = hardware.nanoTime() + (writeTime*1_000_000);
//logger.info("i2c request read "+Arrays.toString(Arrays.copyOfRange(connection.readCmd, 0, connection.readCmd.length)));
//Write the request to read
while(!i2c.write((byte)connection.address, connection.readCmd, connection.readCmd.length) && hardware.nanoTime()<timeOut){}
if (hardware.nanoTime()>timeOut) {
logger.warn("failed to get I2C bus master");
//timeout trying to get the i2c bus
return;
}
long now = System.nanoTime();
long limit = now + this.inputs[inProgressIdx].delayAfterRequestNS;
while(System.nanoTime() < limit) {
//do nothing in here, this is very short and we must get off the bus as fast as possible.
}
workingBuffer[0] = -2;
byte[] temp =i2c.read(this.inputs[inProgressIdx].address, workingBuffer, this.inputs[inProgressIdx].readBytes);
//logger.info("i2c reading result {} delay before read {} ",Arrays.toString(Arrays.copyOfRange(temp, 0, this.inputs[inProgressIdx].readBytes )),this.inputs[inProgressIdx].delayAfterRequestNS);
PipeWriter.tryWriteFragment(i2cResponsePipe, I2CResponseSchema.MSG_RESPONSE_10);
PipeWriter.writeInt(i2cResponsePipe, I2CResponseSchema.MSG_RESPONSE_10_FIELD_ADDRESS_11, this.inputs[inProgressIdx].address);
PipeWriter.writeLong(i2cResponsePipe, I2CResponseSchema.MSG_RESPONSE_10_FIELD_TIME_13, hardware.currentTimeMillis());
PipeWriter.writeInt(i2cResponsePipe, I2CResponseSchema.MSG_RESPONSE_10_FIELD_REGISTER_14, this.inputs[inProgressIdx].register);
PipeWriter.writeBytes(i2cResponsePipe, I2CResponseSchema.MSG_RESPONSE_10_FIELD_BYTEARRAY_12, temp, 0, this.inputs[inProgressIdx].readBytes, Integer.MAX_VALUE);
PipeWriter.publishWrites(i2cResponsePipe);
} else {
if (rate.longValue()>500_000) {
if (hardware.nanoTime()>prcRelease) {
processReleasedCommands(rate.longValue());
prcRelease+=rate.longValue();
}
}
}
//since we exit early if the pipe is full we must not move this forward until now at the bottom of the loop.
scheduleIdx = (scheduleIdx+1) % schedule.script.length;
}while(inProgressIdx != -1);
blockStartTime += schedule.commonClock;
} while (true);
} else {
//System.err.println("nothing to poll, should choose a simpler design");
if (hardware.nanoTime()>prcRelease) {
processReleasedCommands(rate.longValue());
prcRelease+=rate.longValue();
}
}
}
private boolean hasListeners() {
return i2cResponsePipe != null;
}
protected void processMessagesForPipe(int a) {
sendOutgoingCommands(a);
}
private void sendOutgoingCommands(int activePipe) {
if(activePipe == -1){
return; //No active pipe selected yet
}
Pipe<I2CCommandSchema> pipe = fromCommandChannels[activePipe];
// logger.info("i2c while: {} {} {} {} {} {}",
// activePipe,
// hasReleaseCountRemaining(activePipe),
// isChannelUnBlocked(activePipe),
// isConnectionUnBlocked(PipeReader.peekInt(pipe, 1)),
// PipeReader.hasContentToRead(pipe),
// pipe
while ( hasReleaseCountRemaining(activePipe)
&& isChannelUnBlocked(activePipe)
&& PipeReader.hasContentToRead(pipe)
&& isConnectionUnBlocked(PipeReader.peekInt(pipe, 1)) //peek next connection and check that it is not blocking for some time
&& PipeReader.tryReadFragment(pipe)){
int msgIdx = PipeReader.getMsgIdx(pipe);
switch(msgIdx){
case I2CCommandSchema.MSG_COMMAND_7:
{
int connection = PipeReader.readInt(pipe, I2CCommandSchema.MSG_COMMAND_7_FIELD_CONNECTOR_11);
assert isConnectionUnBlocked(connection): "expected command to not be blocked";
int addr = PipeReader.readInt(pipe, I2CCommandSchema.MSG_COMMAND_7_FIELD_ADDRESS_12);
byte[] backing = PipeReader.readBytesBackingArray(pipe, I2CCommandSchema.MSG_COMMAND_7_FIELD_BYTEARRAY_2);
int len = PipeReader.readBytesLength(pipe, I2CCommandSchema.MSG_COMMAND_7_FIELD_BYTEARRAY_2);
int pos = PipeReader.readBytesPosition(pipe, I2CCommandSchema.MSG_COMMAND_7_FIELD_BYTEARRAY_2);
int mask = PipeReader.readBytesMask(pipe, I2CCommandSchema.MSG_COMMAND_7_FIELD_BYTEARRAY_2);
Pipe.copyBytesFromToRing(backing, pos, mask, workingBuffer, 0, Integer.MAX_VALUE, len);
try {
if (logger.isDebugEnabled()) {
logger.debug("{} send command {} {}", activePipe, Appendables.appendArray(new StringBuilder(), '[', backing, pos, mask, ']', len), pipe);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
timeOut = hardware.currentTimeMillis() + writeTime;
while(!i2c.write((byte) addr, workingBuffer, len) && hardware.currentTimeMillis()<timeOut){}
}
break;
case I2CCommandSchema.MSG_BLOCKCHANNEL_22:
{
blockChannelDuration(activePipe,PipeReader.readLong(pipe, I2CCommandSchema.MSG_BLOCKCHANNEL_22_FIELD_DURATIONNANOS_13));
if (logger.isDebugEnabled()) {
logger.debug("CommandChannel blocked for {} millis ",PipeReader.readLong(pipe, I2CCommandSchema.MSG_BLOCKCHANNEL_22_FIELD_DURATIONNANOS_13));
}
}
break;
case I2CCommandSchema.MSG_BLOCKCONNECTION_20:
{
int connection = PipeReader.readInt(pipe, I2CCommandSchema.MSG_BLOCKCONNECTION_20_FIELD_CONNECTOR_11);
assert isConnectionUnBlocked(connection): "expected command to not be blocked";
int addr = PipeReader.readInt(pipe, I2CCommandSchema.MSG_BLOCKCONNECTION_20_FIELD_ADDRESS_12);
long duration = PipeReader.readLong(pipe, I2CCommandSchema.MSG_BLOCKCONNECTION_20_FIELD_DURATIONNANOS_13);
blockConnectionDuration(connection, duration);
if (logger.isDebugEnabled()) {
logger.debug("I2C addr {} {} blocked for {} nanos {}", addr, connection, duration, pipe);
}
}
break;
case I2CCommandSchema.MSG_BLOCKCONNECTIONUNTIL_21:
{
int connection = PipeReader.readInt(pipe, I2CCommandSchema.MSG_BLOCKCONNECTIONUNTIL_21_FIELD_CONNECTOR_11);
int addr = PipeReader.readInt(pipe, I2CCommandSchema.MSG_BLOCKCONNECTIONUNTIL_21_FIELD_ADDRESS_12);
long time = PipeReader.readLong(pipe, I2CCommandSchema.MSG_BLOCKCONNECTIONUNTIL_21_FIELD_TIMEMS_14);
blockConnectionUntil(connection, time);
if (logger.isDebugEnabled()) {
logger.debug("I2C addr {} {} blocked until {} millis {}", addr, connection, time, pipe);
}
}
break;
case -1 :
requestShutdown();
}
PipeReader.releaseReadLock(pipe);
//only do now after we know its not blocked and was completed
decReleaseCount(activePipe);
}
}
} |
package com.oneliang.util.task;
import com.oneliang.Constant;
import com.oneliang.util.concurrent.ThreadTask;
import com.oneliang.util.logging.Logger;
import com.oneliang.util.logging.LoggerManager;
public class TaskNodeThreadTask implements ThreadTask {
private static final Logger logger=LoggerManager.getLogger(TaskNodeThreadTask.class);
private TaskEngine taskEngine=null;
private TaskNode taskNode=null;
public TaskNodeThreadTask(TaskEngine taskEngine,TaskNode taskNode) {
this.taskEngine=taskEngine;
this.taskNode=taskNode;
}
public void runTask() {
long begin=System.currentTimeMillis();
logger.info(taskNode.getName()+" ready");
while(!taskNode.isAllParentFinished()){
synchronized(taskNode){
try {
taskNode.wait();
} catch (InterruptedException e) {
logger.error(Constant.Base.EXCEPTION, e);
}
}
}
long runBegin=System.currentTimeMillis();
try{
if(taskNode.getRunnable()!=null){
logger.info(taskNode.getName()+" start");
taskNode.getRunnable().run();
}
}catch(Exception e){
logger.error(Constant.Base.EXCEPTION, e);
taskEngine.setSuccessful(false);
}finally{
taskNode.setFinished(true);
}
long runCost=System.currentTimeMillis()-runBegin;
if(taskNode.getChildTaskNodeList()!=null&&!taskNode.getChildTaskNodeList().isEmpty()){
for(TaskNode childTaskNode:taskNode.getChildTaskNodeList()){
// taskEngine.executeTaskNode(childTaskNode);
synchronized(childTaskNode){
childTaskNode.notify();
}
}
}
long taskCost=System.currentTimeMillis()-begin;
logger.info(taskNode.getName()+" end,task cost:"+taskCost+",run cost:"+runCost+",waiting:"+(taskCost-runCost));
this.taskNode.setRunCostTime(runCost);
if(this.taskEngine.isDefaultMode()){
if(this.taskEngine.isAllTaskNodeFinished()){
synchronized (this.taskEngine) {
this.taskEngine.notify();
}
}
}
}
} |
package com.palantir.semver;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PrefixSemanticVersion implements SemanticVersion {
private static final String SEMANTIC_VERSION_REGEX = createSemanticVersionRegex();
private static final SemanticVersionComparator COMPARATOR = new SemanticVersionComparator();
private static String createSemanticVersionRegex() {
String majorMinorPatchPattern = "v?(\\d+)(\\.(\\d+))(\\.(\\d+))";
String releaseCandidatePattern = "(-(([0-9A-Za-z-]+)(\\.[0-9A-Za-z-]+)*))?";
String buildPattern = "(\\+(([0-9A-Za-z-]+)(\\.[0-9A-Za-z-]+)*))?";
return majorMinorPatchPattern + releaseCandidatePattern + buildPattern;
}
private final String originalVersion;
private final int major;
private final int minor;
private final int patch;
// This can be null
private final String releaseCandidate;
// This can be null
private final String metadata;
/**
* This constructor is package private for the purposes of testing
*
* @param version
*
* @param releaseCandidate is nullable
* @param metadata is nullable
*/
PrefixSemanticVersion(String originalVersion,
int major,
int minor,
int patch,
String releaseCandidate,
String metadata) {
this.originalVersion = originalVersion;
this.major = checkNonNegativeVersion(major);
this.minor = checkNonNegativeVersion(minor);
this.patch = checkNonNegativeVersion(patch);
this.releaseCandidate = releaseCandidate;
this.metadata = metadata;
}
public static SemanticVersion createFromString(String prefix, String version) {
String prefixPatternString = "^" + prefix + "-?" + SEMANTIC_VERSION_REGEX + "$";
Pattern prefixPattern = Pattern.compile(prefixPatternString);
Matcher matcher = prefixPattern.matcher(version);
checkArgument(matcher.matches(), "Version string " + version
+ " is not a semantic version");
int major = Integer.parseInt(matcher.group(1));
int minor = Integer.parseInt(matcher.group(3));
int patch = Integer.parseInt(matcher.group(5));
String releaseCandidate = matcher.group(7);
String build = matcher.group(11);
return new PrefixSemanticVersion(
version,
major,
minor,
patch,
releaseCandidate,
build);
}
private static int checkNonNegativeVersion(int version) {
checkArgument(
version >= 0,
"major, minor, and patch versions cannot be negative");
return version;
}
public static boolean isValid(String prefix, String version) {
String prefixPatternString = "^" + prefix + "-?" + SEMANTIC_VERSION_REGEX + "$";
Pattern prefixPattern = Pattern.compile(prefixPatternString);
return prefixPattern.matcher(version).matches();
}
@Override
public String getOriginalVersion() {
return originalVersion;
}
@Override
public int getMajorVersion() {
return major;
}
@Override
public int getMinorVersion() {
return minor;
}
@Override
public int getPatchVersion() {
return patch;
}
@Override
public String getReleaseCandidate() {
return releaseCandidate;
}
@Override
public String getMetadata() {
return metadata;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((metadata == null) ? 0 : metadata.hashCode());
result = prime * result + major;
result = prime * result + minor;
result = prime * result + patch;
result = prime
* result
+ ((releaseCandidate == null) ? 0 : releaseCandidate.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SemanticVersion other = (SemanticVersion) obj;
if (metadata == null) {
if (other.getMetadata() != null)
return false;
} else if (!metadata.equals(other.getMetadata()))
return false;
if (this.major != other.getMajorVersion())
return false;
if (minor != other.getMinorVersion())
return false;
if (patch != other.getPatchVersion())
return false;
if (releaseCandidate == null) {
if (other.getReleaseCandidate() != null)
return false;
} else if (!releaseCandidate.equals(other.getReleaseCandidate()))
return false;
return true;
}
@Override
public String toString() {
return "SemanticVersion [major=" + major + ", minor=" + minor
+ ", patch=" + patch + ", releaseCandidate=" + releaseCandidate
+ ", build=" + metadata + "]";
}
/**
* Implementation of the semver.org 2.0.0-rc.2 comparison rules
*/
@Override
public int compareTo(SemanticVersion other) {
return COMPARATOR.compare(this, other);
}
private static void checkArgument(boolean condition, String errorMessage) {
if (!condition) {
throw new IllegalArgumentException(errorMessage);
}
}
} |
package org.gemoc.executionframework.extensions.sirius.modelloader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.transaction.RecordingCommand;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditorWithFlyOutPalette;
import org.eclipse.sirius.business.api.session.Session;
import org.eclipse.sirius.business.api.session.SessionManager;
import org.eclipse.sirius.business.internal.session.SessionTransientAttachment;
import org.eclipse.sirius.common.tools.api.resource.ResourceSetFactory;
import org.eclipse.sirius.diagram.DDiagram;
import org.eclipse.sirius.diagram.DSemanticDiagram;
import org.eclipse.sirius.diagram.description.Layer;
import org.eclipse.sirius.diagram.tools.api.command.ChangeLayerActivationCommand;
import org.eclipse.sirius.diagram.ui.business.internal.command.RefreshDiagramOnOpeningCommand;
import org.eclipse.sirius.diagram.ui.tools.api.editor.DDiagramEditor;
import org.eclipse.sirius.diagram.ui.tools.api.graphical.edit.palette.ToolFilter;
import org.eclipse.sirius.ui.business.api.dialect.DialectEditor;
import org.eclipse.sirius.ui.business.api.dialect.DialectUIManager;
import org.eclipse.sirius.ui.business.api.session.IEditingSession;
import org.eclipse.sirius.ui.business.api.session.SessionUIManager;
import org.eclipse.sirius.viewpoint.DRepresentation;
import org.eclipse.sirius.viewpoint.DView;
import org.eclipse.sirius.viewpoint.description.tool.AbstractToolDescription;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PlatformUI;
import org.eclipse.xtext.resource.XtextPlatformResourceURIHandler;
import org.eclipse.xtext.util.StringInputStream;
import org.gemoc.commons.eclipse.emf.EMFResource;
import org.gemoc.executionframework.engine.core.CommandExecution;
import org.gemoc.executionframework.extensions.sirius.Activator;
import org.gemoc.executionframework.extensions.sirius.debug.DebugSessionFactory;
import org.gemoc.executionframework.extensions.sirius.services.AbstractGemocAnimatorServices;
import org.gemoc.xdsmlframework.api.core.IExecutionContext;
import org.gemoc.xdsmlframework.api.core.IModelLoader;
import fr.inria.diverse.melange.adapters.EObjectAdapter;
import fr.inria.diverse.melange.resource.MelangeRegistry;
import fr.inria.diverse.melange.resource.MelangeResourceImpl;
import fr.obeo.dsl.debug.ide.sirius.ui.services.AbstractDSLDebuggerServices;
public class DefaultModelLoader implements IModelLoader {
//public final static String MODEL_ID = Activator.PLUGIN_ID + ".debugModel";
public Resource loadModel(IExecutionContext context)
throws RuntimeException {
Resource resource = null;
ResourceSet resourceSet;
resourceSet = new ResourceSetImpl();
resource = resourceSet.createResource(context.getRunConfiguration()
.getExecutedModelURI());
try {
resource.load(null);
} catch (IOException e) {
new RuntimeException(e);
}
return resource;
}
public Resource loadModelForAnimation(IExecutionContext context)
throws RuntimeException {
Resource resource = null;
ResourceSet resourceSet;
if (context.getRunConfiguration().getAnimatorURI() != null) {
killPreviousSiriusSession(context.getRunConfiguration()
.getAnimatorURI());
Session session;
try {
session = openNewSiriusSession(context, context
.getRunConfiguration().getAnimatorURI());
resourceSet = session.getTransactionalEditingDomain()
.getResourceSet();
} catch (CoreException e) {
throw new RuntimeException(e);
}
// At this point Sirius has loaded the model, so we just need to find it
boolean useMelange = context.getRunConfiguration().getMelangeQuery() != null
&& !context.getRunConfiguration().getMelangeQuery().isEmpty();
// calculating model URI as MelangeURI
URI modelURI = useMelange ? context.getRunConfiguration()
.getExecutedModelAsMelangeURI() : context.getRunConfiguration()
.getExecutedModelURI();
for (Resource r : resourceSet.getResources()) {
if (r.getURI().equals(modelURI)) {
resource = r;
break;
}
}
return resource;
} else {
// animator not available; fall back to classic load
return loadModel(context);
}
}
private void killPreviousSiriusSession(URI sessionResourceURI) {
final Session session = SessionManager.INSTANCE
.getExistingSession(sessionResourceURI);
if (session != null) {
final IEditingSession uiSession = SessionUIManager.INSTANCE
.getUISession(session);
DebugPermissionProvider permProvider = new DebugPermissionProvider();
if (!permProvider.provides(session.getTransactionalEditingDomain()
.getResourceSet())) {
// this is a not debugSession (ie. a normal editing session)
if (uiSession != null) {
for (final DialectEditor editor : uiSession.getEditors()) {
final IEditorSite editorSite = editor.getEditorSite();
if (editor.getSite() == null) {
editorSite.getShell().getDisplay()
.syncExec(new Runnable() {
@Override
public void run() {
editorSite.getPage().closeEditor(
editor, true);
}
});
}
}
PlatformUI.getWorkbench().getDisplay()
.syncExec(new Runnable() {
@Override
public void run() {
uiSession.close();
}
});
}
}
PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
@Override
public void run() {
session.close(new NullProgressMonitor());
SessionManager.INSTANCE.remove(session);
}
});
}
}
private Session openNewSiriusSession(final IExecutionContext context,
URI sessionResourceURI) throws CoreException {
SubMonitor subMonitor = SubMonitor.convert(this.progressMonitor, 10);
boolean useMelange = context.getRunConfiguration().getMelangeQuery() != null
&& !context.getRunConfiguration().getMelangeQuery().isEmpty();
if( useMelange){
subMonitor.setTaskName("Loading model for animation with melange");
} else {
subMonitor.setTaskName("Loading model for animation");
}
// calculating model URI as MelangeURI
URI modelURI = useMelange ? context.getRunConfiguration()
.getExecutedModelAsMelangeURI() : context.getRunConfiguration()
.getExecutedModelURI();
subMonitor.subTask("Configuring ResourceSet");
subMonitor.newChild(1);
// create and configure resource set
HashMap<String, String> nsURIMapping = getnsURIMapping(context);
//final ResourceSet rs = createAndConfigureResourceSet(modelURI, nsURIMapping);
final ResourceSet rs = createAndConfigureResourceSetV2(modelURI, nsURIMapping);
subMonitor.subTask("Loading model");
subMonitor.newChild(3);
// load model resource and resolve all proxies
Resource r = rs.getResource(modelURI, true);
EcoreUtil.resolveAll(rs);
// EObject root = r.getContents().get(0);
// force adaptee model resource in the main ResourceSet
if(r instanceof MelangeResourceImpl){
MelangeResourceImpl mr = (MelangeResourceImpl)r;
rs.getResources().add(mr.getWrappedResource());
if(!r.getContents().isEmpty() && r.getContents().get(0) instanceof EObjectAdapter){
Resource realResource = ((EObjectAdapter) r.getContents().get(0)).getAdaptee().eResource();
rs.getResources().add(realResource);
}
}
// calculating aird URI
/*URI airdURI = useMelange ? URI.createURI(sessionResourceURI.toString()
.replace("platform:/", "melange:/")) : sessionResourceURI;*/
URI airdURI = sessionResourceURI;
// URI airdURI = sessionResourceURI;
subMonitor.subTask("Creating Sirius session");
subMonitor.newChild(1);
// create and load sirius session
final Session session = DebugSessionFactory.INSTANCE.createSession(rs,
airdURI);
//Specific to MelangeResource
if(r.getContents().size() > 0) {
Resource res = r.getContents().get(0).eResource(); // get the used resource
res.eAdapters().add(new SessionTransientAttachment(session)); // link the resource with Sirius session
}
//final IProgressMonitor monitor = new NullProgressMonitor();
final TransactionalEditingDomain editingDomain = session
.getTransactionalEditingDomain();
subMonitor.subTask("Opening Sirius session");
session.open(subMonitor.newChild(2));
// EcoreUtil.resolveAll(rs);
// activating layers
subMonitor.subTask("Opening Sirius editors");
SubMonitor openEditorSubMonitor = subMonitor.newChild(2);
for (DView view : session.getSelectedViews()) {
for (DRepresentation representation : view
.getOwnedRepresentations()) {
final DSemanticDiagram diagram = (DSemanticDiagram) representation;
openEditorSubMonitor.subTask(diagram.getName());
final List<EObject> elements = new ArrayList<EObject>();
elements.add(diagram);
final IEditorPart editorPart = DialectUIManager.INSTANCE
.openEditor(session, representation, openEditorSubMonitor.newChild(1));
if (editorPart instanceof DDiagramEditor) {
((DDiagramEditor) editorPart).getPaletteManager()
.addToolFilter(new ToolFilter() {
@Override
public boolean filter(DDiagram diagram,
AbstractToolDescription tool) {
return true;
}
});
}
try{
RefreshDiagramOnOpeningCommand refresh = new RefreshDiagramOnOpeningCommand(editingDomain, diagram);
CommandExecution.execute(editingDomain, refresh);
} catch (Exception e){
Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
"Problem refreshing diagrams : " + diagram, e));
}
if (editorPart instanceof DiagramEditorWithFlyOutPalette) {
PaletteUtils
.colapsePalette((DiagramEditorWithFlyOutPalette) editorPart);
}
RecordingCommand command = new RecordingCommand(editingDomain,
"Activating animator and debug layers") {
@Override
protected void doExecute() {
boolean hasADebugLayer = false;
for (Layer l : diagram.getDescription()
.getAdditionalLayers()) {
String descName = diagram.getDescription()
.getName();
String layerName = l.getName();
boolean mustBeActiveForDebug = AbstractDSLDebuggerServices.LISTENER
.isRepresentationToRefresh(context.getRunConfiguration().getDebugModelID(),
descName, layerName)
|| layerName.equalsIgnoreCase("Debug");
boolean mustBeActiveForAnimation = AbstractGemocAnimatorServices.ANIMATOR
.isRepresentationToRefresh(descName,
layerName)
|| layerName.equalsIgnoreCase("Animation");
boolean mustBeActive = mustBeActiveForAnimation
|| mustBeActiveForDebug;
hasADebugLayer = hasADebugLayer && mustBeActiveForDebug;
if (mustBeActive
&& !diagram.getActivatedLayers()
.contains(l)) {
ChangeLayerActivationCommand c = new ChangeLayerActivationCommand(
editingDomain, diagram, l, openEditorSubMonitor.newChild(1));
c.execute();
}
}
if(!hasADebugLayer){
// no debug layer defined in the odesign for debugmodelID
Activator.getDefault().getLog().log(new Status(IStatus.WARNING, Activator.PLUGIN_ID,
"No debug service defined in the odesign for the debug model id : " +
context.getRunConfiguration().getDebugModelID()));
}
}
};
CommandExecution.execute(editingDomain, command);
}
}
return session;
}
private ResourceSet createAndConfigureResourceSet(URI modelURI,
HashMap<String, String> nsURIMapping) {
final ResourceSet rs = ResourceSetFactory.createFactory()
.createResourceSet(modelURI);
final String fileExtension = modelURI.fileExtension();
// indicates which melange query should be added to the xml uri handler
// for a given extension
final XMLURIHandler handler = new XMLURIHandler(modelURI.query(), fileExtension); // use to resolve cross ref
// URI during XMI parsing
//final XtextPlatformResourceURIHandler handler = new XtextPlatformResourceURIHandler();
handler.setResourceSet(rs);
rs.getLoadOptions().put(XMLResource.OPTION_URI_HANDLER, handler);
final MelangeURIConverter converter = new MelangeURIConverter(fileExtension, nsURIMapping);
//final ExtensibleURIConverterImpl converter = new ExtensibleURIConverterImpl();
rs.setURIConverter(converter);
// fix sirius to prevent non intentional model savings
converter.getURIHandlers().add(0, new DebugURIHandler(converter.getURIHandlers()));
return rs;
}
private ResourceSet createAndConfigureResourceSetV2(URI modelURI, HashMap<String, String> nsURIMapping) {
final ResourceSet rs = ResourceSetFactory.createFactory()
.createResourceSet(modelURI);
final String fileExtension = modelURI.fileExtension();
// indicates which melange query should be added to the xml uri handler
// for a given extension
final XMLURIHandler handler = new XMLURIHandler(modelURI.query(), fileExtension); // use to resolve cross ref
// URI during XMI parsing
//final XtextPlatformResourceURIHandler handler = new XtextPlatformResourceURIHandler();
handler.setResourceSet(rs);
rs.getLoadOptions().put(XMLResource.OPTION_URI_HANDLER, handler);
final MelangeURIConverterV2 converter = new MelangeURIConverterV2(fileExtension, nsURIMapping);
//final ExtensibleURIConverterImpl converter = new ExtensibleURIConverterImpl();
rs.setURIConverter(converter);
// fix sirius to prevent non intentional model savings
converter.getURIHandlers().add(0, new DebugURIHandler(converter.getURIHandlers()));
return rs;
}
// TODO must be extended to support more complex mappings, currently use
// only the first package in the genmodel
// TODO actually, melange should produce the nsURI mapping and register it
// in some way so we can retreive it
protected HashMap<String, String> getnsURIMapping(IExecutionContext context) {
HashMap<String, String> nsURIMapping = new HashMap<String, String>();
final String langQuery = "lang=";
String melangeQuery = context.getRunConfiguration()
.getExecutedModelAsMelangeURI().query();
if (melangeQuery != null && !melangeQuery.isEmpty()
&& melangeQuery.contains(langQuery)) {
String targetLanguage = melangeQuery.substring(melangeQuery
.indexOf(langQuery) + langQuery.length());
if(targetLanguage.contains("&")){
targetLanguage = targetLanguage.substring(0, targetLanguage.indexOf("&"));
}
String targetLanguageNsURI = MelangeRegistry.INSTANCE.getLanguageByIdentifier(targetLanguage).getUri();
// simply open the original model file in a separate ResourceSet
// and ask its root element class nsURI
Object o = EMFResource.getFirstContent(context
.getRunConfiguration().getExecutedModelURI());
if (o instanceof EObject) {
EPackage rootPackage = ((EObject) o).eClass().getEPackage();
while (rootPackage.getESuperPackage() != null) {
rootPackage = rootPackage.getESuperPackage();
}
nsURIMapping.put(rootPackage.getNsURI(), targetLanguageNsURI);
}
}
return nsURIMapping;
}
class MelangeURIConverterV2 extends ExtensibleURIConverterImpl {
private String _fileExtension;
private HashMap<String, String> _nsURIMapping;
public MelangeURIConverterV2(String fileExtension,
HashMap<String, String> nsURIMapping) {
_fileExtension = fileExtension;
_nsURIMapping = nsURIMapping;
}
@SuppressWarnings("resource")
@Override
public InputStream createInputStream(URI uri, Map<?, ?> options)
throws IOException {
InputStream result = null;
// do not modify content of files loaded using melange:/ scheme
// melange is supposed to do the job
//if (uri.scheme()!= null && uri.scheme().equals("melange")) {
// return super.createInputStream(uri);
if(uri.fileExtension() == null || !uri.fileExtension().equals("aird")){
// only the root aird must be adapted
return super.createInputStream(uri, options);
}
InputStream originalInputStream = null;
try {
originalInputStream = super.createInputStream(uri, options);
String originalContent = convertStreamToString(originalInputStream);
String modifiedContent = originalContent;
for (Entry<String, String> entry : _nsURIMapping
.entrySet()) {
modifiedContent = modifiedContent.replace(
entry.getKey(), entry.getValue());
}
result = new StringInputStream(modifiedContent);
return result;
} finally {
if (originalInputStream != null) {
originalInputStream.close();
}
}
}
private String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s1 = new java.util.Scanner(is);
java.util.Scanner s2 = s1.useDelimiter("\\A");
String result = s2.hasNext() ? s2.next() : "";
s1.close();
s2.close();
return result;
}
}
class MelangeURIConverter extends ExtensibleURIConverterImpl {
private String _fileExtension;
private HashMap<String, String> _nsURIMapping;
public MelangeURIConverter(String fileExtension,
HashMap<String, String> nsURIMapping) {
_fileExtension = fileExtension;
_nsURIMapping = nsURIMapping;
}
@SuppressWarnings("resource")
@Override
public InputStream createInputStream(URI uri, Map<?, ?> options)
throws IOException {
InputStream result = null;
// the URI to use for model loading is not melange:/... but
// platform:/... and without the ?xx=...
URI uriToUse = uri;
boolean useSuperMethod = true;
/*
if (uri.scheme()!= null && uri.scheme().equals("melange")) { // may be null in relative path
String uriAsString = uri.toString().replace("melange:/",
"platform:/");
if (uri.fileExtension() != null
&& uri.fileExtension().equals(_fileExtension)) {
useSuperMethod = false;
uriAsString = uriAsString.substring(0,
uriAsString.indexOf('?'));
uriToUse = URI.createURI(uriAsString);
InputStream originalInputStream = null;
try {
originalInputStream = super.createInputStream(uriToUse,
options);
String originalContent = convertStreamToString(originalInputStream);
String modifiedContent = originalContent;
for (Entry<String, String> entry : _nsURIMapping
.entrySet()) {
modifiedContent = modifiedContent.replace(
entry.getKey(), entry.getValue());
}
result = new StringInputStream(modifiedContent);
} finally {
if (originalInputStream != null) {
originalInputStream.close();
}
}
} else {
uriToUse = URI.createURI(uriAsString);
}
}
*/
if (uri.fileExtension() != null
&& uri.fileExtension().equals(_fileExtension)) {
/* String uriAsString = uri.toString().replace("melange:/",
"platform:/");*/
useSuperMethod = false;
/*uriAsString = uriAsString.substring(0,
uriAsString.indexOf('?'));*/
uriToUse = uri ; //URI.createURI(uri);
InputStream originalInputStream = null;
try {
originalInputStream = super.createInputStream(uriToUse,
options);
String originalContent = convertStreamToString(originalInputStream);
String modifiedContent = originalContent;
for (Entry<String, String> entry : _nsURIMapping
.entrySet()) {
modifiedContent = modifiedContent.replace(
entry.getKey(), entry.getValue());
}
result = new StringInputStream(modifiedContent);
} finally {
if (originalInputStream != null) {
originalInputStream.close();
}
}
} else {
}
if (useSuperMethod) {
result = super.createInputStream(uriToUse, options);
}
// // making sure that uri can be modified
// if (uri.fileExtension() != null
// && uri.fileExtension().equals(_fileExtension)
// && uri.scheme().equals("melange"))
// String uriAsString = uri.toString().replace("melange:/",
// "platform:/");
// uriAsString = uriAsString.substring(0, uriAsString.indexOf('?'));
// uriToUse = URI.createURI(uriAsString);
// InputStream originalInputStream = null;
// try
// originalInputStream = super.createInputStream(uriToUse, options);
// String originalContent =
// convertStreamToString(originalInputStream);
// String modifiedContent =
// result = new StringInputStream(modifiedContent);
// finally
// if (originalInputStream != null)
// originalInputStream.close();
// else
return result;
}
private String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s1 = new java.util.Scanner(is);
java.util.Scanner s2 = s1.useDelimiter("\\A");
String result = s2.hasNext() ? s2.next() : "";
s1.close();
s2.close();
return result;
}
}
/**
* change scheme to melange:// for files with the given fileextension when a melange query is active
* @author dvojtise
*
*/
class XMLURIHandler extends XtextPlatformResourceURIHandler {
private String _queryParameters;
private String _fileExtension;
public XMLURIHandler(String queryParameters, String fileExtension) {
_queryParameters = queryParameters;
if (_queryParameters == null)
_queryParameters = "";
else
_queryParameters = "?" + _queryParameters;
_fileExtension = fileExtension;
}
@Override
public URI resolve(URI uri) {
URI resolvedURI = super.resolve(uri);
if ( !_queryParameters.isEmpty()
&& resolvedURI.scheme() != null
&& !resolvedURI.scheme().equals("melange")
&& resolvedURI.fileExtension() != null
&& resolvedURI.fileExtension().equals(_fileExtension)) {
String fileExtensionWithPoint = "." + _fileExtension;
int lastIndexOfFileExtension = resolvedURI.toString()
.lastIndexOf(fileExtensionWithPoint);
String part1 = resolvedURI.toString().substring(0,
lastIndexOfFileExtension);
part1 = part1.replaceFirst("platform:/", "melange:/");
String part2 = fileExtensionWithPoint + _queryParameters;
String part3 = resolvedURI.toString().substring(
lastIndexOfFileExtension
+ fileExtensionWithPoint.length());
String newURIAsString = part1 + part2 + part3;
return URI.createURI(newURIAsString);
}
return resolvedURI;
}
}
IProgressMonitor progressMonitor;
@Override
public void setProgressMonitor(IProgressMonitor progressMonitor) {
this.progressMonitor = progressMonitor;
}
} |
package com.pollistics.controllers;
import com.pollistics.models.Poll;
import com.pollistics.services.PollService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.MessageFormat;
import java.util.HashMap;
@Controller
public class PollController {
@Autowired
private PollService pollService;
private Cookie cookie = new Cookie("id", "");
@GetMapping(value = "/polls")
public String allPolls(Model model) {
model.addAttribute("polls", pollService.getAllPolls());
return "polls/overview";
}
@GetMapping(value = {"/polls/{pollId}", "/{pollId}"})
public String pollDetail(@PathVariable String pollId, Model model, HttpServletResponse response) {
Poll poll = pollService.getPoll(pollId);
if(poll == null) {
response.setStatus(404);
return "error/404";
}
model.addAttribute("poll", pollService.getPoll(pollId));
return "polls/detail";
}
@PostMapping(value = "/polls/create")
public String createPoll(HttpServletRequest request) {
String title = request.getParameter("title");
String option1 = request.getParameter("option1");
String option2 = request.getParameter("option2");
String option3 = request.getParameter("option3");
HashMap<String, Integer> options = new HashMap<>();
options.put(option1, 0);
options.put(option2, 0);
options.put(option3, 0);
String id = pollService.createPoll(title, options);
return "redirect:/" + id;
}
@PostMapping(value = "/polls/delete/{pollId}")
public String deletePoll(@PathVariable String pollId, HttpServletResponse response, RedirectAttributes redirectAttrs) {
boolean result = pollService.deletePoll(pollId);
if (result) {
redirectAttrs.addFlashAttribute("delete", "The poll has deleted successfully!");
return "redirect:/";
} else {
response.setStatus(404);
return "error/404";
}
}
@PostMapping(value = "/polls/vote/{pollId}")
public String voteOptions(@CookieValue(value = "id", defaultValue = "") String cookieIdValue, @PathVariable String pollId, HttpServletRequest request, HttpServletResponse response, Model model) {
if (cookie.getValue().contains(pollId)) {
Poll p = pollService.getPoll(pollId);
model.addAttribute("msg", MessageFormat.format("You already voted for poll: {0}", p.getName()));
model.addAttribute("previous", MessageFormat.format("/{0}/", pollId));
response.setStatus(403);
return "error/403";
} else {
String value;
if (cookie.getValue().equals("")) {
value = pollId;
} else {
value = MessageFormat.format("{0}-{1}", pollId, cookieIdValue);
}
final int expiryTimeCookie = 2147483647; // maximum of int
final String cookiePath = "/";
cookie.setValue(value);
cookie.setMaxAge(expiryTimeCookie);
cookie.setPath(cookiePath);
response.addCookie(cookie);
String option = request.getParameter("option");
Poll p = pollService.getPoll(pollId);
pollService.voteOption(p, option);
return "redirect:/" + pollId;
}
}
} |
package org.xwiki.contrib.wiki30.internal;
import java.util.List;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.annotation.Requirement;
import org.xwiki.component.logging.AbstractLogEnabled;
import org.xwiki.context.Execution;
import org.xwiki.contrib.wiki30.Workspace;
import org.xwiki.contrib.wiki30.WorkspaceManager;
import org.xwiki.contrib.wiki30.WorkspaceManagerException;
import org.xwiki.script.service.ScriptService;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.plugin.applicationmanager.core.api.XWikiExceptionApi;
import com.xpn.xwiki.plugin.wikimanager.WikiManagerException;
import com.xpn.xwiki.plugin.wikimanager.doc.XWikiServer;
/**
* Makes the WorkspaceManager API available to scripting.
*
* @version $Id:$
*/
@Component("workspaceManager")
public class WorkspaceManagerScriptService extends AbstractLogEnabled implements ScriptService
{
/** Field name of the last error code inserted in context. */
public static final String CONTEXT_LASTERRORCODE = "lasterrorcode";
/** Field name of the last API exception inserted in context. */
public static final String CONTEXT_LASTEXCEPTION = "lastexception";
@Requirement
private WorkspaceManager workspaceManager;
/** Execution context. */
@Requirement
private Execution execution;
public WorkspaceManager getManager()
{
return workspaceManager;
}
/** @see org.xwiki.contrib.wiki30.WorkspaceManager#canCreateWorkspace(java.lang.String, java.lang.String) */
public boolean canCreateWorkspace(String userName, String workspaceName)
{
return workspaceManager.canCreateWorkspace(getPrefixedUserName(userName), workspaceName);
}
/** @see org.xwiki.contrib.wiki30.WorkspaceManager#canEditWorkspace(java.lang.String, java.lang.String) */
public boolean canEditWorkspace(String userName, String workspaceName)
{
return workspaceManager.canEditWorkspace(getPrefixedUserName(userName), workspaceName);
}
/** @see org.xwiki.contrib.wiki30.WorkspaceManager#canDeleteWorkspace(java.lang.String, java.lang.String) */
public boolean canDeleteWorkspace(String userName, String workspaceName)
{
return workspaceManager.canDeleteWorkspace(getPrefixedUserName(userName), workspaceName);
}
/**
* @see org.xwiki.contrib.wiki30.WorkspaceManager#createWorkspace(java.lang.String, java.lang.String,
* com.xpn.xwiki.plugin.wikimanager.doc.XWikiServer)
*/
public int createWorkspace(String workspaceName, XWikiServer newWikiXObjectDocument)
{
int returncode = XWikiExceptionApi.ERROR_NOERROR;
try {
if (!canCreateWorkspace(getXWikiContext().getUser(), workspaceName)) {
throw new WikiManagerException(XWikiException.ERROR_XWIKI_ACCESS_DENIED, String.format(
"Access denied to create the workspace '%s'", workspaceName));
}
/* Avoid "traps" by making sure the page from where this is executed has PR. */
if (!getXWikiContext().getWiki().getRightService().hasProgrammingRights(getXWikiContext())) {
throw new WikiManagerException(XWikiException.ERROR_XWIKI_ACCESS_DENIED, String.format(
"The page requires programming rights in order to create the workspace '%s'", workspaceName));
}
if (workspaceName == null || workspaceName.trim().equals("")) {
throw new WikiManagerException(WikiManagerException.ERROR_WM_WIKINAMEFORBIDDEN, String.format(
"Workspace name '%s' is invalid.", workspaceName));
}
this.workspaceManager.createWorkspace(workspaceName, newWikiXObjectDocument);
} catch (XWikiException e) {
error(String.format("Failed to create workspace '%s'.", workspaceName), e);
returncode = e.getCode();
}
return returncode;
}
/** @see org.xwiki.contrib.wiki30.WorkspaceManager#deleteWorkspace(java.lang.String) */
public void deleteWorkspace(String workspaceName)
{
try {
/* Get prefixed current user. */
String currentUser = getPrefixedUserName(getXWikiContext().getUser());
/* Check rights. */
if (!canDeleteWorkspace(currentUser, workspaceName)) {
throw new WorkspaceManagerException(String.format(
"Access denied for user '%s' to delete the workspace '%s'", currentUser, workspaceName));
}
/* Avoid "traps" by making sure the page from where this is executed has PR. */
if (!getXWikiContext().getWiki().getRightService().hasProgrammingRights(getXWikiContext())) {
throw new WorkspaceManagerException(String.format(
"The page requires programming rights in order to delete the workspace '%s'", workspaceName));
}
/* Delegate call. */
workspaceManager.deleteWorkspace(workspaceName);
} catch (Exception e) {
error(String.format("Failed to delete workspace '%s'.", workspaceName), e);
}
}
/**
* @see org.xwiki.contrib.wiki30.WorkspaceManager#editWorkspace(java.lang.String,
* com.xpn.xwiki.plugin.wikimanager.doc.XWikiServer)
*/
public void editWorkspace(String workspaceName, XWikiServer modifiedWikiXObjectDocument)
{
try {
String currentUser = getPrefixedUserName(getXWikiContext().getUser());
/* Check rights. */
if (!canEditWorkspace(currentUser, workspaceName)) {
throw new WorkspaceManagerException(String.format(
"Access denied for user '%s' to edit the workspace '%s'", currentUser, workspaceName));
}
/* Avoid "traps" by making sure the page from where this is executed has PR. */
if (!getXWikiContext().getWiki().getRightService().hasProgrammingRights(getXWikiContext())) {
throw new WorkspaceManagerException(String.format(
"The page requires programming rights in order to edit the workspace '%s'", workspaceName));
}
/* Delegate call. */
workspaceManager.editWorkspace(workspaceName, modifiedWikiXObjectDocument);
} catch (Exception e) {
error(String.format("Failed to edit workspace '%s'.", workspaceName), e);
}
}
/**
* @param userName a wiki name prefixed or un-prefixed user name.
* @return always the a wiki name prefixed user name.
*/
private String getPrefixedUserName(String userName)
{
XWikiContext deprecatedContext = getXWikiContext();
String result = userName;
if (!result.startsWith(String.format("%s:", deprecatedContext.getMainXWiki()))) {
result = String.format("%s:%s", deprecatedContext.getMainXWiki(), result);
}
return result;
}
/** @return the deprecated xwiki context used to manipulate xwiki objects */
private XWikiContext getXWikiContext()
{
return (XWikiContext) execution.getContext().getProperty("xwikicontext");
}
/**
* Log error and store details in the context.
*
* @param errorMessage error message.
* @param e the caught exception.
* @deprecated stop using {@link XWikiException}, put exception in context under {@link #CONTEXT_LASTEXCEPTION} key
* instead.
*/
private void error(String errorMessage, XWikiException e)
{
getLogger().error(errorMessage, e);
XWikiContext deprecatedContext = getXWikiContext();
deprecatedContext.put(CONTEXT_LASTERRORCODE, Integer.valueOf(e.getCode()));
deprecatedContext.put(CONTEXT_LASTEXCEPTION, new XWikiExceptionApi(e, deprecatedContext));
}
/**
* Log exception and store it in the context.
*
* @param errorMessage error message.
* @param e the caught exception.
* @see #CONTEXT_LASTEXCEPTION
*/
private void error(String errorMessage, Exception e)
{
if (errorMessage == null) {
errorMessage = e.getMessage();
}
/* Log exception. */
getLogger().error(errorMessage, e);
/* Store exception in context. */
XWikiContext deprecatedContext = getXWikiContext();
deprecatedContext.put(CONTEXT_LASTEXCEPTION, e);
}
/**
* Log exception and store it in the context. The logged message is the exception's message. This allows the
* underlying component to define it's messages and removes duplication.
*
* @param e the caught exception.
* @see #CONTEXT_LASTEXCEPTION
*/
private void error(Exception e)
{
error(null, e);
}
/** @see org.xwiki.contrib.wiki30.WorkspaceManager#getWorkspace(String) */
public Workspace getWorkspace(String workspaceId)
{
Workspace result = null;
try {
result = workspaceManager.getWorkspace(workspaceId);
} catch (Exception e) {
error(e);
}
return result;
}
/** @see org.xwiki.contrib.wiki30.WorkspaceManager#getWorkspaces() */
public List<Workspace> getWorkspaces()
{
List<Workspace> result = null;
try {
result = workspaceManager.getWorkspaces();
} catch (Exception e) {
error(e);
}
return result;
}
} |
package org.springframework.tooling.jdt.ls.commons.classpath;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Supplier;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.ListenerList;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.springframework.tooling.jdt.ls.commons.Logger;
import org.springframework.tooling.jdt.ls.commons.classpath.ClasspathListenerManager.ClasspathListener;
/**
* {@link ReusableClasspathListenerHandler} is an 'abstracted' version of the jdtls ClasspathListenerHandler.
*/
public class ReusableClasspathListenerHandler {
public interface NotificationSentCallback {
void sent(Collection<String> projectNames);
}
private final Logger logger;
private final ClientCommandExecutor conn;
private final Supplier<Comparator<IProject>> projectSorterFactory;
private final ListenerList<NotificationSentCallback> notificationsSentCallbacks;
public ReusableClasspathListenerHandler(Logger logger, ClientCommandExecutor conn) {
this(logger, conn, null);
}
public ReusableClasspathListenerHandler(Logger logger, ClientCommandExecutor conn, Supplier<Comparator<IProject>> projectSorterFactory) {
this.logger = logger;
this.projectSorterFactory = projectSorterFactory;
this.conn = conn;
this.notificationsSentCallbacks = new ListenerList<>();
logger.log("Instantiating ReusableClasspathListenerHandler");
}
private class CallbackJob extends Job {
public CallbackJob() {
super("Classpath Notiifcation Post Processing");
setSystem(true);
}
private Set<String> projectNames = Collections.synchronizedSet(new HashSet<>());
@Override
protected IStatus run(IProgressMonitor monitor) {
if (!projectNames.isEmpty()) {
notificationsSentCallbacks.forEach(callback -> callback.sent(projectNames));
}
return Status.OK_STATUS;
}
void queueProjects(Collection<String> projectNames) {
this.projectNames.addAll(projectNames);
schedule();
}
}
class Subscriptions {
private ConcurrentMap<String, SendClasspathNotificationsJob> subscribers;
private ClasspathListenerManager classpathListener;
private CallbackJob callbackJob;
public Subscriptions() {
this.subscribers = new ConcurrentHashMap<>();
this.callbackJob = new CallbackJob();
}
public void subscribe(String callbackCommandId, boolean isBatched) {
// keep out of synchronized block to avoid workspace locks
IProject[] sortedProjects = getSortedProjects();
synchronized(this) {
if (!subscribers.containsKey(callbackCommandId)) {
logger.log("subscribing to classpath changes: " + callbackCommandId +" isBatched = "+isBatched);
classpathListener = new ClasspathListenerManager(logger, new ClasspathListener() {
@Override
public void classpathChanged(IJavaProject jp) {
sendNotification(jp, subscribers.keySet());
}
@Override
public void projectBuilt(IJavaProject jp) {
sendNotificationOnProjectBuilt(jp, subscribers.keySet());
}
});
final SendClasspathNotificationsJob job = new SendClasspathNotificationsJob(logger, conn, callbackCommandId, isBatched);
subscribers.put(callbackCommandId, job);
job.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(IJobChangeEvent event) {
List<String> projectNames = job.notificationsSentForProjects;
if (projectNames != null) {
callbackJob.queueProjects(projectNames);
}
}
});
logger.log("subsribers = " + subscribers);
sendInitialEvents(callbackCommandId, sortedProjects);
}
}
}
private void sendInitialEvents(String callbackCommandId, IProject[] projects) {
logger.log("Sending initial event for all projects ...");
Set<String> callbackIds = Collections.singleton(callbackCommandId);
for (IProject p : projects) {
logger.log("project "+p.getName() +" ..." );
try {
if (p.isAccessible() && p.hasNature(JavaCore.NATURE_ID)) {
IJavaProject jp = JavaCore.create(p);
sendNotification(jp, callbackIds);
} else {
logger.log("project "+p.getName() +" SKIPPED" );
}
} catch (CoreException e) {
logger.log(e);
}
}
logger.log("Sending initial event for all projects DONE");
}
private IProject[] getSortedProjects() {
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
if (projectSorterFactory != null) {
Arrays.sort(projects, projectSorterFactory.get());
}
return projects;
}
private synchronized void sendNotification(IJavaProject jp, Collection<String> callbackIds) {
for (String callbackId : callbackIds) {
SendClasspathNotificationsJob sendNotificationJob = subscribers.get(callbackId);
sendNotificationJob.queue.add(jp);
sendNotificationJob.schedule();
}
}
private synchronized void sendNotificationOnProjectBuilt(IJavaProject jp, Collection<String> callbackIds) {
for (String callbackId : callbackIds) {
SendClasspathNotificationsJob sendNotificationJob = subscribers.get(callbackId);
sendNotificationJob.builtProjectQueue.add(jp);
sendNotificationJob.schedule();
}
}
public synchronized void unsubscribe(String callbackCommandId) {
logger.log("unsubscribing from classpath changes: " + callbackCommandId);
subscribers.remove(callbackCommandId);
if (subscribers.isEmpty() && classpathListener != null) {
classpathListener.dispose();
classpathListener = null;
}
logger.log("subsribers = " + subscribers);
}
public boolean isEmpty() {
return subscribers.isEmpty();
}
}
private Subscriptions subscriptions = new Subscriptions();
public Object removeClasspathListener(String callbackCommandId) {
logger.log("ClasspathListenerHandler removeClasspathListener " + callbackCommandId);
subscriptions.unsubscribe(callbackCommandId);
logger.log("ClasspathListenerHandler removeClasspathListener " + callbackCommandId + " => OK");
return "ok";
}
@Deprecated
public Object addClasspathListener(String callbackCommandId) {
return addClasspathListener(callbackCommandId, false);
}
public Object addClasspathListener(String callbackCommandId, boolean isBatched) {
logger.log("ClasspathListenerHandler addClasspathListener " + callbackCommandId + "isBatched = "+isBatched);
subscriptions.subscribe(callbackCommandId, isBatched);
logger.log("ClasspathListenerHandler addClasspathListener " + callbackCommandId + " => OK");
return "ok";
}
public boolean hasNoActiveSubscriptions() {
return subscriptions.isEmpty();
}
public void addNotificationsSentCallback(NotificationSentCallback callback) {
notificationsSentCallbacks.add(callback);
}
public void removeNotificationsSentCallback(NotificationSentCallback callback) {
notificationsSentCallbacks.remove(callback);
}
} |
package creatures;
import game.Building;
import java.util.Random;
import javax.media.opengl.GL2;
import javax.media.opengl.glu.GLU;
import javax.media.opengl.glu.GLUquadric;
import weapons.Projectile;
import com.jogamp.opengl.util.texture.Texture;
import game.PlayerMotion;
import game.PlayerMotionWatcher;
import game.PlayerStats;
public class PacManGhost implements Creature, PlayerMotionWatcher, ProjectileWatcher {
private Texture parkGhost;
private Texture parkGhostColor;
private GLUquadric quadric;
private float X = 0f;
private float Y = 2.5f;
private float Z = 0f;
private float playerX;
private float playerZ;
private float bulletX;
private float bulletY;
private float playerAngle;
private float T = 0;
private int count = 0;
private float directionAngle = 0;
private boolean seesPlayer = false;
private boolean shotByBullet = false;
private boolean visible = true;
private float detectionRadius = 25f;
private Random random = new Random();
private double k = random.nextDouble();
public PacManGhost(float x, float z, GL2 gl, GLU glu) {
X = x;
Z = z;
parkGhost = Building.setupTexture(gl, "ParkGhost.jpg");
parkGhostColor = Building.setupTexture(gl, "ParkGhostColor.jpg");
quadric = glu.gluNewQuadric();
glu.gluQuadricDrawStyle(quadric, GLU.GLU_FILL); // GLU_POINT, GLU_LINE, GLU_FILL, GLU_SILHOUETTE
glu.gluQuadricNormals (quadric, GLU.GLU_NONE); // GLU_NONE, GLU_FLAT, or GLU_SMOOTH
glu.gluQuadricTexture (quadric, true); // false, or true to generate texture coordinates
PlayerMotion.registerPlayerWatcher(this);
Projectile.registerProjectileWatcher(this);
}
public void drawTail(GL2 gl, GLU glu, float x, float y, float z) {
gl.glPushMatrix();
gl.glTranslatef(x, y, z);
float angle = (float) (10*Math.cos(Math.toRadians(T*360)));
gl.glRotatef(angle, 0, 0, 1);
gl.glRotatef(-90f, 1f, 0f, 0f); // stand upright (Y)
gl.glTranslatef(0, 0, -0.75f);
glu.gluCylinder(quadric, 0, 0.3, 0.75, 20, 20);
gl.glPopMatrix();
}
public void drawTail2(GL2 gl, GLU glu, float x, float y, float z) {
gl.glPushMatrix();
gl.glTranslatef(x, y, z);
float angle = (float) (10*Math.sin(Math.toRadians(T*360-90)));
gl.glRotatef(angle, 0, 0, 1);
gl.glRotatef(-90f, 1f, 0f, 0f); // stand upright (Y)
gl.glTranslatef(0, 0, -0.75f);
glu.gluCylinder(quadric, 0, 0.3, 0.75, 20, 20);
gl.glPopMatrix();
}
public void drawOuterCircle(GL2 gl, GLU glu, float x, float y, float z) {
gl.glPushMatrix();
gl.glTranslatef(x, y, z);
gl.glRotatef(directionAngle, 0f, 1f, 0f);
drawTail(gl, glu, 0.7f, 1f, 0);
drawTail(gl, glu, -0.7f, 1f, 0);
drawTail(gl,glu, 0, 1f, 0.7f);
drawTail(gl,glu, 0, 1f, -0.7f);
drawTail(gl,glu, 0.494f, 1f, 0.494f);
drawTail(gl,glu, -0.494f, 1f, -0.494f);
drawTail(gl,glu, 0.494f, 1f, -0.494f);
drawTail(gl,glu, -0.494f, 1f, 0.494f);
gl.glPopMatrix();
}
public void drawInnerCircle(GL2 gl, GLU glu, float x, float y, float z) {
gl.glPushMatrix();
gl.glTranslatef(x, y, z);
gl.glRotatef(directionAngle, 0f, 1f, 0f);
drawTail2(gl, glu, 0.4f, 1f, 0);
drawTail2(gl, glu, -0.4f, 1f, 0);
drawTail2(gl,glu, 0, 1f, 0.4f);
drawTail2(gl,glu, 0, 1f, -0.4f);
drawTail2(gl,glu, 0.282f, 1f, 0.282f);
drawTail2(gl,glu, -0.282f, 1f, -0.282f);
drawTail2(gl,glu, 0.282f, 1f, -0.282f);
drawTail2(gl,glu, -0.282f, 1f, 0.282f);
gl.glPopMatrix();
}
public void drawAllTails (GL2 gl, GLU glu, float x, float y, float z) {
gl.glEnable(GL2.GL_TEXTURE_2D);
parkGhostColor.bind(gl);;
gl.glPushMatrix();
drawOuterCircle(gl,glu, x, y, z);
drawInnerCircle(gl,glu, x, y, z);
gl.glPopMatrix();
gl.glDisable(GL2.GL_TEXTURE_2D);
}
public void drawBody(GL2 gl, GLU glu, float x, float y, float z) {
gl.glEnable(GL2.GL_TEXTURE_2D);
parkGhostColor.bind(gl);
gl.glPushMatrix();
gl.glTranslatef(x, y + 2.25f, z);
glu.gluSphere(quadric, 1, 40, 40);
gl.glPopMatrix();
parkGhost.bind(gl);
gl.glPushMatrix();
gl.glTranslatef(x, y + 1f, z);
gl.glRotatef(directionAngle, 0f, 1f, 0f);
gl.glRotatef(-90f, 1f, 0f, 0f); // stand upright (Y)
glu.gluCylinder(quadric, 1, 1, 1.25, 40, 40);
gl.glPopMatrix();
gl.glDisable(GL2.GL_TEXTURE_2D);
}
public void drawGhost(GL2 gl, GLU glu, float x, float y, float z) {
if (visible) {
drawAllTails(gl,glu, x, y, z);
drawBody(gl, glu, x, y, z);
}
}
public void checkT() {
if (T > 300) {
T = 0f;
}
}
public void draw(GL2 gl, GLU glu) {
gl.glPushMatrix();
drawGhost(gl, glu, X, Y, Z);
move();
gl.glPopMatrix();
}
public void drawStillMotion() {
T = T + 0.99f;
checkT();
hoverHeight();
}
public void hoverHeight() {
if (count < 50) {
Y = Y + 0.015f;
count = count + 1;
} else if (count < 100) {
Y = Y - 0.015f;
count = count + 1;
} if (count == 100) {
count = 0;
k = random.nextDouble();
}
}
public void move() {
if (seesPlayer && !shotByBullet) {
moveTowardsPlayer();
} else if (shotByBullet) {
animateDeath();
}
drawStillMotion();
moveIdle();
}
public void playerMoved(float x, float y, float z, float angle, float yAngle,PlayerStats s) {
playerX = x;
playerZ = z;
playerAngle = angle;
double distance = Math.sqrt(Math.pow(X-x,2) + Math.pow(Z-z,2));
if(distance <= detectionRadius){
seesPlayer = true;
}
else{
seesPlayer = false;
}
}
public void projectileMoved(double x, double z) {
if ( x > X - 2 && x < X + 2) {
if ( z > Z - 2 && z < Z + 2) {
shotByBullet = true;
}
}
}
public void moveTowardsPlayer() {
directionAngle = playerAngle - 180;
double xV = playerX-X;
double zV = playerZ-Z;
double dotProduct = xV * 0.2 + zV * 0.2;
double lengthV1 = Math.sqrt((xV*xV)+(zV*zV));
lengthV1 = lengthV1 * lengthV1;
double constant = dotProduct / lengthV1;
double dx = constant * xV*1.5;
double dz = constant * zV*1.5;
dx = Math.abs(dx);
dz = Math.abs(dz);
if(playerZ<Z){ Z-=dz; }
else{ Z+=dz; }
if(playerX<X){X-=dx;}
else{ X+=dx;}
}
public void animateDeath() {
if (Y <= 0) {
visible = false;
} else {
Y = Y - 0.4f;
}
}
public void moveIdle() {
if (!seesPlayer) {
if (k <= 0.25) { //go left, directionAngle = 90
directionAngle = 90;
X = X + 0.05f;
} else if (k <= 0.5) { //go up, directionAngle = 0
directionAngle = 0;
Z = Z + 0.05f;
} else if (k <= 0.75) { //go right, directionAngle = 270
directionAngle = 270;
X = X - 0.05f;
} else { //go down, directionAngle = 180
directionAngle = 180;
Z = Z - 0.05f;
}
}
}
} |
package org.innovateuk.ifs.application.forms.questions.granttransferdetails.controller;
import org.innovateuk.ifs.BaseControllerMockMVCTest;
import org.innovateuk.ifs.application.forms.questions.granttransferdetails.form.GrantTransferDetailsForm;
import org.innovateuk.ifs.application.forms.questions.granttransferdetails.populator.GrantTransferDetailsFormPopulator;
import org.innovateuk.ifs.application.forms.questions.granttransferdetails.populator.GrantTransferDetailsViewModelPopulator;
import org.innovateuk.ifs.application.forms.questions.granttransferdetails.saver.GrantTransferDetailsSaver;
import org.innovateuk.ifs.application.forms.questions.granttransferdetails.viewmodel.GrantTransferDetailsViewModel;
import org.innovateuk.ifs.application.service.QuestionStatusRestService;
import org.innovateuk.ifs.user.resource.ProcessRoleResource;
import org.innovateuk.ifs.user.service.UserRestService;
import org.junit.Test;
import org.mockito.Mock;
import java.math.BigDecimal;
import java.util.Collections;
import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess;
import static org.innovateuk.ifs.user.builder.ProcessRoleResourceBuilder.newProcessRoleResource;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
public class GrantTransferDetailsControllerTest extends BaseControllerMockMVCTest<GrantTransferDetailsController> {
@Mock
private GrantTransferDetailsFormPopulator grantTransferDetailsFormPopulator;
@Mock
private GrantTransferDetailsViewModelPopulator grantTransferDetailsViewModelPopulator;
@Mock
private GrantTransferDetailsSaver grantTransferDetailsSaver;
@Mock
private UserRestService userRestService;
@Mock
private QuestionStatusRestService questionStatusRestService;
@Override
protected GrantTransferDetailsController supplyControllerUnderTest() {
return new GrantTransferDetailsController(grantTransferDetailsFormPopulator, grantTransferDetailsViewModelPopulator, grantTransferDetailsSaver, userRestService, questionStatusRestService);
}
@Test
public void viewGrantTransferDetails() throws Exception {
long questionId = 1L;
long applicationId = 2L;
GrantTransferDetailsViewModel viewModel = mock(GrantTransferDetailsViewModel.class);
when(grantTransferDetailsViewModelPopulator.populate(applicationId, questionId, loggedInUser.getId())).thenReturn(viewModel);
mockMvc.perform(
get("/application/{applicationId}/form/question/{questionId}/grant-transfer-details", applicationId, questionId))
.andExpect(status().isOk())
.andExpect(view().name("application/questions/grant-transfer-details"))
.andReturn();
verify(grantTransferDetailsFormPopulator).populate(any(), eq(applicationId));
}
@Test
public void saveAndReturn() throws Exception {
long questionId = 1L;
long applicationId = 2L;
mockMvc.perform(
post("/application/{applicationId}/form/question/{questionId}/grant-transfer-details", applicationId, questionId))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(String.format("/application/%d", applicationId)))
.andReturn();
}
@Test
public void markAsComplete() throws Exception {
long questionId = 1L;
long applicationId = 2L;
GrantTransferDetailsForm grantTransferDetailsForm = new GrantTransferDetailsForm();
grantTransferDetailsForm.setActionType(1L);
grantTransferDetailsForm.setFundingContribution(BigDecimal.valueOf(100000L));
grantTransferDetailsForm.setGrantAgreementNumber("123456");
grantTransferDetailsForm.setProjectCoordinator(true);
grantTransferDetailsForm.setStartDateMonth(10);
grantTransferDetailsForm.setStartDateYear(2000);
grantTransferDetailsForm.setEndDateMonth(10);
grantTransferDetailsForm.setEndDateYear(2025);
grantTransferDetailsForm.setParticipantId("123456789");
grantTransferDetailsForm.setProjectName("Project Name");
ProcessRoleResource role = newProcessRoleResource().build();
when(grantTransferDetailsSaver.save(grantTransferDetailsForm, applicationId)).thenReturn(restSuccess());
when(userRestService.findProcessRole(loggedInUser.getId(), applicationId)).thenReturn(restSuccess(role));
when(questionStatusRestService.markAsComplete(questionId, applicationId, role.getId())).thenReturn(restSuccess(Collections.emptyList()));
mockMvc.perform(
post("/application/{applicationId}/form/question/{questionId}/grant-transfer-details", applicationId, questionId)
.param("complete", "true")
.param("grantAgreementNumber", grantTransferDetailsForm.getGrantAgreementNumber())
.param("participantId", grantTransferDetailsForm.getParticipantId())
.param("projectName", grantTransferDetailsForm.getProjectName())
.param("startDateMonth", String.valueOf(grantTransferDetailsForm.getStartDateMonth()))
.param("startDateYear", String.valueOf(grantTransferDetailsForm.getStartDateYear()))
.param("endDateMonth", String.valueOf(grantTransferDetailsForm.getEndDateMonth()))
.param("endDateYear", String.valueOf(grantTransferDetailsForm.getEndDateYear()))
.param("fundingContribution", String.valueOf(grantTransferDetailsForm.getFundingContribution()))
.param("projectCoordinator", String.valueOf(grantTransferDetailsForm.getProjectCoordinator()))
.param("actionType", String.valueOf(grantTransferDetailsForm.getActionType())))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(String.format("/application/%d/form/question/%d/grant-transfer-details", applicationId, questionId)))
.andReturn();
verify(grantTransferDetailsSaver).save(grantTransferDetailsForm, applicationId);
verify(questionStatusRestService).markAsComplete(questionId, applicationId, role.getId());
}
@Test
public void edit() throws Exception {
long questionId = 1L;
long applicationId = 2L;
ProcessRoleResource role = newProcessRoleResource().build();
when(userRestService.findProcessRole(loggedInUser.getId(), applicationId)).thenReturn(restSuccess(role));
when(questionStatusRestService.markAsInComplete(questionId, applicationId, role.getId())).thenReturn(restSuccess());
GrantTransferDetailsViewModel viewModel = mock(GrantTransferDetailsViewModel.class);
when(grantTransferDetailsViewModelPopulator.populate(applicationId, questionId, loggedInUser.getId())).thenReturn(viewModel);
mockMvc.perform(
post("/application/{applicationId}/form/question/{questionId}/grant-transfer-details", applicationId, questionId)
.param("edit", "true"))
.andExpect(status().isOk())
.andExpect(view().name("application/questions/grant-transfer-details"))
.andReturn();
verify(questionStatusRestService).markAsInComplete(questionId, applicationId, role.getId());
}
} |
package com.sandwell.JavaSimulation3D;
import static com.sandwell.JavaSimulation.Util.formatNumber;
import java.util.ArrayList;
import java.util.HashMap;
import com.jaamsim.input.InputAgent;
import com.jaamsim.math.Color4d;
import com.sandwell.JavaSimulation.BooleanInput;
import com.sandwell.JavaSimulation.BooleanListInput;
import com.sandwell.JavaSimulation.BooleanVector;
import com.sandwell.JavaSimulation.ColourInput;
import com.sandwell.JavaSimulation.DoubleInput;
import com.sandwell.JavaSimulation.DoubleListInput;
import com.sandwell.JavaSimulation.DoubleVector;
import com.sandwell.JavaSimulation.EntityInput;
import com.sandwell.JavaSimulation.EntityListInput;
import com.sandwell.JavaSimulation.ErrorException;
import com.sandwell.JavaSimulation.FileEntity;
import com.sandwell.JavaSimulation.Input;
import com.sandwell.JavaSimulation.InputErrorException;
import com.sandwell.JavaSimulation.IntegerVector;
import com.sandwell.JavaSimulation.Keyword;
import com.sandwell.JavaSimulation.ProbabilityDistribution;
import com.sandwell.JavaSimulation.Process;
import com.sandwell.JavaSimulation.Tester;
import com.sandwell.JavaSimulation.Vector;
/**
* Class ModelEntity - JavaSimulation3D
*/
public class ModelEntity extends DisplayEntity {
// Breakdowns
@Keyword(desc = "Reliability is defined as:\n" +
" 100% - (plant breakdown time / total operation time)\n " +
"or\n " +
"(Operational Time)/(Breakdown + Operational Time)",
example = "Object1 Reliability { 0.95 }")
private final DoubleInput availability;
protected double hoursForNextFailure; // The number of working hours required before the next breakdown
protected double iATFailure; // inter arrival time between failures
protected boolean breakdownPending; // true when a breakdown is to occur
protected boolean brokendown; // true => entity is presently broken down
protected boolean maintenance; // true => entity is presently in maintenance
protected boolean associatedBreakdown; // true => entity is presently in Associated Breakdown
protected boolean associatedMaintenance; // true => entity is presently in Associated Maintenance
protected double breakdownStartTime; // Start time of the most recent breakdown
protected double breakdownEndTime; // End time of the most recent breakdown
// Breakdown Probability Distributions
@Keyword(desc = "A ProbabilityDistribution object that governs the duration of breakdowns (in hours).",
example = "Object1 DowntimeDurationDistribution { BreakdownProbDist1 }")
private final EntityInput<ProbabilityDistribution> downtimeDurationDistribution;
@Keyword(desc = "A ProbabilityDistribution object that governs when breakdowns occur (in hours).",
example = "Object1 DowntimeIATDistribution { BreakdownProbDist1 }")
private final EntityInput<ProbabilityDistribution> downtimeIATDistribution;
// Maintenance
@Keyword(desc = "The simulation time for the start of the first maintenance for each maintenance cycle.",
example = "Object1 FirstMaintenanceTime { 24 h }")
protected DoubleListInput firstMaintenanceTimes;
@Keyword(desc = "The time between maintenance activities for each maintenance cycle",
example = "Object1 MaintenanceInterval { 168 h }")
protected DoubleListInput maintenanceIntervals;
@Keyword(desc = "The durations of a single maintenance event for each maintenance cycle.",
example = "Object1 MaintenanceDuration { 336 h }")
protected DoubleListInput maintenanceDurations;
protected IntegerVector maintenancePendings; // Number of maintenance periods that are due
@Keyword(desc = "A Boolean value. Allows scheduled maintenances to be skipped if it overlaps " +
"with another planned maintenance event.",
example = "Object1 SkipMaintenanceIfOverlap { TRUE }")
protected BooleanListInput skipMaintenanceIfOverlap;
@Keyword(desc = "A list of objects that share the maintenance schedule with this object. " +
"In order for the maintenance to start, all objects on this list must be available." +
"This keyword is for Handlers and Signal Blocks only.",
example = "Block1 SharedMaintenance { Block2 Block2 }")
private final EntityListInput<ModelEntity> sharedMaintenanceList;
protected ModelEntity masterMaintenanceEntity; // The entity that has maintenance information
protected boolean performMaintenanceAfterShipDelayPending; // maintenance needs to be done after shipDelay
// Maintenance based on hours of operations
@Keyword(desc = "Working time for the start of the first maintenance for each maintenance cycle",
example = "Object1 FirstMaintenanceOperatingHours { 1000 2500 h }")
private final DoubleListInput firstMaintenanceOperatingHours;
@Keyword(desc = "Working time between one maintenance event and the next for each maintenance cycle",
example = "Object1 MaintenanceOperatingHoursIntervals { 2000 5000 h }")
private final DoubleListInput maintenanceOperatingHoursIntervals;
@Keyword(desc = "Duration of maintenance events based on working hours for each maintenance cycle",
example = "Ship1 MaintenanceOperatingHoursDurations { 24 48 h }")
private final DoubleListInput maintenanceOperatingHoursDurations;
protected IntegerVector maintenanceOperatingHoursPendings; // Number of maintenance periods that are due
protected DoubleVector hoursForNextMaintenanceOperatingHours;
protected double maintenanceStartTime; // Start time of the most recent maintenance
protected double maintenanceEndTime; // End time of the most recent maintenance
protected DoubleVector nextMaintenanceTimes; // next start time for each maintenance
protected double nextMaintenanceDuration; // duration for next maintenance
protected DoubleVector lastScheduledMaintenanceTimes;
@Keyword(desc = "If maintenance has been deferred by the DeferMaintenanceLookAhead keyword " +
"for longer than this time, the maintenance will start even if " +
"there is an object within the lookahead. There must be one entry for each " +
"defined maintenance schedule if DeferMaintenanceLookAhead is used. This" +
"keyword is only used for signal blocks.",
example = "Object1 DeferMaintenanceLimit { 50 50 h }")
private final DoubleListInput deferMaintenanceLimit;
@Keyword(desc = "If the duration of the downtime is longer than this time, equipment will be released",
example = "Object1 DowntimeToReleaseEquipment { 1.0 h }")
protected final DoubleInput downtimeToReleaseEquipment;
@Keyword(desc = "A list of Boolean values corresponding to the maintenance cycles. If a value is TRUE, " +
"then routes/tasks are released before performing the maintenance in the cycle.",
example = "Object1 ReleaseEquipment { TRUE FALSE FALSE }")
protected final BooleanListInput releaseEquipment;
@Keyword(desc = "A list of Boolean values corresponding to the maintenance cycles. If a value is " +
"TRUE, then maintenance in the cycle can start even if the equipment is presently " +
"working.",
example = "Object1 ForceMaintenance { TRUE FALSE FALSE }")
protected final BooleanListInput forceMaintenance;
// Statistics
@Keyword(desc = "If TRUE, then statistics for this object are " +
"included in the main output report.",
example = "Object1 PrintToReport { TRUE }")
private final BooleanInput printToReport;
// States
private static Vector stateList = new Vector( 11, 1 ); // List of valid states
private final HashMap<String, StateRecord> stateMap;
protected double workingHours; // Accumulated working time spent in working states
public static class StateRecord {
String stateName;
int index;
double initializationHours;
double totalHours;
double completedCycleHours;
double currentCycleHours;
double lastStartTimeInState;
double secondLastStartTimeInState;
public StateRecord(String state, int i) {
stateName = state;
index = i;
}
public int getIndex() {
return index;
}
public String getStateName() {
return stateName;
}
public double getTotalHours() {
return totalHours;
}
public double getCompletedCycleHours() {
return completedCycleHours;
}
public double getCurrentCycleHours() {
return currentCycleHours;
}
public double getLastStartTimeInState() {
return lastStartTimeInState;
}
public double getSecondLastStartTimeInState() {
return secondLastStartTimeInState;
}
public void setInitializationHours(double init) {
initializationHours = init;
}
public void setTotalHours(double total) {
totalHours = total;
}
public void setCompletedCycleHours(double hours) {
completedCycleHours = hours;
}
public void setCurrentCycleHours(double hours) {
currentCycleHours = hours;
}
@Override
public String toString() {
return getStateName();
}
public void clearCurrentCycleHours() {
currentCycleHours = 0.0d;
}
}
private double timeOfLastStateChange;
private int numberOfCompletedCycles;
protected double lastHistogramUpdateTime; // Last time at which a histogram was updated for this entity
protected double secondToLastHistogramUpdateTime; // Second to last time at which a histogram was updated for this entity
private StateRecord presentState; // The present state of the entity
protected FileEntity stateReportFile; // The file to store the state information
private String finalLastState = ""; // The final state of the entity (in a sequence of transitional states)
private double timeOfLastPrintedState = 0; // The time that the last state printed in the trace state file
// Graphics
protected final static Color4d breakdownColor = ColourInput.DARK_RED; // Color of the entity in breaking down
protected final static Color4d maintenanceColor = ColourInput.RED; // Color of the entity in maintenance
static {
stateList.addElement( "Idle" );
stateList.addElement( "Working" );
stateList.addElement( "Breakdown" );
stateList.addElement( "Maintenance" );
}
{
maintenanceDurations = new DoubleListInput("MaintenanceDurations", "Maintenance", new DoubleVector());
maintenanceDurations.setValidRange(0.0d, Double.POSITIVE_INFINITY);
maintenanceDurations.setUnits("h");
this.addInput(maintenanceDurations, true, "MaintenanceDuration");
maintenanceIntervals = new DoubleListInput("MaintenanceIntervals", "Maintenance", new DoubleVector());
maintenanceIntervals.setValidRange(0.0d, Double.POSITIVE_INFINITY);
maintenanceIntervals.setUnits("h");
this.addInput(maintenanceIntervals, true, "MaintenanceInterval");
firstMaintenanceTimes = new DoubleListInput("FirstMaintenanceTimes", "Maintenance", new DoubleVector());
firstMaintenanceTimes.setValidRange(0.0d, Double.POSITIVE_INFINITY);
firstMaintenanceTimes.setUnits("h");
this.addInput(firstMaintenanceTimes, true, "FirstMaintenanceTime");
forceMaintenance = new BooleanListInput("ForceMaintenance", "Maintenance", null);
this.addInput(forceMaintenance, true);
releaseEquipment = new BooleanListInput("ReleaseEquipment", "Maintenance", null);
this.addInput(releaseEquipment, true);
availability = new DoubleInput("Reliability", "Breakdowns", 1.0d, 0.0d, 1.0d);
this.addInput(availability, true);
downtimeIATDistribution = new EntityInput<ProbabilityDistribution>(ProbabilityDistribution.class, "DowntimeIATDistribution", "Breakdowns", null);
this.addInput(downtimeIATDistribution, true);
downtimeDurationDistribution = new EntityInput<ProbabilityDistribution>(ProbabilityDistribution.class, "DowntimeDurationDistribution", "Breakdowns", null);
this.addInput(downtimeDurationDistribution, true);
downtimeToReleaseEquipment = new DoubleInput("DowntimeToReleaseEquipment", "Breakdowns", 0.0d, 0.0d, Double.POSITIVE_INFINITY);
this.addInput(downtimeToReleaseEquipment, true);
skipMaintenanceIfOverlap = new BooleanListInput("SkipMaintenanceIfOverlap", "Maintenance", new BooleanVector());
this.addInput(skipMaintenanceIfOverlap, true);
deferMaintenanceLimit = new DoubleListInput("DeferMaintenanceLimit", "Maintenance", null);
deferMaintenanceLimit.setValidRange(0.0d, Double.POSITIVE_INFINITY);
deferMaintenanceLimit.setUnits("h");
this.addInput(deferMaintenanceLimit, true);
sharedMaintenanceList = new EntityListInput<ModelEntity>(ModelEntity.class, "SharedMaintenance", "Maintenance", new ArrayList<ModelEntity>(0));
this.addInput(sharedMaintenanceList, true);
firstMaintenanceOperatingHours = new DoubleListInput("FirstMaintenanceOperatingHours", "Maintenance", new DoubleVector());
firstMaintenanceOperatingHours.setValidRange(0.0d, Double.POSITIVE_INFINITY);
firstMaintenanceOperatingHours.setUnits("h");
this.addInput(firstMaintenanceOperatingHours, true);
maintenanceOperatingHoursDurations = new DoubleListInput("MaintenanceOperatingHoursDurations", "Maintenance", new DoubleVector());
maintenanceOperatingHoursDurations.setValidRange(1e-15, Double.POSITIVE_INFINITY);
maintenanceOperatingHoursDurations.setUnits("h");
this.addInput(maintenanceOperatingHoursDurations, true);
maintenanceOperatingHoursIntervals = new DoubleListInput("MaintenanceOperatingHoursIntervals", "Maintenance", new DoubleVector());
maintenanceOperatingHoursIntervals.setValidRange(1e-15, Double.POSITIVE_INFINITY);
maintenanceOperatingHoursIntervals.setUnits("h");
this.addInput(maintenanceOperatingHoursIntervals, true);
printToReport = new BooleanInput("PrintToReport", "Report", true);
this.addInput(printToReport, true);
}
public ModelEntity() {
lastHistogramUpdateTime = 0.0;
secondToLastHistogramUpdateTime = 0.0;
hoursForNextFailure = 0.0;
iATFailure = 0.0;
maintenancePendings = new IntegerVector( 1, 1 );
maintenanceOperatingHoursPendings = new IntegerVector( 1, 1 );
hoursForNextMaintenanceOperatingHours = new DoubleVector( 1, 1 );
performMaintenanceAfterShipDelayPending = false;
lastScheduledMaintenanceTimes = new DoubleVector();
breakdownStartTime = 0.0;
breakdownEndTime = Double.POSITIVE_INFINITY;
breakdownPending = false;
brokendown = false;
associatedBreakdown = false;
maintenanceStartTime = 0.0;
maintenanceEndTime = Double.POSITIVE_INFINITY;
maintenance = false;
associatedMaintenance = false;
workingHours = 0.0;
stateMap = new HashMap<String, StateRecord>();
StateRecord idle = new StateRecord("Idle", 0);
stateMap.put("idle" , idle);
presentState = idle;
timeOfLastStateChange = getCurrentTime();
idle.lastStartTimeInState = getCurrentTime();
idle.secondLastStartTimeInState = getCurrentTime();
initStateMap();
}
/**
* Clear internal properties
*/
public void clearInternalProperties() {
hoursForNextFailure = 0.0;
performMaintenanceAfterShipDelayPending = false;
breakdownPending = false;
brokendown = false;
associatedBreakdown = false;
maintenance = false;
associatedMaintenance = false;
workingHours = 0.0;
}
@Override
public void validate()
throws InputErrorException {
super.validate();
this.validateMaintenance();
Input.validateIndexedLists(firstMaintenanceOperatingHours.getValue(), maintenanceOperatingHoursIntervals.getValue(), "FirstMaintenanceOperatingHours", "MaintenanceOperatingHoursIntervals");
Input.validateIndexedLists(firstMaintenanceOperatingHours.getValue(), maintenanceOperatingHoursDurations.getValue(), "FirstMaintenanceOperatingHours", "MaintenanceOperatingHoursDurations");
if( getAvailability() < 1.0 ) {
if( getDowntimeDurationDistribution() == null ) {
throw new InputErrorException("When availability is less than one you must define downtimeDurationDistribution in your input file!");
}
}
if( downtimeIATDistribution.getValue() != null ) {
if( getDowntimeDurationDistribution() == null ) {
throw new InputErrorException("When DowntimeIATDistribution is set, DowntimeDurationDistribution must also be set.");
}
}
if( skipMaintenanceIfOverlap.getValue().size() > 0 )
Input.validateIndexedLists(firstMaintenanceTimes.getValue(), skipMaintenanceIfOverlap.getValue(), "FirstMaintenanceTimes", "SkipMaintenanceIfOverlap");
if( releaseEquipment.getValue() != null )
Input.validateIndexedLists(firstMaintenanceTimes.getValue(), releaseEquipment.getValue(), "FirstMaintenanceTimes", "ReleaseEquipment");
if( forceMaintenance.getValue() != null ) {
Input.validateIndexedLists(firstMaintenanceTimes.getValue(), forceMaintenance.getValue(), "FirstMaintenanceTimes", "ForceMaintenance");
}
if(downtimeDurationDistribution.getValue() != null &&
downtimeDurationDistribution.getValue().getMinimumValue() < 0)
throw new InputErrorException("DowntimeDurationDistribution cannot allow negative values");
if(downtimeIATDistribution.getValue() != null &&
downtimeIATDistribution.getValue().getMinimumValue() < 0)
throw new InputErrorException("DowntimeIATDistribution cannot allow negative values");
}
@Override
public void earlyInit() {
super.earlyInit();
if( downtimeDurationDistribution.getValue() != null ) {
downtimeDurationDistribution.getValue().initialize();
}
if( downtimeIATDistribution.getValue() != null ) {
downtimeIATDistribution.getValue().initialize();
}
}
/**
* Runs after initialization period
*/
public void collectInitializationStats() {
for ( StateRecord each : stateMap.values() ) {
each.setInitializationHours( getTotalHoursFor(each) );
each.totalHours = 0.0d;
each.completedCycleHours = 0.0d;
if (each == presentState)
each.setCurrentCycleHours( getCurrentCycleHoursFor(each) );
}
if ( this.isWorking() )
workingHours += getCurrentTime() - timeOfLastStateChange;
timeOfLastStateChange = getCurrentTime();
numberOfCompletedCycles = 0;
}
/**
* Runs when cycle is finished
*/
public void collectCycleStats() {
// finalize cycle for each state record
for ( StateRecord each : stateMap.values() ) {
double hour = each.getCompletedCycleHours();
hour += getCurrentCycleHoursFor(each);
each.setCompletedCycleHours(hour);
each.clearCurrentCycleHours();
if (each == presentState)
each.setTotalHours( getTotalHoursFor(each) );
}
if ( this.isWorking() )
workingHours += getCurrentTime() - timeOfLastStateChange;
timeOfLastStateChange = getCurrentTime();
numberOfCompletedCycles++;
}
/**
* Runs after each report interval
*/
public void clearReportStats() {
// clear totalHours for each state record
for ( StateRecord each : stateMap.values() ) {
each.totalHours = 0.0d;
each.completedCycleHours = 0.0d;
}
numberOfCompletedCycles = 0;
}
public int getNumberOfCompletedCycles() {
return numberOfCompletedCycles;
}
/**
* Clear the current cycle hours
*/
protected void clearCurrentCycleHours() {
// clear current cycle hours for each state record
for ( StateRecord each : stateMap.values() ) {
if (each == presentState)
each.setTotalHours( getTotalHoursFor(each) );
each.clearCurrentCycleHours();
}
if ( this.isWorking() )
workingHours += getCurrentTime() - timeOfLastStateChange;
timeOfLastStateChange = getCurrentTime();
}
public void initStateMap() {
// Populate the hash map for the states and StateRecord
StateRecord idle = getStateRecordFor("Idle");
stateMap.clear();
for (int i = 0; i < getStateList().size(); i++) {
String state = (String)getStateList().get(i);
if ( state.equals("Idle") ) {
idle.index = i;
continue;
}
StateRecord stateRecord = new StateRecord(state, i);
stateMap.put(state.toLowerCase() , stateRecord);
}
stateMap.put("idle", idle);
timeOfLastStateChange = getCurrentTime();
}
public StateRecord getStateRecordFor(String state) {
return stateMap.get(state.toLowerCase());
}
private StateRecord getStateRecordFor(int index) {
String state = (String)getStateList().get(index);
return getStateRecordFor(state);
}
public double getCompletedCycleHoursFor(String state) {
return getStateRecordFor(state).getCompletedCycleHours();
}
public double getCompletedCycleHoursFor(int index) {
return getStateRecordFor(index).getCompletedCycleHours();
}
public double getCompletedCycleHours() {
double total = 0.0d;
for (int i = 0; i < getStateList().size(); i ++)
total += getStateRecordFor(i).getCompletedCycleHours();
return total;
}
public double getTotalHoursFor(int index) {
return getTotalHoursFor( (String) getStateList().get(index) );
}
public double getTotalHoursFor(String state) {
StateRecord rec = getStateRecordFor(state);
return getTotalHoursFor(rec);
}
public double getTotalHoursFor(StateRecord state) {
double hours = state.getTotalHours();
if (presentState == state)
hours += getCurrentTime() - timeOfLastStateChange;
return hours;
}
public double getTotalHours() {
double total = getCurrentTime() - timeOfLastStateChange;
for (int i = 0; i < getNumberOfStates(); i++)
total += getStateRecordFor(i).getTotalHours();
return total;
}
// INPUT
public void validateMaintenance() {
Input.validateIndexedLists(firstMaintenanceTimes.getValue(), maintenanceIntervals.getValue(), "FirstMaintenanceTimes", "MaintenanceIntervals");
Input.validateIndexedLists(firstMaintenanceTimes.getValue(), maintenanceDurations.getValue(), "FirstMaintenanceTimes", "MaintenanceDurations");
for( int i = 0; i < maintenanceIntervals.getValue().size(); i++ ) {
if( maintenanceIntervals.getValue().get( i ) < maintenanceDurations.getValue().get( i ) ) {
throw new InputErrorException("MaintenanceInterval should be greater than MaintenanceDuration (%f) <= (%f)",
maintenanceIntervals.getValue().get(i), maintenanceDurations.getValue().get(i));
}
}
}
// INITIALIZATION METHODS
public void clearStatistics() {
for( int i = 0; i < getMaintenanceOperatingHoursIntervals().size(); i++ ) {
hoursForNextMaintenanceOperatingHours.set( i, hoursForNextMaintenanceOperatingHours.get( i ) - this.getWorkingHours() );
}
// Determine the time for the first breakdown event
/*if ( downtimeIATDistribution == null ) {
if( breakdownSeed != 0 ) {
breakdownRandGen.initialiseWith( breakdownSeed );
hoursForNextFailure = breakdownRandGen.getUniformFrom_To( 0.5*iATFailure, 1.5*iATFailure );
} else {
hoursForNextFailure = getNextBreakdownIAT();
}
}
else {
hoursForNextFailure = getNextBreakdownIAT();
}*/
}
/**
* *!*!*!*! OVERLOAD !*!*!*!*
* Initialize statistics
*/
public void initialize() {
brokendown = false;
maintenance = false;
associatedBreakdown = false;
associatedMaintenance = false;
// Create state trace file if required
if (testFlag(FLAG_TRACESTATE)) {
String fileName = InputAgent.getReportDirectory() + InputAgent.getRunName() + "-" + this.getName() + ".trc";
stateReportFile = new FileEntity( fileName, FileEntity.FILE_WRITE, false );
}
workingHours = 0.0;
// Calculate the average downtime duration if distributions are used
double average = 0.0;
if(getDowntimeDurationDistribution() != null)
average = getDowntimeDurationDistribution().getExpectedValue();
// Calculate the average downtime inter-arrival time
if( (getAvailability() == 1.0 || average == 0.0) ) {
iATFailure = 10.0E10;
}
else {
if( getDowntimeIATDistribution() != null ) {
iATFailure = getDowntimeIATDistribution().getExpectedValue();
// Adjust the downtime inter-arrival time to get the specified availability
if( ! Tester.equalCheckTolerance( iATFailure, ( (average / (1.0 - getAvailability())) - average ) ) ) {
getDowntimeIATDistribution().setValueFactor_For( ( (average / (1.0 - getAvailability())) - average) / iATFailure, this );
iATFailure = getDowntimeIATDistribution().getExpectedValue();
}
}
else {
iATFailure = ( (average / (1.0 - getAvailability())) - average );
}
}
// Determine the time for the first breakdown event
hoursForNextFailure = getNextBreakdownIAT();
this.setPresentState( "Idle" );
brokendown = false;
// Start the maintenance network
if( firstMaintenanceTimes.getValue().size() != 0 ) {
maintenancePendings.fillWithEntriesOf( firstMaintenanceTimes.getValue().size(), 0 );
lastScheduledMaintenanceTimes.fillWithEntriesOf( firstMaintenanceTimes.getValue().size(), Double.POSITIVE_INFINITY );
this.doMaintenanceNetwork();
}
// calculate hours for first operating hours breakdown
for ( int i = 0; i < getMaintenanceOperatingHoursIntervals().size(); i++ ) {
hoursForNextMaintenanceOperatingHours.add( firstMaintenanceOperatingHours.getValue().get( i ) );
maintenanceOperatingHoursPendings.add( 0 );
}
}
// ACCESSOR METHODS
/**
* Return the time at which the most recent maintenance is scheduled to end
*/
public double getMaintenanceEndTime() {
return maintenanceEndTime;
}
/**
* Return the time at which a the most recent breakdown is scheduled to end
*/
public double getBreakdownEndTime() {
return breakdownEndTime;
}
public double getTimeOfLastStateChange() {
return timeOfLastStateChange;
}
/**
* Returns the availability proportion.
*/
public double getAvailability() {
return availability.getValue();
}
public DoubleListInput getFirstMaintenanceTimes() {
return firstMaintenanceTimes;
}
public boolean getPrintToReport() {
return printToReport.getValue();
}
public boolean isBrokendown() {
return brokendown;
}
public boolean isBreakdownPending() {
return breakdownPending;
}
public boolean isInAssociatedBreakdown() {
return associatedBreakdown;
}
public boolean isInMaintenance() {
return maintenance;
}
public boolean isInAssociatedMaintenance() {
return associatedMaintenance;
}
public boolean isInService() {
return ( brokendown || maintenance || associatedBreakdown || associatedMaintenance );
}
public void setBrokendown( boolean bool ) {
brokendown = bool;
this.setPresentState();
}
public void setMaintenance( boolean bool ) {
maintenance = bool;
this.setPresentState();
}
public void setAssociatedBreakdown( boolean bool ) {
associatedBreakdown = bool;
}
public void setAssociatedMaintenance( boolean bool ) {
associatedMaintenance = bool;
}
public ProbabilityDistribution getDowntimeDurationDistribution() {
return downtimeDurationDistribution.getValue();
}
public double getDowntimeToReleaseEquipment() {
return downtimeToReleaseEquipment.getValue();
}
public boolean hasServiceDefined() {
return( maintenanceDurations.getValue().size() > 0 || getDowntimeDurationDistribution() != null );
}
// HOURS AND STATES
/**
* Return true if the entity is working
*/
public boolean isWorking() {
return false;
}
/**
* Returns the present status.
*/
public String getPresentState() {
return presentState.getStateName();
}
public boolean presentStateEquals(String state) {
return getPresentState().equals(state);
}
public boolean presentStateMatches(String state) {
return getPresentState().equalsIgnoreCase(state);
}
public boolean presentStateStartsWith(String prefix) {
return getPresentState().startsWith(prefix);
}
public boolean presentStateEndsWith(String suffix) {
return getPresentState().endsWith(suffix);
}
protected int getPresentStateIndex() {
return presentState.getIndex();
}
public void setPresentState() {}
/**
* Update the hours for the present state and set new timeofLastStateChange
*/
private void collectPresentHours() {
double curTime = getCurrentTime();
if (curTime == timeOfLastStateChange)
return;
double duration = curTime - timeOfLastStateChange;
timeOfLastStateChange = curTime;
presentState.totalHours += duration;
presentState.currentCycleHours += duration;
if (this.isWorking())
workingHours += duration;
}
/**
* Updates the statistics, then sets the present status to be the specified value.
*/
public void setPresentState( String state ) {
if (traceFlag) {
this.trace("setState( " + state + " )");
this.traceLine(" Old State = " + getPresentState());
}
if (presentStateEquals(state))
return;
if (testFlag(FLAG_TRACESTATE)) this.printStateTrace(state);
StateRecord nextState = this.getStateRecordFor(state);
if (nextState == null)
throw new ErrorException(this + " Specified state: " + state + " was not found in the StateList: " + this.getStateList());
collectPresentHours();
nextState.secondLastStartTimeInState = nextState.getLastStartTimeInState();
nextState.lastStartTimeInState = timeOfLastStateChange;
presentState = nextState;
}
/**
* Print that state information on the trace state log file
*/
public void printStateTrace( String state ) {
// First state ever
if( finalLastState.equals("") ) {
finalLastState = state;
stateReportFile.putString(String.format("%.5f %s.setState( \"%s\" ) dt = %s\n",
0.0d, this.getName(), getPresentState(), formatNumber(getCurrentTime())));
stateReportFile.flush();
timeOfLastPrintedState = getCurrentTime();
}
else {
// The final state in a sequence from the previous state change (one step behind)
if ( ! Tester.equalCheckTimeStep( timeOfLastPrintedState, getCurrentTime() ) ) {
stateReportFile.putString(String.format("%.5f %s.setState( \"%s\" ) dt = %s\n",
timeOfLastPrintedState, this.getName(), finalLastState, formatNumber(getCurrentTime() - timeOfLastPrintedState)));
// for( int i = 0; i < stateTraceRelatedModelEntities.size(); i++ ) {
// ModelEntitiy each = (ModelEntitiy) stateTraceRelatedModelEntities.get( i );
// putString( )
stateReportFile.flush();
timeOfLastPrintedState = getCurrentTime();
}
finalLastState = state;
}
}
/**
* Returns the amount of time spent in the specified status.
*/
public double getCurrentCycleHoursFor( String state ) {
StateRecord rec = getStateRecordFor(state);
return getCurrentCycleHoursFor(rec);
}
/**
* Return spent hours for a given state at the index in stateList
*/
public double getCurrentCycleHoursFor(int index) {
StateRecord rec = getStateRecordFor(index);
return getCurrentCycleHoursFor(rec);
}
public double getCurrentCycleHoursFor(StateRecord state) {
double hours = state.getCurrentCycleHours();
if (presentState == state)
hours += getCurrentTime() - timeOfLastStateChange;
return hours;
}
/**
* Set the last time a histogram was updated for this entity
*/
public void setLastHistogramUpdateTime( double time ) {
secondToLastHistogramUpdateTime = lastHistogramUpdateTime;
lastHistogramUpdateTime = time;
}
/**
* Returns the time from the start of the start state to the start of the end state
*/
public double getTimeFromStartState_ToEndState( String startState, String endState) {
// Determine the index of the start state
StateRecord startStateRec = this.getStateRecordFor(startState);
if (startStateRec == null) {
throw new ErrorException("Specified state: %s was not found in the StateList.", startState);
}
// Determine the index of the end state
StateRecord endStateRec = this.getStateRecordFor(endState);
if (endStateRec == null) {
throw new ErrorException("Specified state: %s was not found in the StateList.", endState);
}
// Is the start time of the end state greater or equal to the start time of the start state?
if (endStateRec.getLastStartTimeInState() >= startStateRec.getLastStartTimeInState()) {
// If either time was not in the present cycle, return NaN
if (endStateRec.getLastStartTimeInState() <= lastHistogramUpdateTime ||
startStateRec.getLastStartTimeInState() <= lastHistogramUpdateTime ) {
return Double.NaN;
}
// Return the time from the last start time of the start state to the last start time of the end state
return endStateRec.getLastStartTimeInState() - startStateRec.getLastStartTimeInState();
}
else {
// If either time was not in the present cycle, return NaN
if (endStateRec.getLastStartTimeInState() <= lastHistogramUpdateTime ||
startStateRec.getSecondLastStartTimeInState() <= secondToLastHistogramUpdateTime ) {
return Double.NaN;
}
// Return the time from the second to last start time of the start date to the last start time of the end state
return endStateRec.getLastStartTimeInState() - startStateRec.getSecondLastStartTimeInState();
}
}
/**
* Return the commitment
*/
public double getCommitment() {
return 1.0 - this.getFractionOfTimeForState( "Idle" );
}
/**
* Return the fraction of time for the given status
*/
public double getFractionOfTimeForState( String aState ) {
if( getTotalHours() > 0.0 ) {
return ((this.getTotalHoursFor( aState ) / getTotalHours()) );
}
else {
return 0.0;
}
}
/**
* Return the percentage of time for the given status
*/
public double getPercentageOfTimeForState( String aState ) {
if( getTotalHours() > 0.0 ) {
return ((this.getTotalHoursFor( aState ) / getTotalHours()) * 100.0);
}
else {
return 0.0;
}
}
/**
* Returns the number of hours the entity is in use.
* *!*!*!*! OVERLOAD !*!*!*!*
*/
public double getWorkingHours() {
double hours = 0.0d;
if ( this.isWorking() )
hours = getCurrentTime() - timeOfLastStateChange;
return workingHours + hours;
}
public Vector getStateList() {
return stateList;
}
/**
* Return total number of states
*/
public int getNumberOfStates() {
return stateMap.size();
}
/**
* Return the total hours in current cycle for all the states
*/
public double getCurrentCycleHours() {
double total = getCurrentTime() - timeOfLastStateChange;
for (int i = 0; i < getNumberOfStates(); i++) {
total += getStateRecordFor(i).getCurrentCycleHours();
}
return total;
}
// MAINTENANCE METHODS
/**
* Perform tasks required before a maintenance period
*/
public void doPreMaintenance() {
//@debug@ cr 'Entity should be overloaded' print
}
/**
* Start working again following a breakdown or maintenance period
*/
public void restart() {
//@debug@ cr 'Entity should be overloaded' print
}
/**
* Disconnect routes, release truck assignments, etc. when performing maintenance or breakdown
*/
public void releaseEquipment() {}
public boolean releaseEquipmentForMaintenanceSchedule( int index ) {
if( releaseEquipment.getValue() == null )
return true;
return releaseEquipment.getValue().get( index );
}
public boolean forceMaintenanceSchedule( int index ) {
if( forceMaintenance.getValue() == null )
return false;
return forceMaintenance.getValue().get( index );
}
/**
* Perform all maintenance schedules that are due
*/
public void doMaintenance() {
// scheduled maintenance
for( int index = 0; index < maintenancePendings.size(); index++ ) {
if( this.getMaintenancePendings().get( index ) > 0 ) {
if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index );
this.doMaintenance(index);
}
}
// Operating hours maintenance
for( int index = 0; index < maintenanceOperatingHoursPendings.size(); index++ ) {
if( this.getWorkingHours() > hoursForNextMaintenanceOperatingHours.get( index ) ) {
hoursForNextMaintenanceOperatingHours.set(index, this.getWorkingHours() + getMaintenanceOperatingHoursIntervals().get( index ));
maintenanceOperatingHoursPendings.addAt( 1, index );
this.doMaintenanceOperatingHours(index);
}
}
}
/**
* Perform all the planned maintenance that is due for the given schedule
*/
public void doMaintenance( int index ) {
double wait;
if( masterMaintenanceEntity != null ) {
wait = masterMaintenanceEntity.getMaintenanceDurations().getValue().get( index );
}
else {
wait = this.getMaintenanceDurations().getValue().get( index );
}
if( wait > 0.0 && maintenancePendings.get( index ) != 0 ) {
if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- start of maintenance" );
// Keep track of the start and end of maintenance times
maintenanceStartTime = getCurrentTime();
if( masterMaintenanceEntity != null ) {
maintenanceEndTime = maintenanceStartTime + ( maintenancePendings.get( index ) * masterMaintenanceEntity.getMaintenanceDurations().getValue().get( index ) );
}
else {
maintenanceEndTime = maintenanceStartTime + ( maintenancePendings.get( index ) * maintenanceDurations.getValue().get( index ) );
}
this.setPresentState( "Maintenance" );
maintenance = true;
this.doPreMaintenance();
// Release equipment if necessary
if( this.releaseEquipmentForMaintenanceSchedule( index ) ) {
this.releaseEquipment();
}
while( maintenancePendings.get( index ) != 0 ) {
maintenancePendings.subAt( 1, index );
scheduleWait( wait );
// If maintenance pending goes negative, something is wrong
if( maintenancePendings.get( index ) < 0 ) {
this.error( "ModelEntity.doMaintenance_Wait()", "Maintenace pending should not be negative", "maintenacePending = "+maintenancePendings.get( index ) );
}
}
if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- end of maintenance" );
// The maintenance is over
this.setPresentState( "Idle" );
maintenance = false;
this.restart();
}
}
/**
* Perform all the planned maintenance that is due
*/
public void doMaintenanceOperatingHours( int index ) {
if(maintenanceOperatingHoursPendings.get( index ) == 0 )
return;
if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- start of maintenance" );
// Keep track of the start and end of maintenance times
maintenanceStartTime = getCurrentTime();
maintenanceEndTime = maintenanceStartTime +
(maintenanceOperatingHoursPendings.get( index ) * getMaintenanceOperatingHoursDurationFor(index));
this.setPresentState( "Maintenance" );
maintenance = true;
this.doPreMaintenance();
while( maintenanceOperatingHoursPendings.get( index ) != 0 ) {
//scheduleWait( maintenanceDurations.get( index ) );
scheduleWait( maintenanceEndTime - maintenanceStartTime );
maintenanceOperatingHoursPendings.subAt( 1, index );
// If maintenance pending goes negative, something is wrong
if( maintenanceOperatingHoursPendings.get( index ) < 0 ) {
this.error( "ModelEntity.doMaintenance_Wait()", "Maintenace pending should not be negative", "maintenacePending = "+maintenanceOperatingHoursPendings.get( index ) );
}
}
if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- end of maintenance" );
// The maintenance is over
maintenance = false;
this.setPresentState( "Idle" );
this.restart();
}
/**
* Check if a maintenance is due. if so, try to perform the maintenance
*/
public boolean checkMaintenance() {
if( traceFlag ) this.trace( "checkMaintenance()" );
if( checkOperatingHoursMaintenance() ) {
return true;
}
// List of all entities going to maintenance
ArrayList<ModelEntity> sharedMaintenanceEntities;
// This is not a master maintenance entity
if( masterMaintenanceEntity != null ) {
sharedMaintenanceEntities = masterMaintenanceEntity.getSharedMaintenanceList();
}
// This is a master maintenance entity
else {
sharedMaintenanceEntities = getSharedMaintenanceList();
}
// If this entity is in shared maintenance relation with a group of entities
if( sharedMaintenanceEntities.size() > 0 || masterMaintenanceEntity != null ) {
// Are all entities in the group ready for maintenance
if( this.areAllEntitiesAvailable() ) {
// For every entity in the shared maintenance list plus the master maintenance entity
for( int i=0; i <= sharedMaintenanceEntities.size(); i++ ) {
ModelEntity aModel;
// Locate master maintenance entity( after all entity in shared maintenance list have been taken care of )
if( i == sharedMaintenanceEntities.size() ) {
// This entity is manster maintenance entity
if( masterMaintenanceEntity == null ) {
aModel = this;
}
// This entity is on the shared maintenannce list of the master maintenance entity
else {
aModel = masterMaintenanceEntity;
}
}
// Next entity in the shared maintenance list
else {
aModel = sharedMaintenanceEntities.get( i );
}
// Check for aModel maintenances
for( int index = 0; index < maintenancePendings.size(); index++ ) {
if( aModel.getMaintenancePendings().get( index ) > 0 ) {
if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index );
aModel.startProcess("doMaintenance", index);
}
}
}
return true;
}
else {
return false;
}
}
// This block is maintained indipendently
else {
// Check for maintenances
for( int i = 0; i < maintenancePendings.size(); i++ ) {
if( maintenancePendings.get( i ) > 0 ) {
if( this.canStartMaintenance( i ) ) {
if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + i );
this.startProcess("doMaintenance", i);
return true;
}
}
}
}
return false;
}
/**
* Determine how many hours of maintenance is scheduled between startTime and endTime
*/
public double getScheduledMaintenanceHoursForPeriod( double startTime, double endTime ) {
if( traceFlag ) this.trace("Handler.getScheduledMaintenanceHoursForPeriod( "+startTime+", "+endTime+" )" );
double totalHours = 0.0;
double firstTime = 0.0;
// Add on hours for all pending maintenance
for( int i=0; i < maintenancePendings.size(); i++ ) {
totalHours += maintenancePendings.get( i ) * maintenanceDurations.getValue().get( i );
}
if( traceFlag ) this.traceLine( "Hours of pending maintenances="+totalHours );
// Add on hours for all maintenance scheduled to occur in the given period from startTime to endTime
for( int i=0; i < maintenancePendings.size(); i++ ) {
// Find the first time that maintenance is scheduled after startTime
firstTime = firstMaintenanceTimes.getValue().get( i );
while( firstTime < startTime ) {
firstTime += maintenanceIntervals.getValue().get( i );
}
if( traceFlag ) this.traceLine(" first time maintenance "+i+" is scheduled after startTime= "+firstTime );
// Now have the first maintenance start time after startTime
// Add all maintenances that lie in the given interval
while( firstTime < endTime ) {
if( traceFlag ) this.traceLine(" Checking for maintenances for period:"+firstTime+" to "+endTime );
// Add the maintenance
totalHours += maintenanceDurations.getValue().get( i );
// Update the search period
endTime += maintenanceDurations.getValue().get( i );
// Look for next maintenance in new interval
firstTime += maintenanceIntervals.getValue().get( i );
if( traceFlag ) this.traceLine(" Adding Maintenance duration = "+maintenanceDurations.getValue().get( i ) );
}
}
// Return the total hours of maintenance scheduled from startTime to endTime
if( traceFlag ) this.traceLine( "Maintenance hours to add= "+totalHours );
return totalHours;
}
public boolean checkOperatingHoursMaintenance() {
if( traceFlag ) this.trace("checkOperatingHoursMaintenance()");
// Check for maintenances
for( int i = 0; i < getMaintenanceOperatingHoursIntervals().size(); i++ ) {
// If the entity is not available, maintenance cannot start
if( ! this.canStartMaintenance( i ) )
continue;
if( this.getWorkingHours() > hoursForNextMaintenanceOperatingHours.get( i ) ) {
hoursForNextMaintenanceOperatingHours.set(i, (this.getWorkingHours() + getMaintenanceOperatingHoursIntervals().get( i )));
maintenanceOperatingHoursPendings.addAt( 1, i );
if( traceFlag ) this.trace( "Starting Maintenance Operating Hours Schedule : " + i );
this.startProcess("doMaintenanceOperatingHours", i);
return true;
}
}
return false;
}
/**
* Wrapper method for doMaintenance_Wait.
*/
public void doMaintenanceNetwork() {
this.startProcess("doMaintenanceNetwork_Wait");
}
/**
* Network for planned maintenance.
* This method should be called in the initialize method of the specific entity.
*/
public void doMaintenanceNetwork_Wait() {
// Initialize schedules
for( int i=0; i < maintenancePendings.size(); i++ ) {
maintenancePendings.set( i, 0 );
}
nextMaintenanceTimes = new DoubleVector(firstMaintenanceTimes.getValue());
nextMaintenanceDuration = 0;
// Find the next maintenance event
int index = 0;
double earliestTime = Double.POSITIVE_INFINITY;
for( int i=0; i < nextMaintenanceTimes.size(); i++ ) {
double time = nextMaintenanceTimes.get( i );
if( Tester.lessCheckTolerance( time, earliestTime ) ) {
earliestTime = time;
index = i;
nextMaintenanceDuration = maintenanceDurations.getValue().get( i );
}
}
// Make sure that maintenance for entities on the shared list are being called after those entities have been initialize (AT TIME ZERO)
scheduleLastLIFO();
while( true ) {
double dt = earliestTime - getCurrentTime();
// Wait for the maintenance check time
if( dt > Process.getEventTolerance() ) {
scheduleWait( dt );
}
// Increment the number of maintenances due for the entity
maintenancePendings.addAt( 1, index );
// If this is a master maintenance entity
if (getSharedMaintenanceList().size() > 0) {
// If all the entities on the shared list are ready for maintenance
if( this.areAllEntitiesAvailable() ) {
// Put this entity to maintenance
if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index );
this.startProcess("doMaintenance", index);
}
}
// If this entity is maintained independently
else {
// Do maintenance if possible
if( ! this.isInService() && this.canStartMaintenance( index ) ) {
// if( traceFlag ) this.trace( "doMaintenanceNetwork_Wait: Starting Maintenance. PresentState = "+presentState+" IsAvailable? = "+this.isAvailable() );
if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index );
this.startProcess("doMaintenance", index);
}
// Keep track of the time the maintenance was attempted
else {
lastScheduledMaintenanceTimes.set( index, getCurrentTime() );
// If skipMaintenance was defined, cancel the maintenance
if( this.shouldSkipMaintenance( index ) ) {
// if a different maintenance is due, cancel this maintenance
boolean cancelMaintenance = false;
for( int i=0; i < maintenancePendings.size(); i++ ) {
if( i != index ) {
if( maintenancePendings.get( i ) > 0 ) {
cancelMaintenance = true;
break;
}
}
}
if( cancelMaintenance || this.isInMaintenance() ) {
maintenancePendings.subAt( 1, index );
}
}
// Do a check after the limit has expired
if( this.getDeferMaintenanceLimit( index ) > 0.0 ) {
this.startProcess( "scheduleCheckMaintenance", this.getDeferMaintenanceLimit( index ) );
}
}
}
// Determine the next maintenance time
nextMaintenanceTimes.addAt( maintenanceIntervals.getValue().get( index ), index );
// Find the next maintenance event
index = 0;
earliestTime = Double.POSITIVE_INFINITY;
for( int i=0; i < nextMaintenanceTimes.size(); i++ ) {
double time = nextMaintenanceTimes.get( i );
if( Tester.lessCheckTolerance( time, earliestTime ) ) {
earliestTime = time;
index = i;
nextMaintenanceDuration = maintenanceDurations.getValue().get( i );
}
}
}
}
public double getDeferMaintenanceLimit( int index ) {
if( deferMaintenanceLimit.getValue() == null )
return 0.0d;
return deferMaintenanceLimit.getValue().get( index );
}
public void scheduleCheckMaintenance( double wait ) {
scheduleWait( wait );
this.checkMaintenance();
}
public boolean shouldSkipMaintenance( int index ) {
if( skipMaintenanceIfOverlap.getValue().size() == 0 )
return false;
return skipMaintenanceIfOverlap.getValue().get( index );
}
/**
* Return TRUE if there is a pending maintenance for any schedule
*/
public boolean isMaintenancePending() {
for( int i = 0; i < maintenancePendings.size(); i++ ) {
if( maintenancePendings.get( i ) > 0 ) {
return true;
}
}
for( int i = 0; i < hoursForNextMaintenanceOperatingHours.size(); i++ ) {
if( this.getWorkingHours() > hoursForNextMaintenanceOperatingHours.get( i ) ) {
return true;
}
}
return false;
}
public boolean isForcedMaintenancePending() {
if( forceMaintenance.getValue() == null )
return false;
for( int i = 0; i < maintenancePendings.size(); i++ ) {
if( maintenancePendings.get( i ) > 0 && forceMaintenance.getValue().get(i) ) {
return true;
}
}
return false;
}
public ArrayList<ModelEntity> getSharedMaintenanceList () {
return sharedMaintenanceList.getValue();
}
public IntegerVector getMaintenancePendings () {
return maintenancePendings;
}
public DoubleListInput getMaintenanceDurations() {
return maintenanceDurations;
}
/**
* Return the start of the next scheduled maintenance time if not in maintenance,
* or the start of the current scheduled maintenance time if in maintenance
*/
public double getNextMaintenanceStartTime() {
if( nextMaintenanceTimes == null )
return Double.POSITIVE_INFINITY;
else
return nextMaintenanceTimes.getMin();
}
/**
* Return the duration of the next maintenance event (assuming only one pending)
*/
public double getNextMaintenanceDuration() {
return nextMaintenanceDuration;
}
// Shows if an Entity would ever go on service
public boolean hasServiceScheduled() {
if( firstMaintenanceTimes.getValue().size() != 0 || masterMaintenanceEntity != null ) {
return true;
}
return false;
}
public void setMasterMaintenanceBlock( ModelEntity aModel ) {
masterMaintenanceEntity = aModel;
}
// BREAKDOWN METHODS
/**
* No Comments Given.
*/
public void calculateTimeOfNextFailure() {
hoursForNextFailure = (this.getWorkingHours() + this.getNextBreakdownIAT());
}
/**
* Activity Network for Breakdowns.
*/
public void doBreakdown() {
}
/**
* Prints the header for the entity's state list.
* @return bottomLine contains format for each column of the bottom line of the group report
*/
public IntegerVector printUtilizationHeaderOn( FileEntity anOut ) {
IntegerVector bottomLine = new IntegerVector();
if( getStateList().size() != 0 ) {
anOut.putStringTabs( "Name", 1 );
bottomLine.add( ReportAgent.BLANK );
int doLoop = getStateList().size();
for( int x = 0; x < doLoop; x++ ) {
String state = (String)getStateList().get( x );
anOut.putStringTabs( state, 1 );
bottomLine.add( ReportAgent.AVERAGE_PCT_ONE_DEC );
}
anOut.newLine();
}
return bottomLine;
}
/**
* Print the entity's name and percentage of hours spent in each state.
* @return columnValues are the values for each column in the group report (0 if the value is a String)
*/
public DoubleVector printUtilizationOn( FileEntity anOut ) {
double total;
DoubleVector columnValues = new DoubleVector();
if( getNumberOfStates() != 0 ) {
total = getTotalHours();
if( !(total == 0.0) ) {
anOut.putStringTabs( getName(), 1 );
columnValues.add( 0.0 );
for( int i = 0; i < getNumberOfStates(); i++ ) {
double value = getTotalHoursFor( i ) / total;
anOut.putDoublePercentWithDecimals( value, 1 );
anOut.putTabs( 1 );
columnValues.add( value );
}
anOut.newLine();
}
}
return columnValues;
}
/**
* This method must be overridden in any subclass of ModelEntity.
*/
public boolean isAvailable() {
throw new ErrorException( "Must override isAvailable in any subclass of ModelEntity." );
}
/**
* This method must be overridden in any subclass of ModelEntity.
*/
public boolean canStartMaintenance( int index ) {
return isAvailable();
}
/**
* This method must be overridden in any subclass of ModelEntity.
*/
public boolean canStartForcedMaintenance() {
return isAvailable();
}
/**
* This method must be overridden in any subclass of ModelEntity.
*/
public boolean areAllEntitiesAvailable() {
throw new ErrorException( "Must override areAllEntitiesAvailable in any subclass of ModelEntity." );
}
/**
* Return the time of the next breakdown duration
*/
public double getBreakdownDuration() {
// if( traceFlag ) this.trace( "getBreakdownDuration()" );
// If a distribution was specified, then select a duration randomly from the distribution
if ( getDowntimeDurationDistribution() != null ) {
return getDowntimeDurationDistribution().nextValue();
}
else {
return 0.0;
}
}
/**
* Return the time of the next breakdown IAT
*/
public double getNextBreakdownIAT() {
if( getDowntimeIATDistribution() != null ) {
return getDowntimeIATDistribution().nextValue();
}
else {
return iATFailure;
}
}
public double getHoursForNextFailure() {
return hoursForNextFailure;
}
public void setHoursForNextFailure( double hours ) {
hoursForNextFailure = hours;
}
/**
Returns a vector of strings describing the ModelEntity.
Override to add details
@return Vector - tab delimited strings describing the DisplayEntity
**/
@Override
public Vector getInfo() {
Vector info = super.getInfo();
info.add( String.format("Present State\t%s", getPresentState()) );
return info;
}
protected DoubleVector getMaintenanceOperatingHoursIntervals() {
return maintenanceOperatingHoursIntervals.getValue();
}
protected double getMaintenanceOperatingHoursDurationFor(int index) {
return maintenanceOperatingHoursDurations.getValue().get(index);
}
protected ProbabilityDistribution getDowntimeIATDistribution() {
return downtimeIATDistribution.getValue();
}
} |
package courgette.runtime;
import cucumber.api.CucumberOptions;
import cucumber.runtime.model.CucumberFeature;
import java.io.File;
import java.net.URL;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import static java.util.Arrays.asList;
import static java.util.Arrays.copyOf;
public class CourgetteRuntimeOptions {
private final CourgetteProperties courgetteProperties;
private final CucumberFeature cucumberFeature;
private final CucumberOptions cucumberOptions;
private final String reportTargetDir;
private List<String> runtimeOptions = new ArrayList<>();
private String rerunFile;
private String cucumberResourcePath;
private final int instanceId = UUID.randomUUID().hashCode();
public CourgetteRuntimeOptions(CourgetteProperties courgetteProperties, CucumberFeature cucumberFeature) {
this.courgetteProperties = courgetteProperties;
this.cucumberFeature = cucumberFeature;
this.cucumberOptions = courgetteProperties.getCourgetteOptions().cucumberOptions();
this.cucumberResourcePath = cucumberFeature.getUri();
this.reportTargetDir = courgetteProperties.getCourgetteOptions().reportTargetDir();
createRuntimeOptions(cucumberOptions, cucumberResourcePath).forEach((key, value) -> runtimeOptions.addAll(value));
}
public CourgetteRuntimeOptions(CourgetteProperties courgetteProperties) {
this.courgetteProperties = courgetteProperties;
this.cucumberOptions = courgetteProperties.getCourgetteOptions().cucumberOptions();
this.cucumberFeature = null;
this.reportTargetDir = courgetteProperties.getCourgetteOptions().reportTargetDir();
createRuntimeOptions(cucumberOptions, null).forEach((key, value) -> runtimeOptions.addAll(value));
}
public String[] getRuntimeOptions() {
return copyOf(runtimeOptions.toArray(), runtimeOptions.size(), String[].class);
}
public Map<String, List<String>> mapRuntimeOptions() {
return createRuntimeOptions(cucumberOptions, cucumberResourcePath);
}
public String getRerunFile() {
return rerunFile;
}
public String getCucumberRerunFile() {
final String cucumberRerunFile = cucumberRerunPlugin.apply(courgetteProperties);
if (cucumberRerunFile == null) {
return getRerunFile();
}
return cucumberRerunFile;
}
public List<String> getReportJsFiles() {
final List<String> reportFiles = new ArrayList<>();
runtimeOptions.forEach(option -> {
if (option != null && isReportPlugin.test(option)) {
String reportFile = option.substring(option.indexOf(":") + 1);
if (reportFile.endsWith(".html")) {
reportFile = reportFile + "/report.js";
}
reportFiles.add(reportFile);
}
});
return reportFiles;
}
public String getCourgetteReportJson() {
return String.format("%s/courgette-report/data/report.json", reportTargetDir);
}
@SuppressWarnings("deprecation")
private Map<String, List<String>> createRuntimeOptions(CucumberOptions cucumberOptions, String path) {
final Map<String, List<String>> runtimeOptions = new HashMap<>();
runtimeOptions.put("--glue", optionParser.apply("--glue", envCucumberOptionParser.apply("glue", cucumberOptions.glue())));
runtimeOptions.put("--tags", optionParser.apply("--tags", envCucumberOptionParser.apply("tags", cucumberOptions.tags())));
runtimeOptions.put("--plugin", optionParser.apply("--plugin", parsePlugins(envCucumberOptionParser.apply("plugin", cucumberOptions.plugin()))));
runtimeOptions.put("--format", optionParser.apply("--format", cucumberOptions.format()));
runtimeOptions.put("--name", optionParser.apply("--name", envCucumberOptionParser.apply("name", cucumberOptions.name())));
runtimeOptions.put("--junit", optionParser.apply("--junit", envCucumberOptionParser.apply("junit", cucumberOptions.junit())));
runtimeOptions.put("--snippets", optionParser.apply("--snippets", cucumberOptions.snippets()));
runtimeOptions.put("--dryRun", Collections.singletonList(cucumberOptions.dryRun() ? "--dry-run" : "--no-dry-run"));
runtimeOptions.put("--strict", Collections.singletonList(cucumberOptions.strict() ? "--strict" : "--no-strict"));
runtimeOptions.put("--monochrome", Collections.singletonList(cucumberOptions.monochrome() ? "--monochrome" : "--no-monochrome"));
runtimeOptions.put(null, featureParser.apply(cucumberOptions.features(), path));
runtimeOptions.values().removeIf(Objects::isNull);
return runtimeOptions;
}
private BiFunction<String, String[], String[]> envCucumberOptionParser = (systemPropertyName, cucumberOptions) -> {
String cucumberOption = System.getProperty("cucumber." + systemPropertyName);
if (cucumberOption != null) {
final List<String> options = new ArrayList<>();
Arrays.stream(cucumberOption.split(",")).forEach(t -> options.add(t.trim()));
String[] cucumberOptionArray = new String[options.size()];
return options.toArray(cucumberOptionArray);
}
return cucumberOptions;
};
private String getMultiThreadRerunFile() {
return getTempDirectory() + courgetteProperties.getSessionId() + "_rerun_" + getFeatureId(cucumberFeature) + ".txt";
}
private String getMultiThreadReportFile() {
return getTempDirectory() + courgetteProperties.getSessionId() + "_thread_report_" + getFeatureId(cucumberFeature);
}
private String getFeatureId(CucumberFeature cucumberFeature) {
return String.format("%s_%s", cucumberFeature.getGherkinFeature().getFeature().hashCode(), instanceId);
}
private Function<CourgetteProperties, String> cucumberRerunPlugin = (courgetteProperties) -> {
final String rerunPlugin = Arrays.stream(courgetteProperties.getCourgetteOptions()
.cucumberOptions()
.plugin()).filter(p -> p.startsWith("rerun")).findFirst().orElse(null);
if (rerunPlugin != null) {
return rerunPlugin.substring(rerunPlugin.indexOf(":") + 1);
}
return null;
};
private final Predicate<String> isReportPlugin = (plugin) -> plugin.startsWith("html:") || plugin.startsWith("json:");
private String[] parsePlugins(String[] plugins) {
List<String> pluginList = new ArrayList<>();
if (plugins.length == 0) {
plugins = new String[]{"json:" + getCourgetteReportJson()};
}
asList(plugins).forEach(plugin -> {
if (isReportPlugin.test(plugin)) {
if (cucumberFeature != null) {
pluginList.add(plugin);
String extension = plugin.substring(0, plugin.indexOf(":"));
if (!extension.equals("")) {
final String reportPath = String.format("%s:%s.%s", extension, getMultiThreadReportFile(), extension);
pluginList.add(reportPath);
}
} else {
pluginList.add(plugin);
}
} else {
pluginList.add(plugin);
}
});
Predicate<List<String>> alreadyAddedRerunPlugin = (addedPlugins) -> addedPlugins.stream().anyMatch(p -> p.startsWith("rerun:"));
if (!alreadyAddedRerunPlugin.test(pluginList)) {
if (cucumberFeature != null) {
rerunFile = getMultiThreadRerunFile();
} else {
final String cucumberRerunFile = cucumberRerunPlugin.apply(courgetteProperties);
rerunFile = cucumberRerunFile != null ? cucumberRerunFile : String.format("%s/courgette-rerun.txt", reportTargetDir);
}
pluginList.add("rerun:" + rerunFile);
}
if (pluginList.stream().noneMatch(plugin -> plugin.contains(getCourgetteReportJson()))) {
pluginList.add("json:" + getCourgetteReportJson());
}
return copyOf(pluginList.toArray(), pluginList.size(), String[].class);
}
private BiFunction<String, Object, List<String>> optionParser = (name, options) -> {
final List<String> runOptions = new ArrayList<>();
final Boolean isStringArray = options instanceof String[];
if (options == null || (isStringArray && ((String[]) options).length == 0)) {
return runOptions;
}
if (isStringArray) {
final String[] optionArray = (String[]) options;
asList(asList(optionArray).toString().split(","))
.forEach(value -> {
runOptions.add(name);
runOptions.add(value.trim().replace("[", "").replace("]", ""));
});
} else {
if (name != null) {
runOptions.add(name);
}
runOptions.add(options.toString());
}
return runOptions;
};
private BiFunction<String, String, String> resourceFinder = (resourcePath, featurePath) -> {
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
final String[] resourceFolders = resourcePath.split("/");
if (resourcePath.equals(featurePath)) {
return resourcePath;
}
Integer startIndex = featurePath.indexOf(resourceFolders[resourceFolders.length - 1]);
if (startIndex > -1) {
startIndex = startIndex + (resourceFolders[resourceFolders.length - 1].length() + 1);
} else {
startIndex = 0;
}
String resourceName = featurePath.substring(startIndex);
if (resourceFolders.length > 0) {
final StringBuilder resourcePathBuilder = new StringBuilder();
for (int i = resourceFolders.length - 1; i >= 0; i
resourcePathBuilder.insert(0, String.format("%s/", resourceFolders[i]));
final URL resource = classLoader.getResource(String.format("%s%s", resourcePathBuilder.toString(), resourceName));
if (resource != null) {
return resourcePathBuilder.toString();
}
}
}
return null;
};
private BiFunction<String[], String, List<String>> featureParser = (resourceFeaturePaths, featurePath) -> {
final List<String> featurePaths = new ArrayList<>();
if (featurePath != null) {
for (String resourceFeaturePath : resourceFeaturePaths) {
final String resource = resourceFinder.apply(resourceFeaturePath, featurePath);
if (resource != null) {
if (featurePath.startsWith(resourceFeaturePath)) {
featurePaths.add(featurePath);
} else {
featurePaths.add(String.format("%s/%s", resourceFeaturePath, featurePath));
}
return featurePaths;
}
}
}
featurePaths.addAll(Arrays.asList(resourceFeaturePaths));
return featurePaths;
};
private String getTempDirectory() {
final String fileSeparator = File.separator;
final String tmpDir = System.getProperty("java.io.tmpdir");
if (!tmpDir.endsWith(fileSeparator)) {
return tmpDir + fileSeparator;
}
return tmpDir;
}
} |
package crazypants.enderio.gui;
import javax.annotation.Nonnull;
import com.enderio.core.api.client.gui.IGuiScreen;
import com.enderio.core.client.gui.button.CycleButton;
import crazypants.enderio.Lang;
import crazypants.enderio.machine.interfaces.IRedstoneModeControlable;
import crazypants.enderio.machine.modes.PacketRedstoneMode;
import crazypants.enderio.machine.modes.RedstoneControlMode;
import crazypants.enderio.network.PacketHandler;
import net.minecraft.tileentity.TileEntity;
public class RedstoneModeButton<T extends TileEntity & IRedstoneModeControlable> extends CycleButton<RedstoneControlMode.IconHolder> {
private @Nonnull IRedstoneModeControlable model;
private T te;
public RedstoneModeButton(@Nonnull IGuiScreen gui, int id, int x, int y, @Nonnull IRedstoneModeControlable model) {
super(gui, id, x, y, RedstoneControlMode.IconHolder.class);
this.model = model;
setModeRaw(RedstoneControlMode.IconHolder.getFromMode(model.getRedstoneControlMode()));
}
public RedstoneModeButton(@Nonnull IGuiScreen gui, int id, int x, int y, @Nonnull T te) {
this(gui, id, x, y, (IRedstoneModeControlable) te);
this.te = te;
}
public RedstoneControlMode.IconHolder setModeRaw(@Nonnull RedstoneControlMode.IconHolder newMode) {
super.setMode(newMode);
setToolTip(Lang.GUI_REDSTONE_MODE.get(), getMode().getTooltip()); // forces our behavior
return getMode();
}
@Override
public RedstoneControlMode.IconHolder setMode(@Nonnull RedstoneControlMode.IconHolder newMode) {
setModeRaw(newMode);
model.setRedstoneControlMode(getMode().getMode());
if (te != null) {
PacketHandler.INSTANCE.sendToServer(new PacketRedstoneMode(te));
}
return getMode();
}
} |
package cz.muni.fi.jboss.migration;
import cz.muni.fi.jboss.migration.actions.CliCommandAction;
import cz.muni.fi.jboss.migration.actions.IMigrationAction;
import cz.muni.fi.jboss.migration.conf.AS7Config;
import cz.muni.fi.jboss.migration.conf.Configuration;
import cz.muni.fi.jboss.migration.conf.GlobalConfiguration;
import cz.muni.fi.jboss.migration.ex.ActionException;
import cz.muni.fi.jboss.migration.ex.CliBatchException;
import cz.muni.fi.jboss.migration.ex.InitMigratorsExceptions;
import cz.muni.fi.jboss.migration.ex.LoadMigrationException;
import cz.muni.fi.jboss.migration.ex.MigrationException;
import cz.muni.fi.jboss.migration.migrators.connectionFactories.ResAdapterMigrator;
import cz.muni.fi.jboss.migration.migrators.dataSources.DatasourceMigrator;
import cz.muni.fi.jboss.migration.migrators.logging.LoggingMigrator;
import cz.muni.fi.jboss.migration.migrators.security.SecurityMigrator;
import cz.muni.fi.jboss.migration.migrators.server.ServerMigrator;
import cz.muni.fi.jboss.migration.spi.IMigrator;
import cz.muni.fi.jboss.migration.utils.AS7CliUtils;
import cz.muni.fi.jboss.migration.utils.Utils;
import cz.muni.fi.jboss.migration.utils.as7.BatchFailure;
import cz.muni.fi.jboss.migration.utils.as7.BatchedCommandWithAction;
import org.apache.commons.collections.map.MultiValueMap;
import org.eclipse.persistence.exceptions.JAXBException;
import org.jboss.as.cli.batch.BatchedCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.UnknownHostException;
import java.util.*;
import org.jboss.as.controller.client.ModelControllerClient;
/**
* Controls the core migration processes.
*
* TODO: Perhaps leave init() and doMigration() in here
* and separate the other methods to a MigrationService{} ?
*
* @author Roman Jakubco
*/
public class MigratorEngine {
private static final Logger log = LoggerFactory.getLogger(MigratorEngine.class);
private Configuration config;
private MigrationContext ctx;
private List<IMigrator> migrators;
public MigratorEngine( Configuration config ) throws InitMigratorsExceptions {
this.config = config;
this.init();
this.resetContext();
}
private void resetContext() {
this.ctx = new MigrationContext();
}
/**
* Initializes this Migrator, especially instantiates the IMigrators.
*/
private void init() throws InitMigratorsExceptions {
// Find IMigrator implementations.
List<Class<? extends IMigrator>> migratorClasses = findMigratorClasses();
// Initialize migrator instances.
Map<Class<? extends IMigrator>, IMigrator> migratorsMap =
createMigrators( migratorClasses, config.getGlobal(), null);
this.migrators = new ArrayList(migratorsMap.values());
// For each migrator (AKA module, AKA plugin)...
for( IMigrator mig : this.migrators ){
// Supply some references.
mig.setGlobalConfig( this.config.getGlobal() );
// Let migrators process module-specific args.
for( Configuration.ModuleSpecificProperty moduleOption : config.getModuleConfigs() ){
mig.examineConfigProperty( moduleOption );
}
}
}// init()
/**
* Instantiate the plugins.
*/
private static Map<Class<? extends IMigrator>, IMigrator> createMigrators(
List<Class<? extends IMigrator>> migratorClasses,
GlobalConfiguration globalConfig,
MultiValueMap config
) throws InitMigratorsExceptions {
Map<Class<? extends IMigrator>, IMigrator> migs = new HashMap<>();
List<Exception> exs = new LinkedList<>();
for( Class<? extends IMigrator> cls : migratorClasses ){
try {
//IMigrator mig = cls.newInstance();
//GlobalConfiguration globalConfig, MultiValueMap config
Constructor<? extends IMigrator> ctor = cls.getConstructor(GlobalConfiguration.class, MultiValueMap.class);
IMigrator mig = ctor.newInstance(globalConfig, config);
migs.put(cls, mig);
}
catch( NoSuchMethodException ex ){
String msg = cls.getName() + " doesn't have constructor ...(GlobalConfiguration globalConfig, MultiValueMap config).";
log.error( msg );
exs.add( new MigrationException(msg) );
}
catch( InvocationTargetException | InstantiationException | IllegalAccessException ex) {
log.error("Failed instantiating " + cls.getSimpleName() + ": " + ex.toString());
log.debug("Stack trace: ", ex);
exs.add(ex);
}
}
if( ! exs.isEmpty() ){
throw new InitMigratorsExceptions(exs);
}
return migs;
}// createMigrators()
/**
* Finds the implementations of the IMigrator.
* TODO: Implement scanning for classes.
*/
private static List<Class<? extends IMigrator>> findMigratorClasses() {
LinkedList<Class<? extends IMigrator>> migratorClasses = new LinkedList();
migratorClasses.add( SecurityMigrator.class );
migratorClasses.add( ServerMigrator.class );
migratorClasses.add( DatasourceMigrator.class );
migratorClasses.add( ResAdapterMigrator.class );
migratorClasses.add( LoggingMigrator.class );
return migratorClasses;
}
public void doMigration() throws MigrationException {
log.info("Commencing migration.");
this.resetContext();
AS7Config as7Config = config.getGlobal().getAS7Config();
// Parse AS 7 config. MIGR-31 OK
File as7configFile = new File(as7Config.getConfigFilePath());
try {
DocumentBuilder db = Utils.createXmlDocumentBuilder();
Document doc = db.parse(as7configFile);
ctx.setAS7ConfigXmlDoc(doc);
// TODO: Do backup at file level, instead of parsing and writing back.
// And rework it in general. MIGR-23.
doc = db.parse(as7configFile);
ctx.setAs7ConfigXmlDocOriginal(doc);
}
catch ( SAXException | IOException ex ) {
throw new MigrationException("Failed loading AS 7 config from " + as7configFile, ex );
}
// MIGR-31 - The new way.
String message = null;
try {
// Load the source server config.
message = "Failed loading AS 5 config from " + as7configFile;
this.loadAS5Data();
// Open an AS 7 management client connection.
openManagementClient();
// Ask all the migrators to create the actions to be performed.
message = "Failed preparing the migration actions.";
this.prepareActions();
message = "Migration actions validation failed.";
this.preValidateActions();
message = "Failed creating backups for the migration actions.";
this.backupActions();
message = "Failed performing the migration actions.";
this.performActions();
message = "Verification of migration actions results failed.";
this.postValidateActions();
// Close the AS 7 management client connection.
closeManagementClient();
}
catch( MigrationException ex ) {
this.rollbackActionsWhichWerePerformed();
// Build up a description.
String description = "";
if( ex instanceof ActionException ){
IMigrationAction action = ((ActionException)ex).getAction();
description =
"\n Migration action which caused the failure: "
+ " (from " + action.getFromMigrator().getSimpleName() + ")"
+ "\n " + action.toDescription();
if( action.getOriginMessage() != null )
description += "\n Purpose of the action: " + action.getOriginMessage();
}
throw new MigrationException( message
+ "\n " + ex.getMessage()
+ description, ex );
}
finally {
this.cleanBackupsIfAny();
}
}// migrate()
/**
* Ask all the migrators to create the actions to be performed; stores them in the context.
*/
private void prepareActions() throws MigrationException {
log.debug("====== prepareActions() ========");
// Call all migrators to create their actions.
try {
for (IMigrator mig : this.migrators) {
log.debug(" Preparing actions with " + mig.getClass().getSimpleName());
mig.createActions(this.ctx);
}
} catch (JAXBException e) {
throw new MigrationException(e);
}
// TODO: Additional logic to filter out duplicated file copying etc.
}
/*
* Actions methods.
*/
private void preValidateActions() throws MigrationException {
log.debug("======== preValidateActions() ========");
List<IMigrationAction> actions = ctx.getActions();
for( IMigrationAction action : actions ) {
action.setMigrationContext(ctx);
action.preValidate();
}
}
private void backupActions() throws MigrationException {
log.debug("======== backupActions() ========");
List<IMigrationAction> actions = ctx.getActions();
for( IMigrationAction action : actions ) {
action.backup();
}
}
/**
* Performs the actions.
* Should do all the active steps: File manipulation, AS CLI commands etc.
* @throws MigrationException
*/
private void performActions() throws MigrationException {
// Clear CLI commands, should there be any.
ctx.getBatch().clear();
// Store CLI actions into an ordered list.
List<CliCommandAction> cliActions = new LinkedList();
// Perform the actions.
log.info("Performing actions:");
List<IMigrationAction> actions = ctx.getActions();
for( IMigrationAction action : actions ) {
if( action instanceof CliCommandAction )
cliActions.add((CliCommandAction) action);
log.info(" " + action.toDescription());
action.setMigrationContext(ctx);
action.perform();
}
/// DEBUG: Dump created CLI scripts
log.debug("CLI scripts in batch:");
int i = 1;
for( BatchedCommand command : ctx.getBatch().getCommands() ){
log.debug(" " + i++ + ": " + command.getCommand());
}
// Execution
log.debug("Executing CLI batch:");
try {
AS7CliUtils.executeRequest( ctx.getBatch().toRequest(), config.getGlobal().getAS7Config() );
}
catch( CliBatchException ex ){
//Integer index = AS7CliUtils.parseFailedOperationIndex( ex.getResponseNode() );
BatchFailure failure = AS7CliUtils.extractFailedOperationNode( ex.getResponseNode() );
if( null == failure ){
log.warn("Unable to parse CLI batch operation index: " + ex.getResponseNode());
throw new MigrationException("Executing a CLI batch failed: " + ex, ex);
}
IMigrationAction causeAction;
// First, try if it's a BatchedCommandWithAction, and get the action if so.
BatchedCommand cmd = ctx.getBatch().getCommands().get( failure.getIndex() - 1 );
if( cmd instanceof BatchedCommandWithAction )
causeAction = ((BatchedCommandWithAction)cmd).getAction();
// Then shoot blindly into cliActions. May be wrong offset - some actions create multiple CLI commands! TODO.
else
causeAction = cliActions.get( failure.getIndex() - 1 );
throw new ActionException( causeAction, "Executing a CLI batch failed: " + failure.getMessage());
}
catch( IOException ex ) {
throw new MigrationException("Executing a CLI batch failed: " + ex, ex);
}
}// performActions()
private void postValidateActions() throws MigrationException {
List<IMigrationAction> actions = ctx.getActions();
for( IMigrationAction action : actions ) {
action.postValidate();
}
}
private void cleanBackupsIfAny() throws MigrationException {
List<IMigrationAction> actions = ctx.getActions();
for( IMigrationAction action : actions ) {
//if( action.isAfterBackup()) // Checked in cleanBackup() itself.
action.cleanBackup();
}
}
private void rollbackActionsWhichWerePerformed() throws MigrationException {
List<IMigrationAction> actions = ctx.getActions();
for( IMigrationAction action : actions ) {
//if( action.isAfterPerform()) // Checked in rollback() itself.
action.rollback();
}
}
/**
* Calls all migrators' callback for loading configuration data from the source server.
*
* @throws LoadMigrationException
*/
public void loadAS5Data() throws LoadMigrationException {
log.debug("======== loadAS5Data() ========");
try {
for (IMigrator mig : this.migrators) {
log.debug(" Scanning with " + mig.getClass().getSimpleName());
mig.loadAS5Data(this.ctx);
}
} catch (JAXBException e) {
throw new LoadMigrationException(e);
}
}
// AS 7 management client connection.
private void openManagementClient() throws MigrationException {
ModelControllerClient as7Client = null;
AS7Config as7Config = config.getGlobal().getAS7Config();
try {
as7Client = ModelControllerClient.Factory.create( as7Config.getHost(), as7Config.getManagementPort() );
}
catch( UnknownHostException ex ){
throw new MigrationException("Unknown AS 7 host.", ex);
}
ctx.setAS7ManagementClient( as7Client );
}
private void closeManagementClient(){
AS7CliUtils.safeClose( ctx.getAS7Client() );
ctx.setAS7ManagementClient( null );
}
}// class |
package lombok.ast.template;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import javax.tools.JavaFileObject;
import javax.tools.Diagnostic.Kind;
import lombok.Data;
import lombok.NonNull;
@SupportedAnnotationTypes("lombok.ast.template.GenerateAstNode")
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class TemplateProcessor extends AbstractProcessor {
@Data
private static class FieldData {
private final String name;
private final boolean mandatory;
private final String type;
private final boolean isList;
private final boolean astNode;
public String titleCasedName() {
String n = name.replace("_", "");
return n.isEmpty() ? "" : Character.toTitleCase(n.charAt(0)) + n.substring(1);
}
}
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (Element element : roundEnv.getElementsAnnotatedWith(GenerateAstNode.class)) {
if (element.getKind() != ElementKind.CLASS) {
processingEnv.getMessager().printMessage(Kind.ERROR, "@GenerateAstNode is only supported on plain classes", element);
continue;
}
List<FieldData> fields = new ArrayList<FieldData>();
String className;
String extending = null;
TypeElement annotated = (TypeElement)element;
className = annotated.getQualifiedName().toString();
if (className.endsWith("Template")) className = className.substring(0, className.length() - "Template".length());
else {
processingEnv.getMessager().printMessage(Kind.ERROR, "@GenerateAstNode annotated classes must end in 'Template'. Example: IfTemplate");
return true;
}
for (AnnotationMirror annotation : annotated.getAnnotationMirrors()) {
if (!annotation.getAnnotationType().toString().equals(GenerateAstNode.class.getName())) continue;
for (Entry<? extends ExecutableElement, ? extends AnnotationValue> value : annotation.getElementValues().entrySet()) {
extending = value.getValue().toString();
if (extending.endsWith(".class")) {
extending = extending.substring(0, extending.length() - ".class".length());
}
}
if (extending == null) extending = "lombok.ast.Node";
}
for (Element enclosed : annotated.getEnclosedElements()) {
if (enclosed.getKind() != ElementKind.FIELD) continue;
VariableElement field = (VariableElement) enclosed;
String fieldName = String.valueOf(field.getSimpleName());
boolean isMandatory = field.getAnnotation(NonNull.class) != null;
TypeMirror type = field.asType();
if (type instanceof DeclaredType) {
DeclaredType t = (DeclaredType) type;
if (t.toString().startsWith("java.util.List<")) {
fields.add(new FieldData(fieldName, true, t.getTypeArguments().get(0).toString(), true, isAstNodeChild(t.getTypeArguments().get(0))));
continue;
}
}
fields.add(new FieldData(fieldName, isMandatory, type.toString(), false, isAstNodeChild(type)));
}
try {
generateSourceFile(annotated, className, extending, fields);
} catch (IOException e) {
processingEnv.getMessager().printMessage(Kind.ERROR, String.format(
"Can't generate sourcefile %s: %s",
className + "Template", e), annotated);
}
}
return true;
}
private static final List<String> TREAT_AS_PRIMITIVE = Collections.unmodifiableList(Arrays.asList(
"boolean", "byte", "char", "short", "int", "long", "float", "double", "void",
"String", "java.util.String", "Object", "java.lang.Object", "Number", "java.lang.Number"
));
private boolean isAstNodeChild(TypeMirror m) {
return !TREAT_AS_PRIMITIVE.contains(m.toString());
}
private void generateSourceFile(Element originatingElement, String className, String extending, List<FieldData> fields) throws IOException {
JavaFileObject file = processingEnv.getFiler().createSourceFile(className, originatingElement);
Writer out = file.openWriter();
out.write("//Generated by lombok.ast.template.TemplateProcessor. DO NOT EDIT, DO NOT CHECK IN!\n\n");
String pkgName, typeName; {
int idx = className.lastIndexOf('.');
if (idx == -1) {
pkgName = null;
typeName = className;
} else {
pkgName = className.substring(0, idx);
typeName = className.substring(idx+1);
}
}
if (pkgName != null) {
out.write("package ");
out.write(pkgName);
out.write(";\n\n");
}
out.write("public class ");
out.write(typeName);
if (extending != null) {
out.write(" extends ");
out.write(extending);
}
out.write(" {\n");
for (FieldData field : fields) {
if (field.isList() && !field.isAstNode()) {
throw new UnsupportedOperationException("Generating an AST Node with a list containing non lombok.ast.Node-based objects is not supported: " + field.getName());
}
if (field.isList()) {
generateFieldsForList(out, className, typeName, fields.size(), field);
continue;
}
if (!field.isAstNode()) {
generateFieldsForBasic(out, field);
continue;
}
generateFieldsForNode(out, field);
}
out.write("\t\n");
for (FieldData field : fields) {
if (field.isList()) {
generateListAccessor(out, field.getName(), className, field);
continue;
}
if (!field.isAstNode()) {
generateFairWeatherGetter(out, field, false);
generateFairWeatherSetter(out, className, field);
continue;
}
generateFairWeatherGetter(out, field, true);
generateFairWeatherSetter(out, className, field);
generateRawGetter(out, field);
generateRawSetter(out, className, field);
}
/* checkSyntacticValidity */ {
out.write("\t@java.lang.Override public void checkSyntacticValidity(java.util.List<lombok.ast.SyntaxProblem> problems) {\n");
for (FieldData field : fields) {
if (field.isList()) {
generateCheckForList(out, field);
continue;
}
if (!field.isAstNode()) {
generateCheckForBasicField(out, field);
continue;
}
generateCheckForNodeField(out, field);
}
out.write("\t}\n\t\n");
}
/* accept */ {
out.write("\t@java.lang.Override public void accept(lombok.ast.ASTVisitor visitor) {\n" +
"\t\tif (visitor.visit");
out.write(typeName);
out.write("(this)) return;\n");
for (FieldData field : fields) {
if (!field.isAstNode()) continue;
if (field.isList()) {
out.write("\t\tfor (lombok.ast.Node child : this.");
out.write(field.getName());
out.write(") {\n\t\t\tchild.accept(visitor);\n\t\t}\n");
continue;
}
out.write("\t\tif (this.");
out.write(field.getName());
out.write(" != null) this.");
out.write(field.getName());
out.write(".accept(visitor);\n");
}
out.write("\t}\n");
}
out.write("}\n");
out.close();
}
private void generateFieldsForList(Writer out, String className, String typeName, int fieldsSize, FieldData field) throws IOException {
out.write("\tprivate final java.util.List<lombok.ast.Node> ");
out.write(field.getName());
out.write(" = new java.util.ArrayList<lombok.ast.Node>();\n");
// private lombok.ast.ListAccessor<CatchBlock, Try> catchesAccessor = ListAccessor.of(catches, this, CatchBlock.class, "Try.catches");
out.write("\tprivate lombok.ast.ListAccessor<");
out.write(field.getType());
out.write(", ");
out.write(className);
out.write("> ");
out.write(field.getName());
out.write("Accessor = ListAccessor.of(");
out.write(field.getName());
out.write(", this, ");
out.write(field.getType());
out.write(".class, \"");
out.write(typeName);
if (fieldsSize > 1) {
out.write(".");
out.write(field.getName());
}
out.write("\");\n");
}
private void generateFairWeatherGetter(Writer out, FieldData field, boolean generateCheck) throws IOException {
out.write("\tpublic ");
out.write(field.getType());
out.write(field.getType().equals("boolean") ? " is" : " get");
out.write(field.titleCasedName());
out.write("() {\n");
if (generateCheck) {
out.write("\t\tassertChildType(");
out.write(field.getName());
out.write(", \"");
out.write(field.getName());
out.write("\", ");
out.write("" + field.isMandatory());
out.write(", ");
out.write(field.getType());
out.write(".class);\n");
}
out.write("\t\treturn ");
if (generateCheck) {
out.write("(");
out.write(field.getType());
out.write(") ");
}
out.write("this.");
out.write(field.getName());
out.write(";\n\t}\n\t\n");
}
private void generateRawGetter(Writer out, FieldData field) throws IOException {
out.write("\tpublic lombok.ast.Node getRaw");
out.write(field.titleCasedName());
out.write("() {\n\t\treturn this.");
out.write(field.getName());
out.write(";\n\t}\n\t\n");
}
private void generateRawSetter(Writer out, String className, FieldData field) throws IOException {
out.write("\tpublic ");
out.write(className);
out.write(" setRaw");
out.write(field.titleCasedName());
out.write("(lombok.ast.Node ");
out.write(field.getName());
out.write(") {\n");
out.write("\t\tthis.");
out.write(field.getName());
out.write(" = ");
out.write(field.getName());
out.write(";\n\t\treturn this;\n\t}\n\t\n");
}
private void generateFairWeatherSetter(Writer out, String className, FieldData field) throws IOException {
out.write("\tpublic ");
out.write(className);
out.write(" set");
out.write(field.titleCasedName());
out.write("(");
out.write(field.getType());
out.write(" ");
out.write(field.getName());
out.write(") {\n");
if (field.isMandatory()) {
out.write("\t\tif (");
out.write(field.getName());
out.write(" == null) throw new java.lang.NullPointerException(\"");
out.write(field.getName());
out.write(" is mandatory\");\n");
}
out.write("\t\tthis.");
out.write(field.getName());
out.write(" = ");
out.write(field.getName());
out.write(";\n\t\treturn this;\n\t}\n\t\n");
}
private void generateFieldsForBasic(Writer out, FieldData field) throws IOException {
out.write("\tprivate ");
out.write(field.getType());
out.write(" ");
out.write(field.getName());
out.write(";\n");
}
private void generateListAccessor(Writer out, String methodName, String className, FieldData field) throws IOException {
out.write("\tpublic lombok.ast.ListAccessor<");
out.write(field.getType());
out.write(", ");
out.write(className);
out.write("> ");
out.write(methodName);
out.write("() {\n\t\treturn this.");
out.write(field.getName());
out.write("Accessor;\n\t}\n");
}
private void generateFieldsForNode(Writer out, FieldData field) throws IOException {
out.write("\tprivate lombok.ast.Node ");
out.write(field.getName());
out.write(";\n");
}
private void generateCheckForList(Writer out, FieldData field) throws IOException {
out.write("\t\tfor (int i = 0; i < this.");
out.write(field.getName());
out.write(".size(); i++) {\n");
out.write("\t\t\tcheckChildValidity(problems, this.");
out.write(field.getName());
out.write(".get(i), \"");
out.write(field.getName());
out.write("[\" + i + \"]\", true, ");
out.write(field.getType());
out.write(".class);\n");
out.write("\t\t}\n");
}
private void generateCheckForBasicField(Writer out, FieldData field) throws IOException {
if (field.isMandatory()) {
out.write("\t\tif (this.");
out.write(field.getName());
out.write(" == null) problems.add(new lombok.ast.SyntaxProblem(this, \"");
out.write(field.getName());
out.write(" is mandatory\"));\n");
}
}
private void generateCheckForNodeField(Writer out, FieldData field) throws IOException {
out.write("\t\tcheckChildValidity(problems, this.");
out.write(field.getName());
out.write(", \"");
out.write(field.getName());
out.write("\", ");
out.write("" + field.isMandatory());
out.write(", ");
out.write(field.getType());
out.write(".class);\n");
}
} |
package de.bmoth.backend.z3;
import com.microsoft.z3.*;
import de.bmoth.app.PersonalPreferences;
import de.bmoth.backend.TranslationOptions;
import de.bmoth.parser.Parser;
import de.bmoth.parser.ast.AbstractVisitor;
import de.bmoth.parser.ast.AstTransformationForZ3;
import de.bmoth.parser.ast.nodes.*;
import de.bmoth.parser.ast.nodes.ExpressionOperatorNode.ExpressionOperator;
import de.bmoth.parser.ast.nodes.FormulaNode.FormulaType;
import de.bmoth.parser.ast.types.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
/**
* This class translates a FormulaNode of the parser to a z3 backend node.
**/
public class FormulaToZ3Translator {
private Context z3Context;
// the context which is used to create z3 objects
private final LinkedList<BoolExpr> constraintList = new LinkedList<>();
// For example, for the B keyword NATURAL an ordinary z3 identifier will be
// created because there no corresponding keyword in z3.
// Additionally, a constraint axiomatizing this identifier will be added to
// this list.
private int tempVariablesCounter = 0;
// used to generate unique identifiers
List<DeclarationNode> implicitDeclarations;
FormulaNode formulaNode;
private FuncDecl pow = null;
private String createFreshTemporaryVariable() {
this.tempVariablesCounter++;
return "$t_" + this.tempVariablesCounter;
}
public List<DeclarationNode> getImplicitDeclarations() {
return this.implicitDeclarations;
}
public List<Expr> getImplicitVariablesAsZ3Expression() {
List<Expr> list = new ArrayList<>();
for (DeclarationNode decl : implicitDeclarations) {
Expr mkConst = this.z3Context.mkConst(decl.getName(), bTypeToZ3Sort(decl.getType()));
list.add(mkConst);
}
return list;
}
private FormulaToZ3Translator(Context z3Context, String formula) {
this.z3Context = z3Context;
formulaNode = Parser.getFormulaAsSemanticAst(formula);
this.implicitDeclarations = formulaNode.getImplicitDeclarations();
}
private FormulaToZ3Translator(Context z3Context) {
this.z3Context = z3Context;
}
public static BoolExpr translateVariableEqualToExpr(String name, ExprNode value, Context z3Context) {
ExprNode exprNode = AstTransformationForZ3.transformExprNode(value);
return translateVariableEqualToExpr(name, exprNode, z3Context, new TranslationOptions());
}
public static BoolExpr translateVariableEqualToExpr(String name, ExprNode value, Context z3Context,
TranslationOptions opt) {
FormulaToZ3Translator formulaToZ3Translator = new FormulaToZ3Translator(z3Context);
FormulaToZ3TranslatorVisitor visitor = formulaToZ3Translator.new FormulaToZ3TranslatorVisitor();
Expr z3Value = visitor.visitExprNode(value, opt);
Expr variable = z3Context.mkConst(name, z3Value.getSort());
return z3Context.mkEq(variable, z3Value);
}
public static BoolExpr translatePredicate(String formula, Context z3Context) {
FormulaToZ3Translator formulaToZ3Translator = new FormulaToZ3Translator(z3Context, formula);
if (formulaToZ3Translator.formulaNode.getFormulaType() != FormulaType.PREDICATE_FORMULA) {
throw new RuntimeException("Expected predicate.");
}
PredicateNode predNode = AstTransformationForZ3
.transformSemanticNode((PredicateNode) formulaToZ3Translator.formulaNode.getFormula());
FormulaToZ3TranslatorVisitor visitor = formulaToZ3Translator.new FormulaToZ3TranslatorVisitor();
Expr constraint = visitor.visitPredicateNode(predNode, new TranslationOptions());
if (!(constraint instanceof BoolExpr)) {
throw new RuntimeException("Invalid translation. Expected BoolExpr but found " + constraint.getClass());
}
BoolExpr boolExpr = (BoolExpr) constraint;
// adding all additional constraints to result
for (BoolExpr bExpr : formulaToZ3Translator.constraintList) {
boolExpr = z3Context.mkAnd(boolExpr, bExpr);
}
return boolExpr;
}
public static BoolExpr translatePredicate(PredicateNode pred, Context z3Context) {
PredicateNode predNode = AstTransformationForZ3.transformSemanticNode(pred);
return translatePredicate(predNode, z3Context, new TranslationOptions());
}
public static BoolExpr translatePredicate(PredicateNode pred, Context z3Context, TranslationOptions opt) {
PredicateNode predNode = AstTransformationForZ3.transformSemanticNode(pred);
FormulaToZ3Translator formulaToZ3Translator = new FormulaToZ3Translator(z3Context);
FormulaToZ3TranslatorVisitor formulaToZ3TranslatorVisitor = formulaToZ3Translator.new FormulaToZ3TranslatorVisitor();
BoolExpr boolExpr = (BoolExpr) formulaToZ3TranslatorVisitor.visitPredicateNode(predNode, opt);
// adding all additional constraints to result
for (BoolExpr bExpr : formulaToZ3Translator.constraintList) {
boolExpr = z3Context.mkAnd(boolExpr, bExpr);
}
return boolExpr;
}
public static Sort bTypeToZ3Sort(Context z3Context, Type t) {
FormulaToZ3Translator formulaToZ3Translator = new FormulaToZ3Translator(z3Context);
return formulaToZ3Translator.bTypeToZ3Sort(t);
}
public Sort bTypeToZ3Sort(Type t) {
if (t instanceof IntegerType) {
return z3Context.getIntSort();
}
if (t instanceof BoolType) {
return z3Context.getBoolSort();
}
if (t instanceof SetType) {
SetType s = (SetType) t;
Sort subSort = bTypeToZ3Sort(s.getSubtype());
return z3Context.mkSetSort(subSort);
}
if (t instanceof CoupleType) {
CoupleType c = (CoupleType) t;
Sort[] subSorts = new Sort[2];
subSorts[0] = bTypeToZ3Sort(c.getLeft());
subSorts[1] = bTypeToZ3Sort(c.getRight());
return z3Context.mkTupleSort(z3Context.mkSymbol("couple"),
new Symbol[]{z3Context.mkSymbol("left"), z3Context.mkSymbol("right")}, subSorts);
}
if (t instanceof SequenceType) {
SequenceType s = (SequenceType) t;
Sort subSort = bTypeToZ3Sort(s.getSubtype());
Sort intType = z3Context.getIntSort();
Sort[] subSorts = new Sort[2];
subSorts[0] = z3Context.mkArraySort(intType, subSort);
subSorts[1] = intType;
return z3Context.mkTupleSort(z3Context.mkSymbol("sequence"),
new Symbol[]{z3Context.mkSymbol("array"), z3Context.mkSymbol("size")}, subSorts);
}
throw new AssertionError("Missing Type Conversion: " + t.getClass());
}
class FormulaToZ3TranslatorVisitor extends AbstractVisitor<Expr, TranslationOptions> {
private String addPrimes(TranslationOptions ops, String name) {
int numOfPrimes = ops.getPrimeLevel();
StringBuilder nameBuilder = new StringBuilder(name);
while (numOfPrimes > 0) {
nameBuilder.append("'");
numOfPrimes
}
return nameBuilder.toString();
}
@Override
public Expr visitIdentifierExprNode(IdentifierExprNode node, TranslationOptions ops) {
Type type = node.getDeclarationNode().getType();
return z3Context.mkConst(addPrimes(ops, node.getName()), bTypeToZ3Sort(type));
}
@Override
public Expr visitCastPredicateExpressionNode(CastPredicateExpressionNode node, TranslationOptions expected) {
return visitPredicateNode(node.getPredicate(), expected);
}
@Override
public Expr visitIdentifierPredicateNode(IdentifierPredicateNode node, TranslationOptions ops) {
return z3Context.mkBoolConst(node.getName());
}
@Override
public Expr visitPredicateOperatorWithExprArgs(PredicateOperatorWithExprArgsNode node, TranslationOptions ops) {
final List<Expr> arguments = node.getExpressionNodes().stream().map(it -> visitExprNode(it, ops)).collect(Collectors.toList());
switch (node.getOperator()) {
case EQUAL:
return z3Context.mkEq(arguments.get(0), arguments.get(1));
case NOT_EQUAL:
return z3Context.mkNot(z3Context.mkEq(arguments.get(0), arguments.get(1)));
case ELEMENT_OF:
return z3Context.mkSetMembership(arguments.get(0), (ArrayExpr) arguments.get(1));
case LESS_EQUAL:
return z3Context.mkLe((ArithExpr) arguments.get(0), (ArithExpr) arguments.get(1));
case LESS:
return z3Context.mkLt((ArithExpr) arguments.get(0), (ArithExpr) arguments.get(1));
case GREATER_EQUAL:
return z3Context.mkGe((ArithExpr) arguments.get(0), (ArithExpr) arguments.get(1));
case GREATER:
return z3Context.mkGt((ArithExpr) arguments.get(0), (ArithExpr) arguments.get(1));
case NOT_BELONGING:
return z3Context.mkNot(z3Context.mkSetMembership(arguments.get(0), (ArrayExpr) arguments.get(1)));
case INCLUSION:
// a <: S
return z3Context.mkSetSubset((ArrayExpr) arguments.get(0), (ArrayExpr) arguments.get(1));
case STRICT_INCLUSION:
// a <<: S
return z3Context.mkAnd(z3Context.mkNot(z3Context.mkEq(arguments.get(0), arguments.get(1))), z3Context.mkSetSubset((ArrayExpr) arguments.get(0), (ArrayExpr) arguments.get(1)));
case NON_INCLUSION:
return z3Context.mkNot(z3Context.mkSetSubset((ArrayExpr) arguments.get(0), (ArrayExpr) arguments.get(1)));
case STRICT_NON_INCLUSION:
return z3Context.mkNot(z3Context.mkAnd(z3Context.mkNot(z3Context.mkEq(arguments.get(0), arguments.get(1))),
z3Context.mkSetSubset((ArrayExpr) arguments.get(0), (ArrayExpr) arguments.get(1))));
default:
throw new AssertionError("Not implemented: " + node.getOperator());
}
}
@Override
public Expr visitExprOperatorNode(ExpressionOperatorNode node, TranslationOptions ops) {
List<ExprNode> expressionNodes = node.getExpressionNodes();
switch (node.getOperator()) {
case PLUS: {
ArithExpr left = (ArithExpr) visitExprNode(expressionNodes.get(0), ops);
ArithExpr right = (ArithExpr) visitExprNode(expressionNodes.get(1), ops);
return z3Context.mkAdd(left, right);
}
case UNARY_MINUS: {
return z3Context.mkUnaryMinus((ArithExpr) visitExprNode(expressionNodes.get(0), ops));
}
case MINUS: {
ArithExpr left = (ArithExpr) visitExprNode(expressionNodes.get(0), ops);
ArithExpr right = (ArithExpr) visitExprNode(expressionNodes.get(1), ops);
return z3Context.mkSub(left, right);
}
case MOD: {
IntExpr left = (IntExpr) visitExprNode(expressionNodes.get(0), ops);
IntExpr right = (IntExpr) visitExprNode(expressionNodes.get(1), ops);
return z3Context.mkMod(left, right);
}
case MULT: {
ArithExpr left = (ArithExpr) visitExprNode(expressionNodes.get(0), ops);
ArithExpr right = (ArithExpr) visitExprNode(expressionNodes.get(1), ops);
return z3Context.mkMul(left, right);
}
case DIVIDE: {
ArithExpr left = (ArithExpr) visitExprNode(expressionNodes.get(0), ops);
ArithExpr right = (ArithExpr) visitExprNode(expressionNodes.get(1), ops);
constraintList.add(z3Context.mkNot(z3Context.mkEq(right, z3Context.mkInt(0))));
return z3Context.mkDiv(left, right);
}
case POWER_OF: {
ArithExpr left = (ArithExpr) visitExprNode(expressionNodes.get(0), ops);
ArithExpr right = (ArithExpr) visitExprNode(expressionNodes.get(1), ops);
if (pow == null) {
pow = initPowerOf();
}
return pow.apply(left, right);
}
case INTERVAL: {
ArithExpr left = (ArithExpr) visitExprNode(expressionNodes.get(0), ops);
ArithExpr right = (ArithExpr) visitExprNode(expressionNodes.get(1), ops);
ArithExpr x = (ArithExpr) z3Context.mkConst(createFreshTemporaryVariable(), z3Context.getIntSort());
Expr T = z3Context.mkConst(createFreshTemporaryVariable(), bTypeToZ3Sort(node.getType()));
BoolExpr leftLe = z3Context.mkLe(left, x);
BoolExpr rightGe = z3Context.mkGe(right, x);
BoolExpr interval = z3Context.mkAnd(leftLe, rightGe);
BoolExpr member = z3Context.mkSetMembership(x, (ArrayExpr) T);
BoolExpr equality = z3Context.mkEq(interval, member);
Expr[] bound = new Expr[]{x};
Quantifier q = z3Context.mkForall(bound, equality, 1, null, null, null, null);
constraintList.add(q);
return T;
}
case INTEGER: {
return z3Context.mkFullSet(z3Context.mkIntSort());
}
case NATURAL1: {
Type type = node.getType();// POW(INTEGER)
// !x.(x >= 1 <=> x : NATURAL)
Expr x = z3Context.mkConst("x", z3Context.getIntSort());
Expr natural1 = z3Context.mkConst("NATURAL1", bTypeToZ3Sort(type));
Expr[] bound = new Expr[]{x};
// x >= 1
BoolExpr a = z3Context.mkGe((ArithExpr) x, z3Context.mkInt(1));
// x : NATURAL
BoolExpr b = z3Context.mkSetMembership(x, (ArrayExpr) natural1);
// a <=> b
BoolExpr body = z3Context.mkEq(a, b);
Quantifier q = z3Context.mkForall(bound, body, 1, null, null, null, null);
constraintList.add(q);
return natural1;
}
case NATURAL: {
Type type = node.getType();// POW(INTEGER)
// !x.(x >= 0 <=> x : NATURAL)
Expr x = z3Context.mkConst("x", z3Context.getIntSort());
Expr natural = z3Context.mkConst(ExpressionOperator.NATURAL.toString(), bTypeToZ3Sort(type));
Expr[] bound = new Expr[]{x};
// x >= 0
BoolExpr a = z3Context.mkGe((ArithExpr) x, z3Context.mkInt(0));
// x : NATURAL
BoolExpr b = z3Context.mkSetMembership(x, (ArrayExpr) natural);
// a <=> b
BoolExpr body = z3Context.mkEq(a, b);
Quantifier q = z3Context.mkForall(bound, body, 1, null, null, null, null);
constraintList.add(q);
return natural;
}
case FALSE:
return z3Context.mkFalse();
case TRUE:
return z3Context.mkTrue();
case BOOL: {
return z3Context.mkFullSet(z3Context.mkBoolSort());
}
case UNION: {
ArrayExpr[] array = new ArrayExpr[expressionNodes.size()];
for (int i = 0; i < array.length; i++) {
array[i] = (ArrayExpr) visitExprNode(expressionNodes.get(i), ops);
}
return z3Context.mkSetUnion(array);
}
case COUPLE: {
CoupleType type = (CoupleType) node.getType();
TupleSort bTypeToZ3Sort = (TupleSort) bTypeToZ3Sort(type);
Expr left = visitExprNode(node.getExpressionNodes().get(0), ops);
Expr right = visitExprNode(node.getExpressionNodes().get(1), ops);
return bTypeToZ3Sort.mkDecl().apply(left, right);
}
case DOMAIN:
break;
case INTERSECTION: {
ArrayExpr left = (ArrayExpr) visitExprNode(expressionNodes.get(0), ops);
ArrayExpr right = (ArrayExpr) visitExprNode(expressionNodes.get(1), ops);
return z3Context.mkSetIntersection(left, right);
}
case RANGE:
break;
case LAST: {
Expr expr = visitExprNode(expressionNodes.get(0), ops);
DatatypeExpr d = (DatatypeExpr) expr;
Expr[] args = d.getArgs();
ArrayExpr array = (ArrayExpr) args[0];
ArithExpr size = (ArithExpr) args[1];
// add WD constraint
constraintList.add(z3Context.mkLe(z3Context.mkInt(1), size));
return z3Context.mkSelect(array, size);
}
case FRONT: {
Expr expr = visitExprNode(expressionNodes.get(0), ops);
DatatypeExpr d = (DatatypeExpr) expr;
Expr[] args = d.getArgs();
ArrayExpr array = (ArrayExpr) args[0];
ArithExpr size = (ArithExpr) args[1];
constraintList.add(z3Context.mkLe(z3Context.mkInt(1), size));
TupleSort mkTupleSort = (TupleSort) bTypeToZ3Sort(node.getType());
return mkTupleSort.mkDecl().apply(array, z3Context.mkSub(size, z3Context.mkInt(1)));
}
case TAIL:
break;
case CONC:
break;
case EMPTY_SET: // this is not missing! it is equal to an empty set
// enumeration below
case SET_ENUMERATION: {
SetType type = (SetType) node.getType();
Type subType = type.getSubtype();
ArrayExpr z3Set = z3Context.mkEmptySet(bTypeToZ3Sort(subType));
for (ExprNode exprNode : expressionNodes) {
z3Set = z3Context.mkSetAdd(z3Set, visitExprNode(exprNode, ops));
}
return z3Set;
}
case SET_SUBTRACTION: {
ArrayExpr left = (ArrayExpr) visitExprNode(expressionNodes.get(0), ops);
ArrayExpr right = (ArrayExpr) visitExprNode(expressionNodes.get(1), ops);
return z3Context.mkSetDifference(left, right);
}
case CONCAT:
case DIRECT_PRODUCT:
case DOMAIN_RESTRICTION:
case DOMAIN_SUBTRACTION:
case GENERALIZED_INTER:
break;
case GENERALIZED_UNION: {
// union(S)
// return Res
// !(e).(e : Res <=> #(s).(s : S & e : s)
SetType setType = (SetType) node.getType();
Expr S = visitExprNode(expressionNodes.get(0), ops);
Expr res = z3Context.mkConst(createFreshTemporaryVariable(), bTypeToZ3Sort(setType));
Expr s = z3Context.mkConst(createFreshTemporaryVariable(), bTypeToZ3Sort(setType));
Expr e = z3Context.mkConst(createFreshTemporaryVariable(), bTypeToZ3Sort(setType.getSubtype()));
BoolExpr eIsInRes = z3Context.mkSetMembership(e, (ArrayExpr) res);
BoolExpr sIsInS = z3Context.mkSetMembership(s, (ArrayExpr) S);
BoolExpr eIsIns = z3Context.mkSetMembership(e, (ArrayExpr) s);
Quantifier exists = z3Context.mkExists(new Expr[]{s}, z3Context.mkAnd(sIsInS, eIsIns), 1, null, null,
null, null);
Quantifier q = z3Context.mkForall(new Expr[]{e}, z3Context.mkEq(eIsInRes, exists), 1, null, null,
null, null);
constraintList.add(q);
return res;
}
case EMPTY_SEQUENCE: {
Sort intType = z3Context.getIntSort();
Type type = ((SequenceType) node.getType()).getSubtype();
Sort rangeType = bTypeToZ3Sort(type);
ArrayExpr a = z3Context.mkArrayConst(createFreshTemporaryVariable(), intType, rangeType);
TupleSort mkTupleSort = (TupleSort) bTypeToZ3Sort(node.getType());
return mkTupleSort.mkDecl().apply(a, z3Context.mkInt(expressionNodes.size()));
}
case SEQ_ENUMERATION: {
Sort intType = z3Context.getIntSort();
Type type = ((SequenceType) node.getType()).getSubtype();
Sort rangeType = bTypeToZ3Sort(type);
ArrayExpr a = z3Context.mkArrayConst(createFreshTemporaryVariable(), intType, rangeType);
for (int i = 0; i < expressionNodes.size(); i++) {
int j = i + 1;
IntNum index = z3Context.mkInt(j);
Expr value = visitExprNode(expressionNodes.get(i), ops);
a = z3Context.mkStore(a, index, value);
}
TupleSort mkTupleSort = (TupleSort) bTypeToZ3Sort(node.getType());
return mkTupleSort.mkDecl().apply(a, z3Context.mkInt(expressionNodes.size()));
}
case FIRST: {
Expr expr = visitExprNode(expressionNodes.get(0), ops);
DatatypeExpr d = (DatatypeExpr) expr;
Expr[] args = d.getArgs();
ArrayExpr array = (ArrayExpr) args[0];
ArithExpr size = (ArithExpr) args[1];
// add WD constraint
constraintList.add(z3Context.mkLe(z3Context.mkInt(1), size));
return z3Context.mkSelect(array, z3Context.mkInt(1));
}
case FUNCTION_CALL: {
Expr expr = visitExprNode(expressionNodes.get(0), ops);
DatatypeExpr d = (DatatypeExpr) expr;
Expr[] args = d.getArgs();
ArrayExpr array = (ArrayExpr) args[0];
ArithExpr size = (ArithExpr) args[1];
ArithExpr index = (ArithExpr) visitExprNode(expressionNodes.get(1), ops);
// add WD constraint
constraintList
.add(z3Context.mkAnd(z3Context.mkGe(index, z3Context.mkInt(1)), z3Context.mkLe(index, size)));
return z3Context.mkSelect(array, index);
}
case CARD: {
break;
}
case INSERT_FRONT:
case INSERT_TAIL:
case OVERWRITE_RELATION:
case INVERSE_RELATION: {
SetType nType = (SetType) node.getType();
CoupleType subType = (CoupleType) nType.getSubtype();
CoupleType revType = new CoupleType(subType.getRight(), subType.getLeft());
TupleSort subSort = (TupleSort) bTypeToZ3Sort(subType);
TupleSort revSort = (TupleSort) bTypeToZ3Sort(revType);
ArrayExpr expr = (ArrayExpr) visitExprNode(expressionNodes.get(0), ops);
Expr tempLeft = z3Context.mkConst(createFreshTemporaryVariable(), bTypeToZ3Sort(subType.getLeft()));
Expr tempRight = z3Context.mkConst(createFreshTemporaryVariable(), bTypeToZ3Sort(subType.getRight()));
ArrayExpr tempConstant = (ArrayExpr) z3Context.mkConst(createFreshTemporaryVariable(), bTypeToZ3Sort(new SetType(revType)));
BoolExpr lrInExpr = z3Context.mkSetMembership(subSort.mkDecl().apply(tempLeft, tempRight), expr);
BoolExpr rlInTempExpr = z3Context.mkSetMembership(revSort.mkDecl().apply(tempRight, tempLeft), tempConstant);
BoolExpr equality = z3Context.mkEq(lrInExpr, rlInTempExpr);
Expr[] bound = new Expr[]{tempLeft, tempRight};
Quantifier q = z3Context.mkForall(bound, equality, 2, null, null, null, null);
constraintList.add(q);
return tempConstant;
}
case RANGE_RESTRICTION:
case RANGE_SUBTRATION:
case RESTRICT_FRONT:
case RESTRICT_TAIL:
break;
case SEQ:
break;
case SEQ1:
break;
case ISEQ:
break;
case ISEQ1:
break;
case CARTESIAN_PRODUCT: {
ArrayExpr left = (ArrayExpr) visitExprNode(expressionNodes.get(0), ops);
ArrayExpr right = (ArrayExpr) visitExprNode(expressionNodes.get(1), ops);
SetType setType = (SetType) node.getType();
CoupleType coupleType = (CoupleType) setType.getSubtype();
TupleSort bTypeToZ3Sort = (TupleSort) bTypeToZ3Sort(coupleType);
ArithExpr leftExpr = (ArithExpr) z3Context.mkConst(createFreshTemporaryVariable(), bTypeToZ3Sort(coupleType.getLeft()));
ArithExpr rightExpr = (ArithExpr) z3Context.mkConst(createFreshTemporaryVariable(), bTypeToZ3Sort(coupleType.getRight()));
ArrayExpr tempConstant = (ArrayExpr) z3Context.mkConst(createFreshTemporaryVariable(), bTypeToZ3Sort(node.getType()));
Expr couple = bTypeToZ3Sort.mkDecl().apply(leftExpr, rightExpr);
BoolExpr xInLeft = z3Context.mkSetMembership(leftExpr, left);
BoolExpr yInRight = z3Context.mkSetMembership(rightExpr, right);
BoolExpr coupleInCartesian = z3Context.mkSetMembership(couple, tempConstant);
BoolExpr cartesian = z3Context.mkAnd(xInLeft, yInRight);
BoolExpr equality = z3Context.mkEq(cartesian, coupleInCartesian);
Expr[] bound = new Expr[]{leftExpr, rightExpr};
Quantifier q = z3Context.mkForall(bound, equality, 2, null, null, null, null);
constraintList.add(q);
return tempConstant;
}
case INT: {
Type type = node.getType();// POW(INTEGER)
int maxInt = PersonalPreferences.getIntPreference(PersonalPreferences.IntPreference.MAX_INT);
int minInt = PersonalPreferences.getIntPreference(PersonalPreferences.IntPreference.MIN_INT);
// !x.((x >= MIN_INT & x <= MAX_INT) <=> x : INT)
Expr integer = z3Context.mkConst(ExpressionOperator.INT.toString(), bTypeToZ3Sort(type));
Expr x = z3Context.mkConst("x", z3Context.getIntSort());
Expr[] bound = new Expr[]{x};
// x >= MIN_INT
BoolExpr a = z3Context.mkGe((ArithExpr) x, z3Context.mkInt(minInt));
// x :INT
BoolExpr b = z3Context.mkSetMembership(x, (ArrayExpr) integer);
// x <= max_int
BoolExpr c = z3Context.mkLe((ArithExpr) x, z3Context.mkInt(maxInt));
// a <=> b <=> c
BoolExpr body = z3Context.mkEq(z3Context.mkAnd(a, c), b);
Quantifier q = z3Context.mkForall(bound, body, 1, null, null, null, null);
constraintList.add(q);
return integer;
}
case MAXINT: {
int maxInt = PersonalPreferences.getIntPreference(PersonalPreferences.IntPreference.MAX_INT);
return z3Context.mkInt(maxInt);
}
case MININT: {
int minInt = PersonalPreferences.getIntPreference(PersonalPreferences.IntPreference.MIN_INT);
return z3Context.mkInt(minInt);
}
case NAT: {
Type type = node.getType();// POW(INTEGER)
int maxInt = PersonalPreferences.getIntPreference(PersonalPreferences.IntPreference.MAX_INT);
// !x.((x >= 0 & x <= MAX_INT) <=> x : NAT)
Expr x = z3Context.mkConst("x", z3Context.getIntSort());
Expr nat = z3Context.mkConst(ExpressionOperator.NAT.toString(), bTypeToZ3Sort(type));
Expr[] bound = new Expr[]{x};
// x >= 0
BoolExpr a = z3Context.mkGe((ArithExpr) x, z3Context.mkInt(0));
// x : NAT
BoolExpr b = z3Context.mkSetMembership(x, (ArrayExpr) nat);
// x <= max_int
BoolExpr c = z3Context.mkLe((ArithExpr) x, z3Context.mkInt(maxInt));
// a <=> b <=> c
BoolExpr body = z3Context.mkEq(z3Context.mkAnd(a, c), b);
Quantifier q = z3Context.mkForall(bound, body, 1, null, null, null, null);
constraintList.add(q);
return nat;
}
default:
break;
}
throw new AssertionError("Not implemented: " + node.getOperator());
}
private FuncDecl initPowerOf() {
// create function declaration
FuncDecl powerOf = z3Context.mkFuncDecl(ExpressionOperator.POWER_OF.toString(), new Sort[]{z3Context.mkIntSort(), z3Context.mkIntSort()}, z3Context.mkIntSort());
// create arguments & bounds
Expr a = z3Context.mkConst("a", z3Context.getIntSort());
Expr b = z3Context.mkConst("b", z3Context.getIntSort());
Expr[] bound = new Expr[]{a, b};
// pow( a, b / 2 ) * pow( a, b / 2 )
Expr expEven = z3Context.mkMul((ArithExpr) powerOf.apply(a, z3Context.mkDiv((ArithExpr) b, z3Context.mkInt(2))), (ArithExpr) powerOf.apply(a, z3Context.mkDiv((ArithExpr) b, z3Context.mkInt(2))));
// a * pow( a, b - 1 )
Expr expOdd = z3Context.mkMul((ArithExpr) a, (ArithExpr) powerOf.apply(a, z3Context.mkSub((ArithExpr) b, z3Context.mkInt(1))));
// b % 2 == 0 ? expEven : expOdd
Expr expEvenOdd = z3Context.mkITE(z3Context.mkEq(z3Context.mkInt(0), z3Context.mkMod((IntExpr) b, z3Context.mkInt(2))), expEven, expOdd);
// b == 0 ? 1 : expEvenOdd
Expr expZero = z3Context.mkITE(z3Context.mkEq(z3Context.mkInt(0), b), z3Context.mkInt(1), expEvenOdd);
// pow( a, b ) = expZero
Expr body = z3Context.mkEq(powerOf.apply(a, b), expZero);
// prepare pattern
Pattern[] patterns = new Pattern[]{z3Context.mkPattern(powerOf.apply(a, b))};
// annotate recursive function
Symbol recFun = z3Context.mkSymbol(":rec-fun");
BoolExpr powConstraint = z3Context.mkForall(bound, body, bound.length, patterns, null, recFun, null);
constraintList.add(powConstraint);
return powerOf;
}
@Override
public Expr visitNumberNode(NumberNode node, TranslationOptions ops) {
return z3Context.mkInt(node.getValue());
}
@Override
public Expr visitPredicateOperatorNode(PredicateOperatorNode node, TranslationOptions ops) {
final List<BoolExpr> arguments = node.getPredicateArguments().stream().map(it -> (BoolExpr) visitPredicateNode(it, ops)).collect(Collectors.toList());
switch (node.getOperator()) {
case AND:
return z3Context.mkAnd(arguments.toArray(new BoolExpr[arguments.size()]));
case OR:
return z3Context.mkOr(arguments.toArray(new BoolExpr[arguments.size()]));
case IMPLIES:
return z3Context.mkImplies(arguments.get(0), arguments.get(1));
case EQUIVALENCE:
return z3Context.mkEq(arguments.get(0), arguments.get(1));
case NOT:
return z3Context.mkNot(arguments.get(0));
case TRUE:
return z3Context.mkTrue();
case FALSE:
return z3Context.mkFalse();
default:
throw new AssertionError("Not implemented: " + node.getOperator());
}
}
@Override
public Expr visitSelectSubstitutionNode(SelectSubstitutionNode node, TranslationOptions opt) {
throw new AssertionError("Not reachable");
}
@Override
public Expr visitSingleAssignSubstitution(SingleAssignSubstitutionNode node, TranslationOptions opt) {
throw new AssertionError("Not reachable");
}
@Override
public Expr visitParallelSubstitutionNode(ParallelSubstitutionNode node, TranslationOptions opt) {
throw new AssertionError("Not reachable");
}
@Override
public Expr visitQuantifiedExpressionNode(QuantifiedExpressionNode node, TranslationOptions opt) {
switch (node.getOperator()) {
case SET_COMPREHENSION: {
// {e| P}
// return T
// !(e).(e : T <=> P )
Expr P = visitPredicateNode(node.getPredicateNode(), opt);
Expr T = z3Context.mkConst(createFreshTemporaryVariable(), bTypeToZ3Sort(node.getType()));
Expr[] array = new Expr[node.getDeclarationList().size()];
for (int i = 0; i < array.length; i++) {
DeclarationNode decl = node.getDeclarationList().get(i);
Expr e = z3Context.mkConst(decl.getName(), bTypeToZ3Sort(decl.getType()));
array[i] = e;
}
Expr tuple = null;
if (array.length > 1) {
TupleSort tupleSort = (TupleSort) bTypeToZ3Sort(((SetType) node.getType()).getSubtype());
tuple = tupleSort.mkDecl().apply(array);
} else {
tuple = array[0];
}
Expr[] bound = array;
BoolExpr a = z3Context.mkSetMembership(tuple, (ArrayExpr) T);
// a <=> P
BoolExpr body = z3Context.mkEq(a, P);
Quantifier q = z3Context.mkForall(bound, body, array.length, null, null, null, null);
constraintList.add(q);
return T;
}
case QUANTIFIED_INTER:
case QUANTIFIED_UNION:
break;
default:
break;
}
throw new AssertionError("Implement: " + node.getClass());
}
@Override
public Expr visitQuantifiedPredicateNode(QuantifiedPredicateNode node, TranslationOptions opt) {
final Expr[] identifiers = node.getDeclarationList().stream().map(declaration -> z3Context.mkConst(declaration.getName(), bTypeToZ3Sort(declaration.getType()))).toArray(Expr[]::new);
final Expr predicate = visitPredicateNode(node.getPredicateNode(), opt);
switch (node.getOperator()) {
case EXISTENTIAL_QUANTIFICATION:
return z3Context.mkExists(identifiers, predicate, identifiers.length, null, null, null, null);
case UNIVERSAL_QUANTIFICATION:
return z3Context.mkForall(identifiers, predicate, identifiers.length, null, null, null, null);
default:
throw new AssertionError("Implement: " + node.getClass());
}
}
@Override
public Expr visitAnySubstitution(AnySubstitutionNode node, TranslationOptions opt) {
throw new AssertionError("Not reachable");
}
}
} |
package test.dr.evomodel.treelikelihood;
import dr.evolution.alignment.SitePatterns;
import dr.evolution.datatype.Nucleotides;
import dr.evolution.tree.SimpleNode;
import dr.evolution.tree.SimpleTree;
import dr.evolution.tree.Tree;
import dr.evolution.util.Units;
import dr.evomodel.sitemodel.GammaSiteModel;
import dr.evomodel.substmodel.FrequencyModel;
import dr.evomodel.substmodel.GTR;
import dr.evomodel.substmodel.HKY;
import dr.evomodel.tree.TreeModel;
import dr.evomodel.treelikelihood.TreeLikelihood;
import dr.evomodelxml.HKYParser;
import dr.inference.model.Parameter;
import dr.inference.model.Variable;
import junit.framework.Test;
import junit.framework.TestSuite;
import test.dr.inference.trace.TraceCorrelationAssert;
import java.text.NumberFormat;
import java.util.Locale;
/**
* @author Walter Xie
* convert testLikelihood.xml in the folder /example
*/
public class LikelihoodTest extends TraceCorrelationAssert {
private TreeModel treeModel;
private NumberFormat format = NumberFormat.getNumberInstance(Locale.ENGLISH);
public LikelihoodTest(String name) {
super(name);
}
public void setUp() throws Exception {
super.setUp();
format.setMaximumFractionDigits(5);
createAlignment(HOMINID_TAXON_SEQUENCE, Nucleotides.INSTANCE);
createTreeModel ();
}
private void createTreeModel () {
SimpleNode[] nodes = new SimpleNode[10];
for (int n=0; n < 10; n++) {
nodes[n] = new SimpleNode();
}
// nodes[0].setHeight(0);
nodes[0].setTaxon(taxa[0]); // human
nodes[1].setTaxon(taxa[1]); // chimp
nodes[2].setTaxon(taxa[2]); // bonobo
nodes[3].setHeight(0.010772);
nodes[3].addChild(nodes[1]);
nodes[3].addChild(nodes[2]);
nodes[4].setHeight(0.024003);
nodes[4].addChild(nodes[0]);
nodes[4].addChild(nodes[3]);
nodes[5].setTaxon(taxa[3]); // gorilla
nodes[6].setHeight(0.036038);
nodes[6].addChild(nodes[4]);
nodes[6].addChild(nodes[5]);
nodes[7].setTaxon(taxa[4]); // orangutan
nodes[8].setHeight(0.069125);
nodes[8].addChild(nodes[6]);
nodes[8].addChild(nodes[7]);
nodes[9].setTaxon(taxa[5]); // siamang
SimpleNode root = new SimpleNode();
root.setHeight(0.099582);
root.addChild(nodes[8]);
root.addChild(nodes[9]);
Tree tree = new SimpleTree(root);
tree.setUnits(Units.Type.YEARS);
treeModel = new TreeModel(tree); //treeModel
}
public void testNewickTree() {
System.out.println("\nTest Simple Node to convert Newick Tree:");
String expectedNewickTree = "((((human:0.024003,(chimp:0.010772,bonobo:0.010772):0.013231):0.012035," +
"gorilla:0.036038):0.033087,orangutan:0.069125):0.030457,siamang:0.099582);";
assertEquals("Fail to covert the correct tree !!!", expectedNewickTree, Tree.Utils.newick(treeModel, 6));
}
public void testLikelihoodJC69() {
System.out.println("\nTest Likelihood using JC69:");
// Sub model
Parameter freqs = new Parameter.Default(new double[]{0.25, 0.25, 0.25, 0.25});
Parameter kappa = new Parameter.Default(HKYParser.KAPPA, 1.0, 0, 100);
FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs);
HKY hky = new HKY(kappa, f);
//siteModel
GammaSiteModel siteModel = new GammaSiteModel(hky);
Parameter mu = new Parameter.Default(GammaSiteModel.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY);
siteModel.setMutationRateParameter(mu);
//treeLikelihood
SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true);
TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null,
false, false, true, false, false);
assertEquals("treeLikelihoodJC69", format.format(-1992.20564), format.format(treeLikelihood.getLogLikelihood()));
}
public void testLikelihoodK80() {
System.out.println("\nTest Likelihood using K80:");
// Sub model
Parameter freqs = new Parameter.Default(new double[]{0.25, 0.25, 0.25, 0.25});
Parameter kappa = new Parameter.Default(HKYParser.KAPPA, 27.402591, 0, 100);
FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs);
HKY hky = new HKY(kappa, f);
//siteModel
GammaSiteModel siteModel = new GammaSiteModel(hky);
Parameter mu = new Parameter.Default(GammaSiteModel.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY);
siteModel.setMutationRateParameter(mu);
//treeLikelihood
SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true);
TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null,
false, false, true, false, false);
assertEquals("treeLikelihoodK80", format.format(-1856.30305), format.format(treeLikelihood.getLogLikelihood()));
}
public void testLikelihoodHKY85() {
System.out.println("\nTest Likelihood using HKY85:");
// Sub model
Parameter freqs = new Parameter.Default(alignment.getStateFrequencies());
Parameter kappa = new Parameter.Default(HKYParser.KAPPA, 29.739445, 0, 100);
FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs);
HKY hky = new HKY(kappa, f);
//siteModel
GammaSiteModel siteModel = new GammaSiteModel(hky);
Parameter mu = new Parameter.Default(GammaSiteModel.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY);
siteModel.setMutationRateParameter(mu);
//treeLikelihood
SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true);
TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null,
false, false, true, false, false);
assertEquals("treeLikelihoodHKY85", format.format(-1825.21317), format.format(treeLikelihood.getLogLikelihood()));
}
public void testLikelihoodHKY85G() {
System.out.println("\nTest Likelihood using HKY85G:");
// Sub model
Parameter freqs = new Parameter.Default(alignment.getStateFrequencies());
Parameter kappa = new Parameter.Default(HKYParser.KAPPA, 38.829740, 0, 100);
FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs);
HKY hky = new HKY(kappa, f);
//siteModel
Parameter mu = new Parameter.Default(GammaSiteModel.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY);
Parameter shape = new Parameter.Default(GammaSiteModel.GAMMA_SHAPE, 0.137064, 0, 1000.0);
GammaSiteModel siteModel = new GammaSiteModel(hky, mu, shape, 4, null);
//treeLikelihood
SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true);
TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null,
false, false, true, false, false);
assertEquals("treeLikelihoodHKY85G", format.format(-1789.75936), format.format(treeLikelihood.getLogLikelihood()));
}
public void testLikelihoodHKY85I() {
System.out.println("\nTest Likelihood using HKY85I:");
// Sub model
Parameter freqs = new Parameter.Default(alignment.getStateFrequencies());
Parameter kappa = new Parameter.Default(HKYParser.KAPPA, 38.564672, 0, 100);
FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs);
HKY hky = new HKY(kappa, f);
//siteModel
Parameter mu = new Parameter.Default(GammaSiteModel.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY);
Parameter invar = new Parameter.Default(GammaSiteModel.PROPORTION_INVARIANT, 0.701211, 0, 1.0);
GammaSiteModel siteModel = new GammaSiteModel(hky, mu, null, 4, invar);
//treeLikelihood
SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true);
TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null,
false, false, true, false, false);
assertEquals("treeLikelihoodHKY85I", format.format(-1789.91240), format.format(treeLikelihood.getLogLikelihood()));
}
public void testLikelihoodHKY85GI() {
System.out.println("\nTest Likelihood using HKY85GI:");
// Sub model
Parameter freqs = new Parameter.Default(alignment.getStateFrequencies());
Parameter kappa = new Parameter.Default(HKYParser.KAPPA, 39.464538, 0, 100);
FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs);
HKY hky = new HKY(kappa, f);
//siteModel
Parameter mu = new Parameter.Default(GammaSiteModel.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY);
Parameter shape = new Parameter.Default(GammaSiteModel.GAMMA_SHAPE, 0.587649, 0, 1000.0);
Parameter invar = new Parameter.Default(GammaSiteModel.PROPORTION_INVARIANT, 0.486548, 0, 1.0);
GammaSiteModel siteModel = new GammaSiteModel(hky, mu, shape, 4, invar);
//treeLikelihood
SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true);
TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null,
false, false, true, false, false);
assertEquals("treeLikelihoodHKY85GI", format.format(-1789.63923), format.format(treeLikelihood.getLogLikelihood()));
}
public void testLikelihoodGTR() {
System.out.println("\nTest Likelihood using GTR:");
// Sub model
Parameter freqs = new Parameter.Default(alignment.getStateFrequencies());
FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs);
Variable<Double> rateACValue = new Parameter.Default(GTR.A_TO_C, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
Variable<Double> rateAGValue = new Parameter.Default(GTR.A_TO_G, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
Variable<Double> rateATValue = new Parameter.Default(GTR.A_TO_T, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
Variable<Double> rateCGValue = new Parameter.Default(GTR.C_TO_G, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
Variable<Double> rateCTValue = new Parameter.Default(GTR.C_TO_T, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
Variable<Double> rateGTValue = new Parameter.Default(GTR.G_TO_T, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
GTR gtr = new GTR(rateACValue, rateAGValue, rateATValue, rateCGValue, rateCTValue, rateGTValue, f);
//siteModel
Parameter mu = new Parameter.Default(GammaSiteModel.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY);
GammaSiteModel siteModel = new GammaSiteModel(gtr, mu, null, 4, null);
//treeLikelihood
SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true);
TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null,
false, false, true, false, false);
assertEquals("treeLikelihoodGTR", format.format(-1969.14584), format.format(treeLikelihood.getLogLikelihood()));
}
public void testLikelihoodGTRI() {
System.out.println("\nTest Likelihood using GTRI:");
// Sub model
Parameter freqs = new Parameter.Default(alignment.getStateFrequencies());
FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs);
Variable<Double> rateACValue = new Parameter.Default(GTR.A_TO_C, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
Variable<Double> rateAGValue = new Parameter.Default(GTR.A_TO_G, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
Variable<Double> rateATValue = new Parameter.Default(GTR.A_TO_T, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
Variable<Double> rateCGValue = new Parameter.Default(GTR.C_TO_G, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
Variable<Double> rateCTValue = new Parameter.Default(GTR.C_TO_T, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
Variable<Double> rateGTValue = new Parameter.Default(GTR.G_TO_T, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
GTR gtr = new GTR(rateACValue, rateAGValue, rateATValue, rateCGValue, rateCTValue, rateGTValue, f);
//siteModel
Parameter mu = new Parameter.Default(GammaSiteModel.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY);
Parameter invar = new Parameter.Default(GammaSiteModel.PROPORTION_INVARIANT, 0.5, 0, 1.0);
GammaSiteModel siteModel = new GammaSiteModel(gtr, mu, null, 4, invar);
//treeLikelihood
SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true);
TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null,
false, false, true, false, false);
assertEquals("treeLikelihoodGTRI", format.format(-1948.84175), format.format(treeLikelihood.getLogLikelihood()));
}
public void testLikelihoodGTRG() {
System.out.println("\nTest Likelihood using GTRG:");
// Sub model
Parameter freqs = new Parameter.Default(alignment.getStateFrequencies());
FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs);
Variable<Double> rateACValue = new Parameter.Default(GTR.A_TO_C, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
Variable<Double> rateAGValue = new Parameter.Default(GTR.A_TO_G, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
Variable<Double> rateATValue = new Parameter.Default(GTR.A_TO_T, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
Variable<Double> rateCGValue = new Parameter.Default(GTR.C_TO_G, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
Variable<Double> rateCTValue = new Parameter.Default(GTR.C_TO_T, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
Variable<Double> rateGTValue = new Parameter.Default(GTR.G_TO_T, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
GTR gtr = new GTR(rateACValue, rateAGValue, rateATValue, rateCGValue, rateCTValue, rateGTValue, f);
//siteModel
Parameter mu = new Parameter.Default(GammaSiteModel.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY);
Parameter shape = new Parameter.Default(GammaSiteModel.GAMMA_SHAPE, 0.5, 0, 100.0);
GammaSiteModel siteModel = new GammaSiteModel(gtr, mu, shape, 4, null);
//treeLikelihood
SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true);
TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null,
false, false, true, false, false);
assertEquals("treeLikelihoodGTRG", format.format(-1949.03601), format.format(treeLikelihood.getLogLikelihood()));
}
public void testLikelihoodGTRGI() {
System.out.println("\nTest Likelihood using GTRGI:");
// Sub model
Parameter freqs = new Parameter.Default(alignment.getStateFrequencies());
FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs);
Variable<Double> rateACValue = new Parameter.Default(GTR.A_TO_C, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
Variable<Double> rateAGValue = new Parameter.Default(GTR.A_TO_G, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
Variable<Double> rateATValue = new Parameter.Default(GTR.A_TO_T, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
Variable<Double> rateCGValue = new Parameter.Default(GTR.C_TO_G, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
Variable<Double> rateCTValue = new Parameter.Default(GTR.C_TO_T, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
Variable<Double> rateGTValue = new Parameter.Default(GTR.G_TO_T, 1.0, 1.0E-8, Double.POSITIVE_INFINITY);
GTR gtr = new GTR(rateACValue, rateAGValue, rateATValue, rateCGValue, rateCTValue, rateGTValue, f);
//siteModel
Parameter mu = new Parameter.Default(GammaSiteModel.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY);
Parameter shape = new Parameter.Default(GammaSiteModel.GAMMA_SHAPE, 0.5, 0, 100.0);
Parameter invar = new Parameter.Default(GammaSiteModel.PROPORTION_INVARIANT, 0.5, 0, 1.0);
GammaSiteModel siteModel = new GammaSiteModel(gtr, mu, shape, 4, invar);
//treeLikelihood
SitePatterns patterns = new SitePatterns(alignment, null, 0, -1, 1, true);
TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null,
false, false, true, false, false);
assertEquals("treeLikelihoodGTRGI", format.format(-1947.58294), format.format(treeLikelihood.getLogLikelihood()));
}
public static Test suite() {
return new TestSuite(LikelihoodTest.class);
}
} |
package test.dr.integration;
import java.io.*;
import java.util.Random;
import test.dr.beauti.BeautiTesterConfig;
import dr.app.beauti.options.*;
import dr.app.util.Utils;
/**
* GTR Parameter Estimation Tester.
*
* @author Walter Xie
* @version 1.0
* @since <pre>08/06/2009</pre>
*/
public class GTRParameterEstimationTest {
// private static final String TREE_HEIGHT = CoalescentSimulator.ROOT_HEIGHT;
// private static final String birthRateIndicator = "birthRateIndicator";
// private static final String birthRate = "birthRate";
private static final String PRE_PATH = "examples/Joseph/test/";
public GTRParameterEstimationTest() {
try{
splitTreeFiles();
} catch (IOException ioe) {
System.err.println("Unable to read or write files: " + ioe.getMessage());
}
// createBeastXMLFiles();
}
public void splitTreeFiles() throws IOException {
FileReader fileReader = new FileReader(PRE_PATH + "n.trees");
BufferedReader reader = new BufferedReader(fileReader);
FileWriter fileWriter;
BeautiTesterConfig btc = new BeautiTesterConfig();
btc.createScriptWriter(PRE_PATH + "seqgen_banch.bat");
double ac;
double ag;
double at;
double cg;
double ct = 1; // fixed
double gt;
String line = Utils.nextNonCommentLine(reader);
while (line != null) {
if (line.startsWith("tree")) {
// read 1 tree each line
String[] values = line.split(" ");
// write this tree in a file
fileWriter = new FileWriter (PRE_PATH + values[1] + ".tree"); // STATE_1000
fileWriter.write(values[values.length - 1]); // tree
fileWriter.close();
ac = getRandomNum(0.05, 0.5);
ag = getRandomNum(0.3333, 3);
at = getRandomNum(0.05, 0.5);
cg = getRandomNum(0.05, 0.5);
gt = getRandomNum(0.05, 0.5);
btc.printlnScriptWriter("C:\\Users\\dxie004\\Documents\\Seq-Gen.v1.3.2\\seq-gen -mGTR -fe -on -l1000 -r" +
Double.toString(ac) + "," + Double.toString(ag) + "," + Double.toString(at) + "," +
Double.toString(cg) + "," + Double.toString(ct) + "," + Double.toString(gt) +
" < " + values[1] + ".tree > " + values[1] + ".nex");
// C:\Users\dxie004\Documents\Seq-Gen.v1.3.2\seq-Gen.v1.3.2\seq-gen -mGTR -fe -on -l1000 -r0.1,2.1,0.2,0.08,1,0.36 < STATE_0.tree > STATE_0.nex
}
line = Utils.nextNonCommentLine(reader);
}
btc.closeScriptWriter();
fileReader.close();
}
private double getRandomNum(double min, double max) { // range
Random r = new Random();
if (max > min) {
return (max-min)*r.nextDouble() + min;
} else {
return (min-max)*r.nextDouble() + max;
}
}
public void createBeastXMLFiles() {
BeautiOptions beautiOptions;
BeautiTesterConfig btc = new BeautiTesterConfig();
btc.createScriptWriter(PRE_PATH + "beast_banch.bat");
for (int i = 0; i < 3; i++) {
beautiOptions = btc.createOptions();
btc.importFromFile(PRE_PATH + "n.nex", beautiOptions, false);
// assume only 1 partition model
PartitionModel model = beautiOptions.getPartitionModels().get(0);
// set substitution model
// model.setNucSubstitutionModel(NucModelType.GTR);
model.setNucSubstitutionModel(NucModelType.HKY);
model.setCodonHeteroPattern(null);
model.setUnlinkedSubstitutionModel(false);
model.setUnlinkedHeterogeneityModel(false);
model.setGammaHetero(false);
model.setGammaCategories(4);
model.setInvarHetero(false);
// set tree prior
beautiOptions.nodeHeightPrior = TreePrior.YULE;
beautiOptions.clockType = ClockType.STRICT_CLOCK;
// change value of parameters
Parameter para = beautiOptions.getParameter("yule.birthRate");
para.initial = 50;
// for multi-partition models, use beautiOptions.getParameter(name, model);
// remove operators
Operator op = beautiOptions.getOperator("yule.birthRate");
op.inUse = false;
op = model.getOperator("kappa");
op.inUse = false;
op = model.getOperator("frequencies");
op.inUse = false;
// set MCMC
beautiOptions.chainLength = 2000000;;
btc.setCOMMEND("java -jar beast.jar ");
btc.generate(PRE_PATH + "gtr_" + Integer.toString(i), beautiOptions);
}
btc.closeScriptWriter();
}
//Main method
public static void main(String[] args) {
new GTRParameterEstimationTest();
}
// private void randomLocalYuleTester(TreeModel treeModel, Parameter I, Parameter b, OperatorSchedule schedule) {
// MCMC mcmc = new MCMC("mcmc1");
// MCMCOptions options = new MCMCOptions();
// options.setChainLength(1000000);
// options.setUseCoercion(true);
// options.setPreBurnin(100);
// options.setTemperature(1.0);
// options.setFullEvaluationCount(2000);
// TreelengthStatistic tls = new TreelengthStatistic(TL, treeModel);
// TreeHeightStatistic rootHeight = new TreeHeightStatistic(TREE_HEIGHT, treeModel);
// Parameter m = new Parameter.Default("m", 1.0, 0.0, Double.MAX_VALUE);
// SpeciationModel speciationModel = new RandomLocalYuleModel(b, I, m, false, Units.Type.YEARS, 4);
// Likelihood likelihood = new SpeciationLikelihood(treeModel, speciationModel, "randomYule.like");
// ArrayLogFormatter formatter = new ArrayLogFormatter(false);
// MCLogger[] loggers = new MCLogger[2];
// loggers[0] = new MCLogger(formatter, 100, false);
// loggers[0].add(likelihood);
// loggers[0].add(rootHeight);
// loggers[0].add(tls);
// loggers[0].add(I);
// loggers[1] = new MCLogger(new TabDelimitedFormatter(System.out), 100000, false);
// loggers[1].add(likelihood);
// loggers[1].add(rootHeight);
// loggers[1].add(tls);
// loggers[1].add(I);
// mcmc.setShowOperatorAnalysis(true);
// mcmc.init(options, likelihood, Prior.UNIFORM_PRIOR, schedule, loggers);
// mcmc.run();
// List<Trace> traces = formatter.getTraces();
// ArrayTraceList traceList = new ArrayTraceList("yuleModelTest", traces, 0);
// for (int i = 1; i < traces.size(); i++) {
// traceList.analyseTrace(i);
// TraceCorrelation tlStats =
// traceList.getCorrelationStatistics(traceList.getTraceIndex("root." + birthRateIndicator));
// System.out.println("mean = " + tlStats.getMean());
// System.out.println("expected mean = 0.5");
// assertExpectation("root." + birthRateIndicator, tlStats, 0.5);
} |
package core.languageHandler.compiler;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import argo.jdom.JsonNode;
import argo.jdom.JsonNodeFactories;
import core.languageHandler.Language;
import core.userDefinedTask.DormantUserDefinedTask;
import core.userDefinedTask.UserDefinedAction;
import utilities.FileUtility;
import utilities.Function;
import utilities.JSONUtility;
import utilities.Pair;
import utilities.RandomUtil;
import utilities.StringUtilities;
import utilities.swing.SwingUtil;
public class JavaNativeCompiler extends AbstractNativeCompiler {
private DynamicClassLoader classLoader;
private final String[] packageTree;
private final String defaultClassName;
private String className;
private String[] classPaths;
private File home;
public JavaNativeCompiler(String className, String[] packageTree, String[] classPaths) {
this.packageTree = packageTree;
this.defaultClassName = className;
this.classPaths = classPaths;
classLoader = new DynamicClassLoader(getClassPaths(), ClassLoader.getSystemClassLoader());
home = new File(System.getProperty("java.home"));
}
@Override
public Pair<DynamicCompilerOutput, UserDefinedAction> compile(String sourceCode, File classFile) {
className = FileUtility.removeExtension(classFile).getName();
if (!classFile.getParentFile().getAbsolutePath().equals(new File(FileUtility.joinPath(packageTree)).getAbsolutePath())) {
getLogger().warning("Class file " + classFile.getAbsolutePath() + "is not consistent with packageTree");
} else if (!classFile.getName().endsWith(".class")) {
getLogger().warning("Java class file " + classFile.getAbsolutePath() + " does not end with .class. Compiling using source code");
return compile(sourceCode);
} else if (!FileUtility.fileExists(classFile)) {
getLogger().warning("Cannot find file " + classFile.getAbsolutePath() + ". Compiling using source code");
return compile(sourceCode);
}
try {
Pair<DynamicCompilerOutput, UserDefinedAction> output = loadClass(className);
getLogger().info("Skipped compilation and loaded object file.");
className = null;
return output;
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IOException e) {
getLogger().log(Level.WARNING, "Cannot load class file " + classFile.getAbsolutePath(), e);
getLogger().info("Compiling using source code");
return compile(sourceCode);
}
}
@Override
public Pair<DynamicCompilerOutput, UserDefinedAction> compile(String sourceCode) {
String originalPath = System.getProperty("java.home");
// This no longer works in JDK 9 (but why?).
// We are forced to run the program in JDK in order to be
// able to retrieve the compiler.
System.setProperty("java.home", home.getAbsolutePath());
if (!sourceCode.contains("class " + defaultClassName)) {
getLogger().warning("Cannot find class " + defaultClassName + " in source code.");
return new Pair<DynamicCompilerOutput, UserDefinedAction>(DynamicCompilerOutput.SOURCE_MISSING_PREFORMAT_ELEMENTS, null);
}
String newClassName = className;
if (newClassName == null) {
newClassName = getDummyPrefix() + RandomUtil.randomID();
}
sourceCode = sourceCode.replaceFirst("class " + defaultClassName, "class " + newClassName);
try {
File compiling = getSourceFile(newClassName);
if (compiling.getParentFile().exists() || compiling.getParentFile().mkdirs()) {
try {
if (!FileUtility.writeToFile(sourceCode, compiling, false)) {
getLogger().warning("Cannot write source code to file.");
return new Pair<DynamicCompilerOutput, UserDefinedAction>(DynamicCompilerOutput.SOURCE_NOT_ACCESSIBLE, new DormantUserDefinedTask(sourceCode));
}
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
getLogger().warning("No java compiler found. Set class path points to JDK in setting?");
return new Pair<DynamicCompilerOutput, UserDefinedAction>(DynamicCompilerOutput.COMPILER_MISSING, new DormantUserDefinedTask(sourceCode));
}
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, Locale.US, StandardCharsets.UTF_8);
// This sets up the class path that the compiler will use.
// Added the .jar file that contains the [className] interface within in it...
List<String> optionList = new ArrayList<String>();
optionList.add("-classpath");
String paths = System.getProperty("java.class.path");
if (classPaths.length > 0) {
paths += ";" + StringUtilities.join(classPaths, ";");
}
optionList.add(paths);
Iterable<? extends JavaFileObject> compilationUnit
= fileManager.getJavaFileObjectsFromFiles(Arrays.asList(compiling));
JavaCompiler.CompilationTask task = compiler.getTask(
null,
fileManager,
diagnostics,
optionList,
null,
compilationUnit);
/********************************************************************************************* Compilation Requirements **/
if (task.call()) {
Pair<DynamicCompilerOutput, UserDefinedAction> output = loadClass(newClassName);
getLogger().info("Successfully compiled class " + defaultClassName);
return output;
} else {
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
getLogger().warning("Error on line " + diagnostic.getLineNumber() +" in " + diagnostic.getSource().toUri() + "\n");
getLogger().warning(diagnostic.getMessage(Locale.US));
}
}
fileManager.close();
} catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException exp) {
getLogger().log(Level.WARNING, "Error during compilation...", exp);
}
}
getLogger().warning("Cannot compile class " + defaultClassName);
return new Pair<DynamicCompilerOutput, UserDefinedAction>(DynamicCompilerOutput.COMPILATION_ERROR, null);
} finally {
className = null;
System.setProperty("java.home", originalPath);
}
}
private Pair<DynamicCompilerOutput, UserDefinedAction> loadClass(String loadClassName) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
classLoader.addURL(new File("./").toURI().toURL());
Class<?> loadedClass = classLoader.loadClass(StringUtilities.join(packageTree, ".") + "." + loadClassName);
Object object = null;
try {
object = loadedClass.getDeclaredConstructor().newInstance();
} catch (IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
getLogger().log(Level.WARNING, "Unable to create a new instance...", e);
return new Pair<DynamicCompilerOutput, UserDefinedAction>(DynamicCompilerOutput.CONSTRUCTOR_ERROR, null);
}
getLogger().log(Level.FINE, "Successfully loaded class " + loadClassName);
UserDefinedAction output = (UserDefinedAction) object;
output.setSourcePath(getSourceFile(loadClassName).getAbsolutePath());
return new Pair<DynamicCompilerOutput, UserDefinedAction>(DynamicCompilerOutput.COMPILATION_SUCCESS, output);
}
/**
* Construct an array of URLs from array of string representing list of
* class paths.
*
* @return array of URLs representing the class paths.
*/
private URL[] getClassPaths() {
List<URL> output = new ArrayList<>();
for (String path : classPaths) {
try {
output.add(new File(path).toURI().toURL());
} catch (MalformedURLException e) {
getLogger().log(Level.WARNING, "Unable to construct URL for classpath " + path, e);
}
}
return output.toArray(new URL[output.size()]);
}
@Override
protected File getSourceFile(String compileClass) {
return new File(FileUtility.joinPath(FileUtility.joinPath(packageTree), compileClass + ".java"));
}
@Override
public Language getName() {
return Language.JAVA;
}
@Override
public String getExtension() {
return ".java";
}
@Override
public String getObjectExtension() {
return ".class";
}
@Override
public File getPath() {
return home.getAbsoluteFile();
}
@Override
public void setPath(File path) {
home = path;
}
@Override
public boolean parseCompilerSpecificArgs(JsonNode node) {
if (!node.isArrayNode("classpath")) {
return false;
}
List<String> paths = new ArrayList<>();
JSONUtility.addAllJson(node.getArrayNode("classpath"), new Function<JsonNode, String>(){
@Override
public String apply(JsonNode d) {
return d.getStringValue().toString();
}
}, paths);
// Override current class paths
classPaths = paths.toArray(classPaths);
try {
applyClassPath();
} catch (MalformedURLException | NoSuchMethodException | SecurityException |
IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
getLogger().log(Level.WARNING, "Unable to apply class path.", e);
return false;
}
return true;
}
@Override
public JsonNode getCompilerSpecificArgs() {
List<JsonNode> paths = new ArrayList<>(classPaths.length);
for (String path : classPaths) {
paths.add(JsonNodeFactories.string(path));
}
return JsonNodeFactories.object(JsonNodeFactories.field("classpath", JsonNodeFactories.array(paths)));
}
@Override
protected String getDummyPrefix() {
return "CC_";
}
@Override
public Logger getLogger() {
return Logger.getLogger(JavaNativeCompiler.class.getName());
}
public void applyClassPath() throws MalformedURLException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// Hacky reflection solution to alter the global classpath.
// This no longer works for JDK 9 since system class loader is no longer a URLClassLoader.
// JDK 9 also emits warnings as reflection package tries to access addURL method.
// Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
// method.setAccessible(true);
// for (String path : classPaths) {
// method.invoke(ClassLoader.getSystemClassLoader(), new Object[]{new File(path).toURI().toURL()});
// Add all URL to existing class loader.
for (URL url : getClassPaths()) {
classLoader.addURL(url);
}
}
/**
* Since code loaded by this class loader is user written (hopefully),
* exposing addURL should not be a concern.
*/
private static final class DynamicClassLoader extends URLClassLoader {
public DynamicClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
}
/**
* Note that adding a path multiple times is fine since underlying
* implementation treats it as no-op.
*/
@Override
protected void addURL(URL url) {
super.addURL(url);
}
}
@Override
public void promptChangePath(JFrame parent) {
JFileChooser chooser = new JFileChooser(getPath());
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (chooser.showDialog(parent, "Set Java home") == JFileChooser.APPROVE_OPTION) {
setPath(chooser.getSelectedFile());
}
}
@Override
public void changeCompilationButton(JButton bCompile) {
bCompile.setText("Compile source");
}
@Override
public void configure() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(new JLabel("It is advisable to restart the program if you remove a path from the class path list."));
panel.add(new JLabel("Class paths (1 path per row)"));
panel.add(new JLabel("E.g. D:\\path\\to\\dir\\the_jar.jar"));
JTextArea texts = new JTextArea(StringUtilities.join(classPaths, "\n"));
JScrollPane scrollPane = new JScrollPane(texts);
texts.setRows(10);
texts.setColumns(80);
panel.add(scrollPane);
if (!SwingUtil.DialogUtil.genericInput("Configure Java compiler", panel)) {
return;
}
String[] paths = texts.getText().split("\n");
ArrayList<String> validPaths = new ArrayList<>();
for (String path : paths) {
if (path.trim().isEmpty()) {
continue;
}
if (Files.isReadable(Paths.get(path))) {
validPaths.add(path);
} else {
getLogger().log(Level.WARNING, "The path " + path + " is not readable.");
return;
}
}
classPaths = new String[validPaths.size()];
for (int i = 0; i < validPaths.size(); i++) {
classPaths[i] = validPaths.get(i);
}
try {
applyClassPath();
} catch (Exception e) {
getLogger().log(Level.WARNING, "Unable to configure the new classpath.", e);
}
}
} |
package de.jeha.demo.resources;
import com.codahale.metrics.annotation.Timed;
import de.jeha.demo.core.Hello;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import java.util.concurrent.atomic.AtomicInteger;
@Path("/")
public class HelloWorldResource {
private String message;
private final AtomicInteger counter = new AtomicInteger();
@GET
@Path("/hello-world")
@Produces(MediaType.APPLICATION_JSON)
@Timed
public Object hello(@QueryParam(value = "name") String name) {
return new Hello(counter.incrementAndGet(), name == null ? getMessage() : getMessage() + ", " + name);
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
} |
package com.java.blick.dates;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;
import org.junit.Test;
public class DateConvertTest {
private Date date;
private Instant instant;
private Calendar calendar;
private LocalDate localDate;
private LocalDateTime localDateTime;
private ZonedDateTime zonedDateTime;
private long millis = 0;
private Timestamp timestamp;
@Test
public void converting_from_to_date() {
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(2018, 1, 1, 12, 30);
date = cal.getTime();
instant = DateConvert.from(date).toInstant();
assertThat(DateConvert.from(instant).toDate(), is(date));
calendar = DateConvert.from(date).toCalendar();
assertThat(DateConvert.from(calendar).toDate(), is(date));
localDate = DateConvert.from(date).withDefaultZone().toLocalDate();
assertThat(DateConvert.from(localDate).withLocalTime(12, 30, 0, 0).withDefaultZoneId().toDate(), is(date));
localDateTime = DateConvert.from(date).withDefaultZone().toLocalDateTime();
assertThat(DateConvert.from(localDateTime).withDefaultZoneId().toDate(), is(date));
zonedDateTime = DateConvert.from(date).toZonedDateTime();
assertThat(DateConvert.from(zonedDateTime).toDate(), is(date));
millis = DateConvert.from(date).toMillis();
assertThat(DateConvert.from(millis).toDate(), is(date));
timestamp = DateConvert.from(date).toTimestamp();
assertThat(DateConvert.from(timestamp).toDate(), is(date));
}
@Test
public void converting_from_to_calendar() {
calendar = Calendar.getInstance();
calendar.clear();
calendar.set(2018, 1, 1, 12, 30);
date = DateConvert.from(calendar).toDate();
assertThat(DateConvert.from(date).toCalendar(), is(calendar));
instant = DateConvert.from(calendar).toInstant();
assertThat(DateConvert.from(instant).toCalendar(), is(calendar));
localDate = DateConvert.from(calendar).toLocalDate();
assertThat(DateConvert.from(localDate).withLocalTime(12, 30, 0, 0).withDefaultZoneId().toCalendar(),
is(calendar));
localDateTime = DateConvert.from(calendar).toLocalDateTime();
assertThat(DateConvert.from(localDate).withLocalTime(12, 30, 0, 0).withDefaultZoneId().toCalendar(),
is(calendar));
zonedDateTime = DateConvert.from(calendar).toZonedDateTimeWithDefaultZone();
assertThat(DateConvert.from(zonedDateTime).toCalendar(), is(calendar));
millis = DateConvert.from(calendar).toMillis();
assertThat(DateConvert.from(millis).toCalendar(), is(calendar));
timestamp = DateConvert.from(calendar).toTimestamp();
assertThat(DateConvert.from(timestamp).toCalendar(), is(calendar));
}
@Test
public void converting_from_to_instant() {
calendar = Calendar.getInstance();
calendar.clear();
calendar.set(2018, 1, 1, 10, 15);
instant = calendar.getTime().toInstant();
date = DateConvert.from(instant).toDate();
assertThat(DateConvert.from(date).toInstant(), is(instant));
calendar = DateConvert.from(instant).toCalendar();
assertThat(DateConvert.from(calendar).toInstant(), is(instant));
localDate = DateConvert.from(instant).toLocalDate();
assertThat(DateConvert.from(localDate).withLocalTime(10, 15, 0, 0).withDefaultZoneId().toInstant(),
is(instant));
localDateTime = DateConvert.from(instant).toLocalDateTime();
assertThat(DateConvert.from(localDate).withLocalTime(10, 15, 0, 0).withDefaultZoneId().toInstant(),
is(instant));
zonedDateTime = DateConvert.from(instant).toZonedDateTimeWithDefaultZone();
assertThat(DateConvert.from(zonedDateTime).toInstant(), is(instant));
millis = DateConvert.from(instant).toMillis();
assertThat(DateConvert.from(millis).toInstant(), is(instant));
timestamp = DateConvert.from(instant).toTimestamp();
assertThat(DateConvert.from(timestamp).toInstant(), is(instant));
}
} |
package com.uwetrottmann.trakt5;
import com.uwetrottmann.trakt5.entities.BaseEpisode;
import com.uwetrottmann.trakt5.entities.BaseMovie;
import com.uwetrottmann.trakt5.entities.BaseRatedEntity;
import com.uwetrottmann.trakt5.entities.BaseSeason;
import com.uwetrottmann.trakt5.entities.BaseShow;
import com.uwetrottmann.trakt5.entities.CastMember;
import com.uwetrottmann.trakt5.entities.Credits;
import com.uwetrottmann.trakt5.entities.CrewMember;
import com.uwetrottmann.trakt5.entities.Ratings;
import com.uwetrottmann.trakt5.entities.Stats;
import com.uwetrottmann.trakt5.enums.Type;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.junit.BeforeClass;
import retrofit2.Call;
import retrofit2.Response;
import java.io.IOException;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
public class BaseTestCase {
protected static final String TEST_CLIENT_ID = "35a671df22d3d98b09aab1c0bc52977e902e696a7704cab94f4d12c2672041e4";
public static final String TEST_ACCESS_TOKEN = "5990f20700607b768f878c25446483ee3465d2dccd1f44e61f2a42f91b0ddc09"; // "sgtest" on production
private static final boolean DEBUG = true;
private static final TraktV2 trakt = new TestTraktV2(TEST_CLIENT_ID);
protected static final Integer DEFAULT_PAGE_SIZE = 10;
static class TestTraktV2 extends TraktV2 {
public TestTraktV2(String apiKey) {
super(apiKey);
}
public TestTraktV2(String apiKey, String clientSecret, String redirectUri) {
super(apiKey, clientSecret, redirectUri);
}
@Override
protected void setOkHttpClientDefaults(OkHttpClient.Builder builder) {
super.setOkHttpClientDefaults(builder);
if (DEBUG) {
// add logging
HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String s) {
// standard output is easier to read
System.out.println(s);
}
});
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addInterceptor(logging);
}
}
}
@BeforeClass
public static void setUpOnce() {
trakt.accessToken(TEST_ACCESS_TOKEN);
}
protected TraktV2 getTrakt() {
return trakt;
}
public <T> T executeCall(Call<T> call) throws IOException {
Response<T> response = call.execute();
if (response.isSuccessful()) {
return response.body();
} else {
handleFailedResponse(response);
}
return null;
}
public static void assertSuccessfulResponse(Response response) {
if (!response.isSuccessful()) {
handleFailedResponse(response);
}
}
private static void handleFailedResponse(Response response) {
if (response.code() == 401) {
fail("Authorization required, supply a valid OAuth access token: "
+ response.code() + " " + response.message());
} else {
fail("Request failed: " + response.code() + " " + response.message());
}
}
protected static <T extends BaseRatedEntity> void assertRatedEntities(List<T> ratedMovies) {
for (BaseRatedEntity movie : ratedMovies) {
assertThat(movie.rated_at).isNotNull();
assertThat(movie.rating).isNotNull();
}
}
public void assertRatings(Ratings ratings) {
// rating can be null, but we use a show where we can be sure it's rated
assertThat(ratings.rating).isGreaterThanOrEqualTo(0);
assertThat(ratings.votes).isGreaterThanOrEqualTo(0);
assertThat(ratings.distribution).hasSize(10);
}
public void assertStats(Stats stats) {
assertThat(stats.watchers).isGreaterThanOrEqualTo(0);
assertThat(stats.plays).isGreaterThanOrEqualTo(0);
assertThat(stats.collectors).isGreaterThanOrEqualTo(0);
assertThat(stats.comments).isGreaterThanOrEqualTo(0);
assertThat(stats.lists).isGreaterThanOrEqualTo(0);
assertThat(stats.votes).isGreaterThanOrEqualTo(0);
}
public void assertShowStats(Stats stats) {
assertStats(stats);
assertThat(stats.collected_episodes).isGreaterThanOrEqualTo(0);
}
protected static void assertSyncMovies(List<BaseMovie> movies, String type) {
for (BaseMovie movie : movies) {
assertThat(movie.movie).isNotNull();
switch (type) {
case "collection":
assertThat(movie.collected_at).isNotNull();
break;
case "watched":
assertThat(movie.plays).isPositive();
assertThat(movie.last_watched_at).isNotNull();
break;
case "watchlist":
assertThat(movie.listed_at).isNotNull();
break;
}
}
}
protected static void assertSyncShows(List<BaseShow> shows, String type) {
for (BaseShow show : shows) {
assertThat(show.show).isNotNull();
if ("collection".equals(type)) {
assertThat(show.last_collected_at).isNotNull();
} else if ("watched".equals(type)) {
assertThat(show.plays).isPositive();
assertThat(show.last_watched_at).isNotNull();
}
for (BaseSeason season : show.seasons) {
assertThat(season.number).isGreaterThanOrEqualTo(0);
for (BaseEpisode episode : season.episodes) {
assertThat(episode.number).isGreaterThanOrEqualTo(0);
if ("collection".equals(type)) {
assertThat(episode.collected_at).isNotNull();
} else if ("watched".equals(type)) {
assertThat(episode.plays).isPositive();
assertThat(episode.last_watched_at).isNotNull();
}
}
}
}
}
public void assertCast(Credits credits, Type type) {
for (CastMember castMember : credits.cast) {
assertThat(castMember.character).isNotNull();
if (type == Type.SHOW) {
assertThat(castMember.movie).isNull();
assertThat(castMember.show).isNotNull();
assertThat(castMember.person).isNull();
} else if (type == Type.MOVIE) {
assertThat(castMember.movie).isNotNull();
assertThat(castMember.show).isNull();
assertThat(castMember.person).isNull();
} else if (type == Type.PERSON) {
assertThat(castMember.movie).isNull();
assertThat(castMember.show).isNull();
assertThat(castMember.person).isNotNull();
}
}
}
public void assertCrew(Credits credits, Type type) {
if (credits.crew != null) {
assertCrewMembers(credits.crew.production, type);
assertCrewMembers(credits.crew.writing, type);
assertCrewMembers(credits.crew.directing, type);
assertCrewMembers(credits.crew.costumeAndMakeUp, type);
assertCrewMembers(credits.crew.sound, type);
assertCrewMembers(credits.crew.art, type);
assertCrewMembers(credits.crew.camera, type);
}
}
public void assertCrewMembers(List<CrewMember> crew, Type type) {
if (crew == null) {
return;
}
for (CrewMember crewMember : crew) {
assertThat(crewMember.job).isNotNull(); // may be empty, so not checking for now
if (type == Type.SHOW) {
assertThat(crewMember.movie).isNull();
assertThat(crewMember.show).isNotNull();
assertThat(crewMember.person).isNull();
} else if (type == Type.MOVIE) {
assertThat(crewMember.movie).isNotNull();
assertThat(crewMember.show).isNull();
assertThat(crewMember.person).isNull();
} else if (type == Type.PERSON) {
assertThat(crewMember.movie).isNull();
assertThat(crewMember.show).isNull();
assertThat(crewMember.person).isNotNull();
}
}
}
} |
package de.tudarmstadt.lt.wsi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import de.tudarmstadt.lt.util.IndexUtil;
import de.tudarmstadt.lt.util.IndexUtil.Index;
import de.tudarmstadt.lt.util.MapUtil;
public class ClusterReaderWriter {
final static Charset UTF_8 = Charset.forName("UTF-8");
final static Random r = new Random();
public static void writeClusters(Writer writer, Map<String, List<Cluster<String>>> clusters) throws IOException {
writeClusters(writer, clusters, IndexUtil.<String>getIdentityIndex());
}
public static <N> void writeClusters(Writer writer, Map<String, List<Cluster<N>>> clusters, Index<String, N> index) throws IOException {
for (Entry<String, List<Cluster<N>>> clusterList : clusters.entrySet()) {
for (Cluster<N> c : clusterList.getValue()) {
writeCluster(writer, c, index);
}
}
}
public static void writeCluster(Writer writer, Cluster<String> cluster) throws IOException {
writeCluster(writer, cluster, IndexUtil.<String>getIdentityIndex());
}
public static <N> void writeCluster(Writer writer, Cluster<N> cluster, Index<String, N> index) throws IOException {
writer.write(cluster.name + "\t" + cluster.clusterId + "\t" + cluster.label + "\t");
writer.write(StringUtils.join(IndexUtil.map(cluster.nodes, index), " "));
if (!cluster.featureScores.isEmpty()) {
writer.write("\t");
Map<N, Float> sortedFeatureCounts = MapUtil.sortMapByValue(cluster.featureScores);
MapUtil.writeMap(IndexUtil.mapKeys(sortedFeatureCounts, index), writer, ":", " ");
}
writer.write("\n");
}
public static Map<String, List<Cluster<String>>> readClusters(Reader in) throws IOException {
return readClusters(in, IndexUtil.<String>getIdentityIndex(), null);
}
public static <N> Map<N, List<Cluster<N>>> readClusters(Reader in, Index<String, N> index, Set<String> whitelist) throws IOException {
System.out.println("Reading clusters...");
Map<N, List<Cluster<N>>> clusters = new HashMap<N, List<Cluster<N>>>();
BufferedReader reader = new BufferedReader(in);
String line;
while ((line = reader.readLine()) != null) {
String[] lineSplits = line.split("\t");
if (whitelist != null && !whitelist.contains(lineSplits[0])) {
continue;
}
N clusterName = index.getIndex(lineSplits[0]);
int clusterId = Integer.parseInt(lineSplits[1]);
N clusterLabel = index.getIndex(lineSplits[2]);
String[] clusterNodes = lineSplits[3].split(" ");
Set<N> clusterNodeSet = new HashSet<N>(5);
// TODO: replace by IndexUtil.map ...
for (String clusterNode : clusterNodes) {
if (!clusterNode.isEmpty()) {
clusterNodeSet.add(index.getIndex(clusterNode));
}
}
int m = clusterNodeSet.size();
Map<N, Float> clusterFeatureProbs = new HashMap<N, Float>();
Map<N, Float> clusterFeatureScores = new HashMap<N, Float>();
if (lineSplits.length >= 5) {
String[] clusterFeatures = lineSplits[4].split(" ");
final int MAX_NUM_FEATURES = Integer.MAX_VALUE;
int i = 0;
for (String featureScorePair : clusterFeatures) {
if (i >= MAX_NUM_FEATURES) {
break;
}
String[] featureArr = splitNCols(featureScorePair, ":", 8);
// String[] featureArr = featureScorePair.split(":");
// TODO: remove isEmpty() check
if (featureArr.length == 8) {
try {
N feature = index.getIndex(featureArr[0]);
// float lmi = Float.parseFloat(featureArr[1]);
float avgProb = Float.parseFloat(featureArr[2]);
float avgCov = Float.parseFloat(featureArr[3]);
long wc = Long.parseLong(featureArr[4]);
long fc = Long.parseLong(featureArr[5]);
// long wfc = Long.parseLong(featureArr[6]);
float avgWc = (float)wc / m;
// float avgWfc = (float)wfc / m;
long n = Long.parseLong(featureArr[7]);
float normalizedAvgWfc = avgCov * avgWc;
float normalizedAvgProb = normalizedAvgWfc / fc;
// float normalizedAvgCov = normalizedAvgWfc / fc;
// float score = normalizedAvgProb * avgCov;
float score = (float)(normalizedAvgWfc * normalizedAvgWfc) / (avgWc * fc);
float normalizedLmi = normalizedAvgWfc*(float)(Math.log(n*normalizedAvgWfc) - Math.log(avgWc*fc));
// float pmi = normalizedP_AB / (wc * fc);
float pmi = avgProb * n / (float)wc;
if (pmi > 10.0f) {
clusterFeatureProbs.put(feature, avgProb);
clusterFeatureScores.put(feature, score);
} else {
// System.out.println("foo");
}
} catch (NumberFormatException e) {
System.err.println("Error (1): malformatted feature-count pair: " + featureScorePair);
}
} else {
System.err.println("Error (2): malformatted feature-count pair: " + featureScorePair);
}
i++;
}
}
List<N> clusterFeaturesSorted = MapUtil.sortMapKeysByValue(clusterFeatureScores);
Set<N> clusterFeatures = new HashSet<N>();
Map<N, Float> clusterFeatureProbsFiltered = new HashMap<N, Float>();
int i = 0;
int limit = 10000;
for(N feature : clusterFeaturesSorted) {
if (i >= limit) {
break;
}
clusterFeatureProbsFiltered.put(feature, clusterFeatureProbs.get(feature));
clusterFeatures.add(feature);
i++;
}
Cluster<N> c = new Cluster<N>(clusterName, clusterId, clusterLabel, clusterNodeSet, clusterFeatureProbs, clusterFeaturesSorted, clusterFeatures);
MapUtil.addTo(clusters, clusterName, c, ArrayList.class);
}
return clusters;
}
static String[] splitNCols(String line, String sep, int n) {
String[] _cols = line.split(sep);
String[] cols = new String[n];
for (int i = 1; i < n; i++) {
cols[n-i] = _cols[_cols.length-i];
}
cols[0] = line.substring(0, line.indexOf(":"));
return cols;
}
public static <N> Map<N, String> readBaselineMapping(Reader in, Index<String, N> index, Set<String> whitelist, Map<N, List<Cluster<N>>> clusters) throws IOException {
Map<N, String> mapping = new HashMap<N, String>();
BufferedReader reader = new BufferedReader(in);
String line;
while ((line = reader.readLine()) != null) {
String[] lineSplits = line.split("\t");
if (whitelist != null && !whitelist.contains(lineSplits[0])) {
continue;
}
N jo = index.getIndex(lineSplits[0]);
String[] resources = lineSplits[1].split(" ");
String resource = resources[0].split(":")[0];
mapping.put(jo, resource);
}
return mapping;
}
public static <N> Map<Cluster<N>, String> readClusterMapping(Reader in, Index<String, N> index, Set<String> whitelist, Map<N, List<Cluster<N>>> clusters) throws IOException {
Map<Cluster<N>, String> mapping = new HashMap<Cluster<N>, String>();
BufferedReader reader = new BufferedReader(in);
String line;
while ((line = reader.readLine()) != null) {
String[] lineSplits = line.split("\t");
if (whitelist != null && !whitelist.contains(lineSplits[0])) {
continue;
}
N jo = index.getIndex(lineSplits[0]);
int clusterId = Integer.parseInt(lineSplits[1]);
String[] resources = lineSplits[2].split(" ");
String resource = resources[0].split(":")[0];
Cluster<N> sense = null;
List<Cluster<N>> clusterSet = clusters.get(jo);
for (Cluster<N> c : clusterSet) {
if (c.clusterId == clusterId) {
sense = c;
break;
}
}
mapping.put(sense, resource);
}
return mapping;
}
} |
package io.techcode.logbulk.util;
import io.techcode.logbulk.VertxTestBase;
import io.vertx.core.Handler;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
/**
* Test for Flusher.
*/
@RunWith(VertxUnitRunner.class)
public class FlusherTest extends VertxTestBase {
@Test(expected = NullPointerException.class)
public void testConstructor1() throws Exception {
new Flusher(null, 1);
}
@Test(expected = IllegalArgumentException.class)
public void testConstructor2() throws Exception {
new Flusher(vertx, -1);
}
@Test public void testFlush1() throws Exception {
Flusher flusher = new Flusher(vertx, 10);
final boolean[] called = {false};
flusher.handler(h -> called[0] = true);
flusher.flush();
assertTrue(called[0]);
}
@Test public void testFlush2(TestContext ctx) throws Exception {
Flusher flusher = new Flusher(vertx, 100);
final boolean[] called = {false};
flusher.handler(h -> called[0] = true);
flusher.start();
vertx.setTimer(150, h -> ctx.assertTrue(called[0]));
}
@Test public void testFlush3(TestContext ctx) throws Exception {
Flusher flusher = new Flusher(vertx, 100);
final boolean[] called = {false};
flusher.handler(h -> called[0] = true);
flusher.start();
vertx.setTimer(150, h -> flusher.flushed());
vertx.setTimer(200, h -> ctx.assertFalse(called[0]));
}
@Test public void testFlush4(TestContext ctx) throws Exception {
Flusher flusher = new Flusher(vertx, 100);
final boolean[] called = {false};
flusher.handler(h -> called[0] = true);
flusher.start();
flusher.stop();
vertx.setTimer(200, h -> ctx.assertFalse(called[0]));
}
@Test public void testFlush5() throws Exception {
Flusher flusher = new Flusher(vertx, 100);
Handler<Void> handler = mock(Handler.class);
flusher.handler(handler);
flusher.handler(null);
flusher.flush();
verify(handler, never()).handle(null);
}
} |
package hprose.io.unserialize;
import static hprose.io.HproseTags.TagNull;
import static hprose.io.HproseTags.TagRef;
import static hprose.io.HproseTags.TagString;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.ByteBuffer;
import java.util.regex.Pattern;
final class PatternUnserializer implements HproseUnserializer {
public final static PatternUnserializer instance = new PatternUnserializer();
public final Object read(HproseReader reader, ByteBuffer buffer, Class<?> cls, Type type) throws IOException {
int tag = buffer.get();
if (tag == TagNull) return null;
if (tag == TagString) {
Pattern pattern = Pattern.compile(ValueReader.readString(buffer));
reader.refer.set(pattern);
return pattern;
}
if (tag == TagRef) {
Object obj = reader.readRef(buffer);
if (obj instanceof Pattern) {
return obj;
}
if (obj instanceof char[]) {
return Pattern.compile(new String((char[])obj));
}
return Pattern.compile(obj.toString());
}
throw ValueReader.castError(reader.tagToString(tag), Pattern.class);
}
public final Object read(HproseReader reader, InputStream stream, Class<?> cls, Type type) throws IOException {
int tag = stream.read();
if (tag == TagNull) return null;
if (tag == TagString) {
Pattern pattern = Pattern.compile(ValueReader.readString(stream));
reader.refer.set(pattern);
return pattern;
}
if (tag == TagRef) {
Object obj = reader.readRef(stream);
if (obj instanceof Pattern) {
return obj;
}
if (obj instanceof char[]) {
return Pattern.compile(new String((char[])obj));
}
return Pattern.compile(obj.toString());
}
throw ValueReader.castError(reader.tagToString(tag), Pattern.class);
}
} |
package de.cpgaertner.edu.inf.api.level.player;
import de.cpgaertner.edu.inf.api.level.Item;
import lombok.Getter;
import lombok.Setter;
import java.util.HashMap;
import java.util.Map;
public class Inventory {
@Getter @Setter protected Map<Integer, Item> items;
@Getter protected final int slots;
public Inventory(int slots) {
this.slots = slots;
this.items = new HashMap<>(slots);
}
public void add(int slot, Item item) throws InsufficientInventorySpaceException {
if (getItems().get(slot) != null) {
throw new InsufficientInventorySpaceException();
}
getItems().put(slot, item);
}
public void add(Item item) throws InsufficientInventorySpaceException {
add(getItems().size(), item);
}
public void remove(int slot) {
getItems().remove(slot);
}
public void clear() {
getItems().clear();
}
} |
package org.xwiki.livedata.test.po;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.model.reference.SpaceReference;
import org.xwiki.test.ui.po.BaseElement;
import org.xwiki.test.ui.po.FormContainerElement;
import org.xwiki.test.ui.po.SuggestInputElement;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Provides the operations to interact with a Live Data when displayed with a table layout.
*
* @version $Id$
* @since 13.4RC1
*/
public class TableLayoutElement extends BaseElement
{
private static final String INNER_HTML_ATTRIBUTE = "innerHTML";
private static final String CLASS_HTML_ATTRIBUTE = "class";
/**
* A matcher for the cell containing links. The matcher assert of a given {@link WebElement} contains a {@code a}
* tag with the expected text and link.
*/
private static class CellWithLinkMatcher extends TypeSafeMatcher<WebElement>
{
private final String text;
private final String link;
private final URI linkUri;
/**
* Initializes the matcher with the expected text and link.
*
* @param text the expected text of the {@code a} tag
* @param link the expected link of the {@code a} tag
*/
CellWithLinkMatcher(String text, String link)
{
this.text = text;
this.link = link;
this.linkUri = URI.create(this.link);
}
@Override
protected boolean matchesSafely(WebElement item)
{
String hrefAttribute = "href";
return item.findElements(By.tagName("a"))
.stream()
.anyMatch(aTag -> {
String href = aTag.getAttribute(hrefAttribute);
return Objects.equals(aTag.getText(), this.text)
&& (Objects.equals(linkUri, URI.create(href))
|| Objects.equals(linkUri, removeTrailingSlash(href)));
});
}
private URI removeTrailingSlash(String href)
{
URI initialUri = URI.create(href);
URIBuilder uriBuilder = new URIBuilder(initialUri);
List<String> pathSegments = uriBuilder.getPathSegments();
URI uri;
if (pathSegments.get(pathSegments.size() - 1).equals("")) {
pathSegments.remove(pathSegments.size() - 1);
try {
uri = uriBuilder.setPathSegments(pathSegments).build();
} catch (URISyntaxException e) {
uri = initialUri;
}
} else {
uri = initialUri;
}
return uri;
}
@Override
protected void describeMismatchSafely(WebElement item, Description mismatchDescription)
{
mismatchDescription.appendText(item.getAttribute(INNER_HTML_ATTRIBUTE));
}
@Override
public void describeTo(Description description)
{
description.appendText("a link with text ");
description.appendValue(this.text);
description.appendText(" and link ");
description.appendValue(this.link);
}
}
private static class WebElementTextMatcher extends TypeSafeMatcher<WebElement>
{
private final String value;
WebElementTextMatcher(String value)
{
this.value = value;
}
@Override
protected boolean matchesSafely(WebElement item)
{
return item.getText().equals(this.value);
}
@Override
protected void describeMismatchSafely(WebElement item, Description mismatchDescription)
{
mismatchDescription.appendText(item.getAttribute(INNER_HTML_ATTRIBUTE));
}
@Override
public void describeTo(Description description)
{
description.appendValue(this.value);
}
}
private static class DatePatternMatcher extends TypeSafeMatcher<WebElement>
{
private static final String REGEX = "\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}";
@Override
protected boolean matchesSafely(WebElement item)
{
return item.getText().matches(REGEX);
}
@Override
public void describeTo(Description description)
{
description.appendValue(String.format("Regex %s", REGEX));
}
@Override
protected void describeMismatchSafely(WebElement item, Description mismatchDescription)
{
mismatchDescription.appendText(item.getAttribute(INNER_HTML_ATTRIBUTE));
}
}
private static final String SELECT_CELLS_BY_COLUMN_INDEX = "tr td:nth-child(%d)";
private static final Logger LOGGER = LoggerFactory.getLogger(TableLayoutElement.class);
private final String liveDataId;
/**
* Default constructor. Initializes a live data table layout page object.
*
* @param liveDataId the live data id
* @since 12.10.9
*/
public TableLayoutElement(String liveDataId)
{
this.liveDataId = liveDataId;
}
/**
* Assert if the column contains a value. See {@link #assertRow(String, Matcher)} to use another matcher on the
* column values.
*
* @param columnLabel a column label (for instance {@code Title})
* @param value the value to be found in the column
* @see #assertRow(String, Matcher)
* @since 12.10.9
*/
public void assertRow(String columnLabel, String value)
{
assertRow(columnLabel, hasItem(getWebElementTextMatcher(value)));
}
/**
* Calls a {@code Matcher} on the column values.
*
* @param columnLabel a column label (for instance {@code Title})
* @param matcher the matcher to apply on the values of the column
* @see #assertRow(String, String)
* @since 13.5RC1
* @since 13.4.1
* @since 12.10.9
*/
public void assertRow(String columnLabel, Matcher<Iterable<? super WebElement>> matcher)
{
assertThat(getValues(columnLabel), matcher);
}
/**
* Assert if the column contains a link with the given name and url.
*
* @param columnName the column name
* @param text the text of the link to be found in the column
* @param link the href value of the link to be found in the column
*/
public void assertCellWithLink(String columnName, String text, String link)
{
assertThat(getValues(columnName), hasItem(getWebElementCellWithLinkMatcher(text, link)));
}
/**
* Assert if the column contains a delete action.
*
* @param columnName the column name
* @param entityReference the entity reference subject of the delete action
* @since 13.5RC1
*/
public void assertCellWithDeleteAction(String columnName, EntityReference entityReference)
{
assertCellWithLink(columnName, "Delete", urlWithoutFormToken(entityReference, "delete"));
}
/**
* Assert if the column contains an edit action.
*
* @param columnName the column name
* @param entityReference the entity reference subject of the edit action
* @since 13.5RC1
*/
public void assertCellWithEditAction(String columnName, EntityReference entityReference)
{
assertCellWithLink(columnName, "Edit", urlWithoutFormToken(entityReference, "edit"));
}
/**
* Assert if the column contains an edit action.
*
* @param columnName the column name
* @param entity the entity reference subject of the edit action
* @since 13.5RC1
*/
public void assertCellWithCopyAction(String columnName, EntityReference entity)
{
assertCellWithLink(columnName, "Copy", getUtil().getURL(entity, "view", "xpage=copy"));
}
/**
* Assert if the column contains an edit action.
*
* @param columnName the column name
* @param entityReference the entity reference subject of the edit action
* @since 13.5RC1
*/
public void assertCellWithRenameAction(String columnName, EntityReference entityReference)
{
assertCellWithLink(columnName, "Rename", getUtil().getURL(entityReference, "view", "xpage=rename&step=1"));
}
/**
* Assert if the column contains an edit action.
*
* @param columnName the column name
* @param entityReference the entity reference subject of the edit action
* @since 13.5RC1
*/
public void assertCellWithRightsAction(String columnName, EntityReference entityReference)
{
DocumentReference webPreferencesReference = new DocumentReference("WebPreferences",
(SpaceReference) entityReference.extractReference(EntityType.SPACE));
assertCellWithLink(columnName, "Rights",
urlWithoutFormToken(
getUtil().getURL(webPreferencesReference, "admin", "editor=spaceadmin§ion=PageRights")));
}
/**
* Waits until the table has content displayed and loaded. If you expect the Live Data to be displayed without
* content, see {@link #waitUntilReady(boolean)}.
*
* @see #waitUntilReady(boolean)
* @since 12.10.9
*/
public void waitUntilReady()
{
waitUntilReady(true);
}
/**
* Waits until the table is loaded. Use {@link #waitUntilReady()} for the default behavior.
*
* @param expectRows when {@code true} waits for rows to be loaded, when {@code false} continue
* without waiting for the content
* @see #waitUntilReady()
* @since 12.10.9
*/
public void waitUntilReady(boolean expectRows)
{
// Waits for all the live data to be loaded and the cells to be finished loading.
getDriver().waitUntilCondition(webDriver -> {
List<String> layoutLoaderClasses =
Arrays.asList(getClasses(getRoot().findElement(By.cssSelector(".layout-loader"))));
boolean isWaiting = layoutLoaderClasses.contains("waiting");
if (isWaiting) {
return false;
}
if (!noFiltering()) {
return false;
}
return !expectRows || !layoutLoaderClasses.contains("loading") && areCellsLoaded();
}, 20);
}
/**
* Waits until a minimal number of rows are displayed in the live data.
*
* @param minimalExpectedRowCount the minimal number of expected rows
* @see #waitUntilRowCountGreaterThan(int, int) if you want to define a custom timeout
*/
public void waitUntilRowCountGreaterThan(int minimalExpectedRowCount)
{
waitUntilRowCountGreaterThan(minimalExpectedRowCount, getDriver().getTimeout());
}
/**
* Waits until a minimal number of rows are displayed in the live data.
*
* @param minimalExpectedRowCount the minimal number of expected rows
* @param timeout a custom timeout before stopping the wait and raising an error
*/
public void waitUntilRowCountGreaterThan(int minimalExpectedRowCount, int timeout)
{
getDriver().waitUntilCondition(webDriver -> {
// Cells are displayed and they are loaded.
if (isEmpty() || !areCellsLoaded()) {
return false;
}
// And the count of row is greater than the expected count.
int count = countRows();
LOGGER.info("LiveTableElement#waitUntilRowCountGreaterThan/refresh(): count = [{}]", count);
return count >= minimalExpectedRowCount;
}, timeout);
}
/**
* Waits until a the number of rows displayed in the live data matches the expected count.
*
* @param expectedRowCount the number of expected rows
* @see #waitUntilRowCountEqualsTo(int, int) if you want to define a custom timeout
*/
public void waitUntilRowCountEqualsTo(int expectedRowCount)
{
waitUntilRowCountEqualsTo(expectedRowCount, getDriver().getTimeout());
}
/**
* Waits until a the number of rows displayed in the live data matches the expected count.
*
* @param expectedRowCount the number of expected rows
* @param timeout a custom timeout before stopping the wait and raising an error
*/
public void waitUntilRowCountEqualsTo(int expectedRowCount, int timeout)
{
getDriver().waitUntilCondition(webDriver -> {
// Cells are displayed. And they are loaded.
if (isEmpty() || !areCellsLoaded()) {
return false;
}
// And the count of row is greater than the expected count.
int count = countRows();
LOGGER.info("LiveTableElement#waitUntilRowCountEqualsTo/refresh(): count = [{}]", count);
return count == expectedRowCount;
}, timeout);
}
/**
* Set the value in the filter of a column and wait for the filtered results to be displayed. See {@link
* #filterColumn(String, String, boolean)} to filter without waiting.
*
* @param columnLabel the label of the column to filter, for instance {@code "Title"}
* @param content the content to set on the filter
* @see #filterColumn(String, String, boolean)
*/
public void filterColumn(String columnLabel, String content)
{
filterColumn(columnLabel, content, true);
}
/**
* Set the value in the filter of a column. Waits for the new filtered values to be displayed before continuing when
* {@code waits} is {@code true}.
*
* @param columnLabel the label of the column to filter, for instance {@code "Creation Date"}
* @param content the content to set on the filter
* @param wait when {@code true} waits for the filtered results to be displayed before continuing, otherwise
* continues without waiting (useful when updating several filters in a row).
* @see #filterColumn(String, String)
*/
public void filterColumn(String columnLabel, String content, boolean wait)
{
int columnIndex = findColumnIndex(columnLabel);
WebElement element = getRoot()
.findElement(By.cssSelector(String.format(".column-filters > th:nth-child(%d) input", columnIndex)));
List<String> classes = Arrays.asList(getClasses(element));
if (classes.contains("filter-list")) {
if (element.getAttribute(CLASS_HTML_ATTRIBUTE).contains("selectized")) {
SuggestInputElement suggestInputElement = new SuggestInputElement(element);
suggestInputElement.sendKeys(content).selectTypedText();
} else {
new Select(element).selectByVisibleText(content);
}
} else if (classes.contains("filter-text")) {
element.clear();
element.sendKeys(content);
}
if (wait) {
waitUntilReady();
}
}
/**
* @return the number of rows currently displayed in the live data
* @since 12.10.9
*/
public int countRows()
{
return getRoot().findElements(By.cssSelector("tbody tr td:first-child")).size();
}
/**
* Return the {@link WebElement} of a cell by its row and column numbers. For instance the second row of the first
* column is {@code (2, 1)}
*
* @param columnLabel the label of the column to get, for instance {@code "Title"}
* @param rowNumber the cell row number to get, starting at 1. For instance the second column has the number 2
* @return the {@link WebElement} of the requested cell
*/
public WebElement getCell(String columnLabel, int rowNumber)
{
int columnNumber = findColumnIndex(columnLabel);
return getRoot().findElement(
By.cssSelector(String.format("tbody tr:nth-child(%d) td:nth-child(%d)", rowNumber, columnNumber)));
}
/**
* Clicks on an action button identified by its name, on a given row.
*
* @param rowNumber the row number, for instance 3 for the third row
* @param actionName the name of the action button to click on
*/
public void clickAction(int rowNumber, String actionName)
{
getRoot().findElement(By.cssSelector(
String.format("tbody tr:nth-child(%d) [name='%s']", rowNumber, actionName)))
.click();
}
/**
* Set a new value to a field in the nth cell of a column. Waits for the cell to be successfully edited before
* continuing.
*
* @param columnLabel the label of the column
* @param rowNumber the number of the row to update (the first line is number 1)
* @param fieldName the name of the field to edit, in other word the name of the corresponding XClass property
* @param newValue the new value of the field
*/
public void editCell(String columnLabel, int rowNumber, String fieldName, String newValue)
{
internalEdit(columnLabel, rowNumber, fieldName, newValue, true);
}
/**
* Starts editing a cell, input a value, but cancel the edition (by pressing escape) instead of saving.
*
* @param columnLabel the label of the column
* @param rowNumber the number of the row to update (the first line is number 1)
* @param fieldName the name of the field to edit, in other word the name of the corresponding XClass property
* @param newValue the new value set of the field, but never saved because we cancel the edition
* @since 13.5RC1
* @since 13.4.1
*/
public void editAndCancel(String columnLabel, int rowNumber, String fieldName, String newValue)
{
internalEdit(columnLabel, rowNumber, fieldName, newValue, false);
}
/**
* Returns a single {@link WebElement} found by passing {@code by} to {@link WebElement#findElement(By)} on the
* {@link WebElement} of the requested row.
*
* @param rowNumber the requested row by its row number, the first row has the number {@code 1}
* @param by the selector to apply on the row web element
* @return the {@link WebElement} found on the row
*/
public WebElement findElementInRow(int rowNumber, By by)
{
return getRoot().findElement(By.cssSelector(String.format("tbody tr:nth-child(%d)", rowNumber)))
.findElement(by);
}
/**
* Return a hamcrest {@link Matcher} on the text of a {@link WebElement}. For instance the {@link Matcher} will
* match on the web element containing the following html source {@code <p>Te<i>st</i></p>} for the value {@code
* "Test"}.
*
* @param value the expected value of the text returned by {@link WebElement#getText()}
* @return a matcher instance
* @since 13.5RC1
* @since 13.4.1
* @since 12.10.9
*/
public Matcher<WebElement> getWebElementTextMatcher(String value)
{
return new WebElementTextMatcher(value);
}
/**
* Return a hamcrest {@link Matcher}. This matcher assert that the text of a {@link WebElement} matches the date
* pattern {@code YYYY/MM/DD HH:mm}.
*
* @return 13.5RC1
*/
public Matcher<WebElement> getDatePatternMatcher()
{
return new DatePatternMatcher();
}
/**
* Return a hamcrest {@link Matcher} on the links of a {@link WebElement}. This matcher matches when a link is found
* on the {@link WebElement} with the expected text and link. For instance, the {@link Matcher} will match on the
* web element containing the following html source {@code <p>Links: <a href="/path">label</a>, <a
* href="/path2">label2</a></p>} for the text {@code "label"} and the link {@code "/path"}.
*
* @param text the expected text
* @param link the expected link
* @return a matcher instance
* @since 13.5RC1
* @since 13.4.1
*/
public Matcher<WebElement> getWebElementCellWithLinkMatcher(String text, String link)
{
return new CellWithLinkMatcher(text, link);
}
/**
* Returns the column index of the given column. The indexes start at {@code 1}, corresponding to the leftest
* column.
*
* @param columnLabel a column label (for instance {@code Title}).
* @return the index of the given column
*/
private int getColumnIndex(String columnLabel)
{
return getColumnsLabels().indexOf(columnLabel) + 1;
}
/**
* Gets the values currently displayed in the given column.
*
* @param columnLabel a column label (for instance {@code Title})
* @return the list of values found in the column
*/
private List<WebElement> getValues(String columnLabel)
{
int columnIndex = getColumnIndex(columnLabel);
return getRoot().findElements(By.cssSelector(String.format(SELECT_CELLS_BY_COLUMN_INDEX, columnIndex)));
}
/**
* @return {@code true} if all the cells of the live data are loaded, {@code false} otherwise
*/
private boolean areCellsLoaded()
{
return getRoot().findElements(By.cssSelector("tbody tr td.cell .xwiki-loader")).isEmpty();
}
/**
* @return {@code false} if the live data contains some result lines, {@code true} otherwise
*/
private boolean isEmpty()
{
return getRoot().findElements(By.cssSelector("tbody tr td.cell .livedata-displayer")).isEmpty();
}
/**
* @return {@code true} if no filters is currently in a filtering state (in other words, when the value currently
* set in the filter has not been taken into account), otherwise {@code false}
*/
private boolean noFiltering()
{
return getRoot().findElements(By.cssSelector(".column-filters .livedata-filter.filtering")).isEmpty();
}
/**
* @return the text of the columns currently displayed in the live data
*/
private List<String> getColumnsLabels()
{
return getRoot().findElements(By.cssSelector(".column-name .property-name"))
.stream()
.map(WebElement::getText)
.collect(Collectors.toList());
}
private WebElement getRoot()
{
return getDriver().findElement(By.id(this.liveDataId));
}
private int findColumnIndex(String columnLabel)
{
List<WebElement> elements = getRoot().findElements(By.cssSelector("thead tr th .property-name"));
int index = -1;
for (int i = 0; i < elements.size(); i++) {
if (elements.get(i).getText().equals(columnLabel)) {
index = i + 1;
break;
}
}
return index;
}
private List<WebElement> getCellsByColumnIndex(int columnIndex)
{
return getRoot().findElements(By.cssSelector(String.format(SELECT_CELLS_BY_COLUMN_INDEX, columnIndex)));
}
/**
* Does the steps for the edition of a cell and then returning the cell to view mode either by clicking on a h1
* tag or by pressing escape if {@code save} is false.
*
* @param columnLabel the label of the column
* @param rowNumber the number of the row to update (the first line is number 1)
* @param fieldName the name of the field to edit, in other word the name of the corresponding XClass property
* @param newValue the new value set of the field, but never saved because we cancel the edition
* @param save if the edit shall be saved (if false, the edit is cancelled)
*/
private void internalEdit(String columnLabel, int rowNumber, String fieldName, String newValue, boolean save)
{
int columnIndex = getColumnIndex(columnLabel);
WebElement element = getCellsByColumnIndex(columnIndex).get(rowNumber - 1);
// Hover on the property and click on the edit button on the displayed popover.
new Actions(getDriver().getWrappedDriver()).moveToElement(element).perform();
By editActionSelector = By.cssSelector(".displayer-action-list span[title='Edit']");
// Waits to have at least one popover visible and click on the edit action of the last one. While it does not
// seems to be possible in normal conditions, using selenium and moveToElement, several popover can be visible
// at the same time (especially on Chrome). We select the latest edit action, which is the one of the targeted
// property because the popover actions are appended at the end of the document.
getDriver().waitUntilCondition(input -> !getDriver().findElementsWithoutWaiting(editActionSelector).isEmpty());
List<WebElement> popoverActions = getDriver().findElementsWithoutWaiting(editActionSelector);
popoverActions.get(popoverActions.size() - 1).click();
// Selector of the edited field.
By selector = By.cssSelector(String.format("[name$='_%s']", fieldName));
// Waits for the text input to be displayed.
getDriver().waitUntilCondition(input -> !getDriver().findElementsWithoutWaiting(element, selector).isEmpty());
// Reuse the FormContainerElement to avoid code duplication of the interaction with the form elements
// displayed in the live data (they are the same as the one of the inline edit mode).
new FormContainerElement(By.cssSelector(".livedata-displayer .edit"))
.setFieldValue(element.findElement(selector), newValue);
if (save) {
// Clicks somewhere outside the edited cell. We use the h1 tag because it is present on all pages.
new Actions(getDriver().getWrappedDriver()).click(getDriver().findElement(By.tagName("h1"))).perform();
} else {
// Press escape to cancel the edition.
new Actions(getDriver().getWrappedDriver()).sendKeys(Keys.ESCAPE).build().perform();
}
// Waits for the field to disappear.
getDriver().waitUntilCondition(input -> {
// The edited field is not displayed anymore.
return element.findElements(selector).isEmpty();
});
// Wait for reload after saving.
if (save) {
waitUntilReady();
}
}
private String[] getClasses(WebElement element)
{
return element.getAttribute(CLASS_HTML_ATTRIBUTE).split("\\s+");
}
private String urlWithoutFormToken(EntityReference entityReference, String action)
{
return urlWithoutFormToken(getUtil().getURL(entityReference, action, ""));
}
/**
* Remove the {@code form_token} path parameter from an url.
*
* @param url the url to clean up
* @return the cleanup url, without the {@code form_token} path parameter
*/
private String urlWithoutFormToken(String url)
{
URI initialUri = URI.create(url);
URIBuilder uriBuilder = new URIBuilder(initialUri);
List<NameValuePair> cleanedUpParams = uriBuilder.getQueryParams().stream()
.filter(it -> !Objects.equals(it.getName(), "form_token"))
.collect(Collectors.toList());
uriBuilder.setParameters(cleanedUpParams);
URI uri;
try {
uri = uriBuilder.build();
} catch (URISyntaxException e) {
uri = initialUri;
}
return uri.toASCIIString();
}
} |
package laboratory.test.java.nio;
import java.nio.charset.Charset;
import java.util.Locale;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CharsetTest {
@SuppressWarnings("unused")
private static final Logger log = LoggerFactory.getLogger(CharsetTest.class);
@Test
public void test() {
Assert.assertTrue(Charset.isSupported("UTF-8"));
Charset charset = Charset.forName("UTF-8");
Assert.assertTrue(charset.canEncode());
Assert.assertEquals("UTF-8", charset.toString());
Assert.assertEquals("UTF-8", charset.displayName(Locale.KOREA));
charset = Charset.forName("EUC-KR");
Assert.assertTrue(charset.canEncode());
Assert.assertEquals("EUC-KR", charset.toString());
Assert.assertEquals("EUC-KR", charset.displayName(Locale.KOREA));
}
} |
package io.bdrc.xmltoldmigration;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.apache.jena.graph.Graph;
import org.apache.jena.graph.Node;
import org.apache.jena.graph.NodeFactory;
import org.apache.jena.ontology.DatatypeProperty;
import org.apache.jena.ontology.Individual;
import org.apache.jena.ontology.OntDocumentManager;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.ontology.OntModelSpec;
import org.apache.jena.ontology.Restriction;
import org.apache.jena.query.Dataset;
import org.apache.jena.query.DatasetFactory;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.RDFLanguages;
import org.apache.jena.riot.RDFParser;
import org.apache.jena.riot.RDFWriter;
import org.apache.jena.riot.RiotException;
import org.apache.jena.riot.system.PrefixMap;
import org.apache.jena.riot.system.PrefixMapFactory;
import org.apache.jena.riot.system.StreamRDFLib;
import org.apache.jena.riot.writer.TriGWriter;
import org.apache.jena.sparql.core.DatasetGraph;
import org.apache.jena.sparql.util.Context;
import org.apache.jena.sparql.util.Symbol;
import org.apache.jena.util.iterator.ExtendedIterator;
import org.apache.jena.vocabulary.OWL;
import org.apache.jena.vocabulary.OWL2;
import org.apache.jena.vocabulary.RDF;
import org.apache.jena.vocabulary.RDFS;
import org.apache.jena.vocabulary.SKOS;
import org.apache.jena.vocabulary.VCARD4;
import org.apache.jena.vocabulary.XSD;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import io.bdrc.jena.sttl.CompareComplex;
import io.bdrc.jena.sttl.ComparePredicates;
import io.bdrc.jena.sttl.STTLWriter;
import io.bdrc.xmltoldmigration.helpers.ContextGenerator;
import io.bdrc.xmltoldmigration.helpers.ExceptionHelper;
import io.bdrc.xmltoldmigration.xml2files.CommonMigration;
import io.bdrc.xmltoldmigration.xml2files.CorporationMigration;
import io.bdrc.xmltoldmigration.xml2files.ImagegroupMigration;
import io.bdrc.xmltoldmigration.xml2files.LineageMigration;
import io.bdrc.xmltoldmigration.xml2files.OfficeMigration;
import io.bdrc.xmltoldmigration.xml2files.OutlineMigration;
import io.bdrc.xmltoldmigration.xml2files.PersonMigration;
import io.bdrc.xmltoldmigration.xml2files.PlaceMigration;
import io.bdrc.xmltoldmigration.xml2files.ProductMigration;
import io.bdrc.xmltoldmigration.xml2files.PubinfoMigration;
import io.bdrc.xmltoldmigration.xml2files.ScanrequestMigration;
import io.bdrc.xmltoldmigration.xml2files.TaxonomyMigration;
import io.bdrc.xmltoldmigration.xml2files.TopicMigration;
import io.bdrc.xmltoldmigration.xml2files.WorkMigration;
import openllet.jena.PelletReasonerFactory;
public class MigrationHelpers {
protected static DocumentBuilderFactory documentFactory = null;
protected static Map<String,Object> typeToFrameObject = new HashMap<>();
public static Writer logWriter;
public static boolean writefiles = true;
public static boolean checkagainstOwl = false;
public static boolean checkagainstXsd = false;
public static boolean deleteDbBeforeInsert = true;
public static OntModel ontologymodel = MigrationHelpers.getOntologyModel();
public static PrefixMap prefixMap = getPrefixMap();
// not used here but let's remember for updating the owl-schema/context.jsonld
public static final Map<String,Object> jsonldcontext = ContextGenerator.generateContextObject(ontologymodel, prefixMap, "bdo");
public static final String DB_PREFIX = "bdrc_";
// types in target DB
public static final String CORPORATION = "corporation";
public static final String LINEAGE = "lineage";
public static final String OFFICE = "office";
public static final String OUTLINE = "outline";
public static final String PERSON = "person";
public static final String PLACE = "place";
public static final String TOPIC = "topic";
public static final String VOLUMES = "volumes";
public static final String ITEMS = "items";
public static final String ITEM = "item";
public static final String WORK = "work";
// types in source DB and not in target DB
public static final String IMAGEGROUP = "imagegroup";
public static final String PRODUCT = "product";
public static final String PUBINFO = "pubinfo";
public static final String SCANREQUEST = "scanrequest";
public static final String VOLUME = "volume";
public static final String TAXONOMY = "taxonomy";
public static final int OUTPUT_STTL = 0;
public static final int OUTPUT_JSONLD = 1;
public static final int OUTPUT_TRIG = 2;
private static final String BDO = CommonMigration.ONTOLOGY_NS;
private static final String BDR = CommonMigration.RESOURCE_NS;
private static final String ADM = CommonMigration.ADMIN_NS;
private static final String BDA = CommonMigration.ADMIN_DATA_NS;
private static final String BDG = CommonMigration.GRAPH_NS;
public static Lang sttl;
public static Context ctx;
public static final Map<String,String> typeToXsdPrefix = new HashMap<>();
public static final Map<String, Boolean> disconnectedRIds;
public static final Map<String, String> ridReplacements;
static {
try {
logWriter = new PrintWriter(new OutputStreamWriter(System.err, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// Well, that's a stupid try/catch...
e.printStackTrace();
}
disconnectedRIds = setupDisconnectedRIDs();
ridReplacements = setupRIDReplacements();
setupSTTL();
typeToXsdPrefix.put(CORPORATION, CorporationMigration.CXSDNS);
typeToXsdPrefix.put(LINEAGE, LineageMigration.LXSDNS);
typeToXsdPrefix.put(OFFICE, OfficeMigration.OXSDNS);
typeToXsdPrefix.put(OUTLINE, OutlineMigration.OXSDNS);
typeToXsdPrefix.put(PERSON, PersonMigration.PXSDNS);
typeToXsdPrefix.put(PLACE, PlaceMigration.PLXSDNS);
typeToXsdPrefix.put(TOPIC, TopicMigration.TXSDNS);
//typeToXsdPrefix.put(ITEMS, CorporationMigration.CXSDNS);
//typeToXsdPrefix.put(ITEM, CorporationMigration.CXSDNS);
typeToXsdPrefix.put(WORK, WorkMigration.WXSDNS);
typeToXsdPrefix.put(IMAGEGROUP, ImagegroupMigration.IGXSDNS);
typeToXsdPrefix.put(PRODUCT, ProductMigration.PRXSDNS);
typeToXsdPrefix.put(PUBINFO, PubinfoMigration.WPXSDNS);
typeToXsdPrefix.put(SCANREQUEST, ScanrequestMigration.SRXSDNS);
//typeToXsdPrefix.put(VOLUME, CorporationMigration.CXSDNS);
//typeToXsdPrefix.put(TAXONOMY, CorporationMigration.CXSDNS);
}
public static boolean isDisconnected(String RID) {
return disconnectedRIds.containsKey(RID);
}
public static Map<String, Boolean> setupDisconnectedRIDs() {
final Map<String,Boolean> res = new HashMap<>();
final ClassLoader classLoader = MigrationHelpers.class.getClassLoader();
final InputStream inputStream = classLoader.getResourceAsStream("disconnectedRIDs.txt");
final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
while(reader.ready()) {
String line = reader.readLine();
res.put(line, true);
}
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
public static Map<String, String> setupRIDReplacements() {
final Map<String,String> res = new HashMap<>();
final ClassLoader classLoader = MigrationHelpers.class.getClassLoader();
final InputStream inputStream = classLoader.getResourceAsStream("ridReplacements.csv");
final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
while(reader.ready()) {
String[] line = reader.readLine().split(",");
res.put(line[0], line[1]);
}
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
public static void writeRIDReplacements(String filename) {
PrintWriter writer;
try {
writer = new PrintWriter(filename, "UTF-8");
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
return;
}
for (Entry<String,String> e : ridReplacements.entrySet()) {
writer.println(e.getKey()+","+e.getValue());
}
writer.close();
}
public static class ResourceInfo {
public Map<String,String> links = null;
public String status = "absent";
public ResourceInfo() {
this.links = null;
this.status = "absent";
}
}
public static Map<String,ResourceInfo> resourceInfos = new HashMap<>();
public static void resourceHasStatus(String res, String status) {
if (res.startsWith("G9GBX") || res.contains("TLM")) return;
ResourceInfo ri = resourceInfos.computeIfAbsent(res, x -> new ResourceInfo());
ri.status = status;
if (status.equals("released"))
ri.links = null;
}
public static void resourceReplacedWith(String res, String rid) {
ridReplacements.put(res, rid);
}
public static void recordLinkTo(String orig, String prop, String to) {
if (orig == null || orig.startsWith("G9GBX") || orig.contains("TLM")) return;
if (isDisconnected(to)) return;
ResourceInfo ri = resourceInfos.computeIfAbsent(to, x -> new ResourceInfo());
if (!ri.status.equals("released")) {
if (ri.links == null)
ri.links = new HashMap<String,String>();
ri.links.put(orig, prop);
}
}
public static String sanitizeRID(String orig, String prop, String to) {
String repl = ridReplacements.get(to);
if (repl != null) {
to = repl;
}
recordLinkTo(orig, prop, to);
return to;
}
public static void reportMissing() {
for (Entry<String,ResourceInfo> e : resourceInfos.entrySet()) {
final ResourceInfo ri = e.getValue();
if (ri.status.equals("released") || ri.links == null)
continue;
StringBuilder sb = new StringBuilder();
sb.append("resource in status `"+ri.status+"` linked from ");
for (Entry<String,String> e2 : ri.links.entrySet()) {
sb.append("`"+e2.getKey()+"` (prop. `"+e2.getValue()+"`) ");
}
ExceptionHelper.logException(ExceptionHelper.ET_MISSING, e.getKey(), e.getKey(), e.getKey(), sb.toString());
}
resourceInfos = null;
}
public static PrefixMap getPrefixMap() {
PrefixMap pm = PrefixMapFactory.create();
pm.add("", BDO);
pm.add("adm", ADM);
pm.add("bda", BDA);
pm.add("bdg", BDG);
pm.add("bdr", BDR);
pm.add("owl", OWL.getURI());
pm.add("rdf", RDF.getURI());
pm.add("rdfs", RDFS.getURI()); ;
pm.add("skos", SKOS.getURI());
pm.add("vcard", VCARD4.getURI());
pm.add("xsd", XSD.getURI());
return pm;
}
public static void setupSTTL() {
sttl = STTLWriter.registerWriter();
SortedMap<String, Integer> nsPrio = ComparePredicates.getDefaultNSPriorities();
nsPrio.put(SKOS.getURI(), 1);
nsPrio.put(ADM, 5);
nsPrio.put("http://purl.bdrc.io/ontology/toberemoved/", 6);
List<String> predicatesPrio = CompareComplex.getDefaultPropUris();
predicatesPrio.add(ADM+"logDate");
predicatesPrio.add(BDO+"seqNum");
predicatesPrio.add(BDO+"onYear");
predicatesPrio.add(BDO+"notBefore");
predicatesPrio.add(BDO+"notAfter");
predicatesPrio.add(BDO+"noteText");
predicatesPrio.add(BDO+"noteWork");
predicatesPrio.add(BDO+"noteLocationStatement");
predicatesPrio.add(BDO+"volumeNumber");
predicatesPrio.add(BDO+"eventWho");
predicatesPrio.add(BDO+"eventWhere");
ctx = new Context();
ctx.set(Symbol.create(STTLWriter.SYMBOLS_NS + "nsPriorities"), nsPrio);
ctx.set(Symbol.create(STTLWriter.SYMBOLS_NS + "nsDefaultPriority"), 2);
ctx.set(Symbol.create(STTLWriter.SYMBOLS_NS + "complexPredicatesPriorities"), predicatesPrio);
ctx.set(Symbol.create(STTLWriter.SYMBOLS_NS + "indentBase"), 4);
ctx.set(Symbol.create(STTLWriter.SYMBOLS_NS + "predicateBaseWidth"), 18);
}
public static void writeLogsTo(PrintWriter w) {
logWriter = w;
}
public static void writeLog(String s) {
try {
logWriter.write(s+"\n");
} catch (IOException e) {
e.printStackTrace();
}
}
public static String inputStreamToString(InputStream s) {
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
try {
while ((length = s.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
} catch (IOException e1) {
e1.printStackTrace();
return null;
}
// StandardCharsets.UTF_8.name() > JDK 7
try {
return result.toString("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
public static void modelToOutputStream(Model m, String type, int outputType, String fname) {
OutputStream out = null;
try {
if (m == null)
throw new IllegalArgumentException("modelToOutputStream called with null model");
if (fname == null || fname.isEmpty())
return;
if (fname.contains(".ttl") || fname.contains(".trig")) {
out = new FileOutputStream(fname);
} else {
if (outputType == OUTPUT_TRIG) {
out = new FileOutputStream(fname + ".trig");
} else if (outputType == OUTPUT_STTL) {
out = new FileOutputStream(fname + ".ttl");
}
}
modelToOutputStream(m, out, type, outputType, fname);
return;
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
} catch (IllegalArgumentException e) {
writeLog("error writing "+fname+": "+e.getMessage());
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void modelToOutputStream(Model m, OutputStream out, String type, int outputType, String fname)
throws FileNotFoundException
{
if (outputType == OUTPUT_STTL) {
RDFWriter.create().source(m.getGraph()).context(ctx).lang(sttl).build().output(out);
return;
}
if (outputType == OUTPUT_TRIG) {
// compute graph uri from fname; if fname == null then testing so use a dummy graph URI
String uriStr =
(fname != null && !fname.isEmpty()) ? BDG + fname.substring(fname.lastIndexOf("/")+1) : BDG + "GraphForTesting";
Node graphUri = NodeFactory.createURI(uriStr);
DatasetGraph dsg = DatasetFactory.create().asDatasetGraph();
dsg.addGraph(graphUri, m.getGraph());
new TriGWriter().write(out, dsg, getPrefixMap(), graphUri.toString(m), ctx);
}
}
public static boolean isSimilarTo(Model src, Model dst) {
return src.isIsomorphicWith(dst);
}
public static Document documentFromFileName(String fname) {
if (documentFactory == null) {
documentFactory = DocumentBuilderFactory.newInstance();
}
documentFactory.setNamespaceAware(true);
Document document = null;
// create a new builder at each document to parse in parallel
try {
final DocumentBuilder builder = documentFactory.newDocumentBuilder();
document = builder.parse(new File(fname));
}
catch (final ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
return document;
}
public static Model modelFromFileName(String fname) {
Model model = ModelFactory.createDefaultModel();
Graph g = model.getGraph();
String ext = fname.substring(fname.lastIndexOf("."));
if (ext.equals(".ttl")) {
try {
RDFParser.create()
.source(fname)
.lang(RDFLanguages.TTL)
.parse(StreamRDFLib.graph(g));
} catch (RiotException e) {
writeLog("error reading "+fname);
return null;
}
} else if (ext.equals(".trig")) {
try {
Dataset dataset = RDFDataMgr.loadDataset(fname);
Iterator<String> iter = dataset.listNames();
if (iter.hasNext()) {
String graphUri = iter.next();
if (iter.hasNext())
writeLog("modelFromFileName " + fname + " getting named model: " + graphUri + ". Has more graphs! ");
model = dataset.getNamedModel(graphUri);
}
} catch (RiotException e) {
writeLog("error reading "+fname);
return null;
}
}
CommonMigration.setPrefixes(model);
return model;
}
public static Model xmlToRdf(Document d, String type) {
Model m = null;
switch (type) {
case CORPORATION:
m = CorporationMigration.MigrateCorporation(d);
break;
case PERSON:
m = PersonMigration.MigratePerson(d);
break;
case PLACE:
m = PlaceMigration.MigratePlace(d);
break;
case PRODUCT:
m = ProductMigration.MigrateProduct(d);
break;
case PUBINFO:
m = PubinfoMigration.MigratePubinfo(d);
break;
case IMAGEGROUP:
m = ImagegroupMigration.MigrateImagegroup(d);
break;
case LINEAGE:
m = LineageMigration.MigrateLineage(d);
break;
case OFFICE:
m = OfficeMigration.MigrateOffice(d);
break;
case OUTLINE:
m = OutlineMigration.MigrateOutline(d);
break;
case SCANREQUEST:
m = ScanrequestMigration.MigrateScanrequest(d);
break;
case TOPIC:
m = TopicMigration.MigrateTopic(d);
break;
case TAXONOMY:
m = TaxonomyMigration.MigrateTaxonomy(d);
break;
case WORK:
m = WorkMigration.MigrateWork(d);
break;
default:
// arg
return m;
}
return m;
}
public static boolean mustBeMigrated(Element root, String type, String status) {
boolean res = (!status.isEmpty() && !status.equals("withdrawn") && !status.equals("onHold"));
if (res == false) return false;
if (type.equals("outline")) {
res = res && !OutlineMigration.ridsToIgnore.containsKey(root.getAttribute("RID"));
}
return res;
}
// model from XML
public static Model getModelFromFile(String src, String type, String fileName) {
Document d = documentFromFileName(src);
if (checkagainstXsd) {
Validator v = getValidatorFor(type);
CommonMigration.documentValidates(d, v, src);
}
Element root = d.getDocumentElement();
final String status = root.getAttribute("status");
MigrationHelpers.resourceHasStatus(root.getAttribute("RID"), status);
Model m = null;
if (status.equals("withdrawn")) {
return migrateWithdrawn(d, type);
}
if (!mustBeMigrated(root, type, status)) {
return null;
}
try {
m = xmlToRdf(d, type);
} catch (IllegalArgumentException e) {
writeLog("error in "+fileName+" "+e.getMessage());
}
if (checkagainstOwl) {
CommonMigration.rdfOkInOntology(m, ontologymodel);
}
return m;
}
private static final Pattern withdrawnPattern = Pattern.compile("(?i:withdrawn in favou?re? of) +([a-zA-Z]+[0-9]+[a-zA-Z0-9]+).*");
public static Model migrateWithdrawn(Document xmlDocument, final String type) {
if (type.equals(PUBINFO) || type.equals(SCANREQUEST)) {
return null;
}
Model m = ModelFactory.createDefaultModel();
CommonMigration.setPrefixes(m, type);
Element root = xmlDocument.getDocumentElement();
Resource main = m.createResource(BDR + root.getAttribute("RID"));
Resource admMain = getAdmResource(m, root.getAttribute("RID"));
CommonMigration.addStatus(m, admMain, root.getAttribute("status"));
final String XsdPrefix = typeToXsdPrefix.get(type);
NodeList nodeList = root.getElementsByTagNameNS(XsdPrefix, "log");
String withdrawnmsg = null;
for (int i = 0; i < nodeList.getLength(); i++) {
Element log = (Element) nodeList.item(i);
NodeList logEntriesList = log.getElementsByTagNameNS(XsdPrefix, "entry");
for (int j = 0; j < logEntriesList.getLength(); j++) {
Element logEntry = (Element) logEntriesList.item(j);
final String msg = logEntry.getTextContent();
if (msg.toLowerCase().contains("withdrawn in "))
withdrawnmsg = msg.trim();
}
logEntriesList = log.getElementsByTagName("entry");
for (int k = 0; k < logEntriesList.getLength(); k++) {
Element logEntry = (Element) logEntriesList.item(k);
final String msg = logEntry.getTextContent();
if (msg.toLowerCase().contains("withdrawn in "))
withdrawnmsg = msg.trim();
}
}
if (withdrawnmsg != null) {
Matcher matcher = withdrawnPattern.matcher(withdrawnmsg);
if (!matcher.matches()) {
System.out.println("possible typo in withdrawing log message in "+main.getLocalName()+": "+withdrawnmsg);
} else {
final String rid = matcher.group(1).toUpperCase();
admMain.addProperty(m.createProperty(ADM, "replaceWith"), m.createResource(BDR+rid));
resourceReplacedWith(root.getAttribute("RID"), rid);
}
}
return m;
}
public static void outputOneModel(Model m, String mainId, String dst, String type) {
if (m == null) return;
if (writefiles) {
modelToOutputStream(m, type, OUTPUT_TRIG, dst);
}
}
// change Range Datatypes from rdf:PlainLitteral to rdf:langString
public static void rdf10tordf11(OntModel o) {
Resource RDFPL = o.getResource("http://www.w3.org/1999/02/22-rdf-syntax-ns#PlainLiteral");
Resource RDFLS = o.getResource("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString");
ExtendedIterator<DatatypeProperty> it = o.listDatatypeProperties();
while(it.hasNext()) {
DatatypeProperty p = it.next();
if (p.hasRange(RDFPL)) {
p.removeRange(RDFPL);
p.addRange(RDFLS);
}
}
ExtendedIterator<Restriction> it2 = o.listRestrictions();
while(it2.hasNext()) {
Restriction r = it2.next();
Statement s = r.getProperty(OWL2.onDataRange); // is that code obvious? no
if (s != null && s.getObject().asResource().equals(RDFPL)) {
s.changeObject(RDFLS);
}
}
}
public static void removeIndividuals(OntModel o) {
ExtendedIterator<Individual> it = o.listIndividuals();
while(it.hasNext()) {
Individual i = it.next();
if (i.getLocalName().equals("UNKNOWN")) continue;
i.remove();
}
}
public static OntModel getOntologyModel()
{
// the initial model from Protege is not considered valid by Openllet because
// it's RDF1.0, so we first open it with no reasoner:
OntModel ontoModel = null;
try {
OntDocumentManager mgrImporting = new OntDocumentManager("owl-file/ont-policy.rdf");
mgrImporting.setProcessImports(true);
OntModelSpec ontSpecImporting = new OntModelSpec(OntModelSpec.OWL_DL_MEM);
ontSpecImporting.setDocumentManager(mgrImporting);
ontoModel = mgrImporting.getOntology(ADM, ontSpecImporting);
} catch (Exception e) {
System.err.println(e.getMessage());
System.exit(1);
}
// then we fix it by converting RDF-1.0 to RDF-1.1
rdf10tordf11(ontoModel);
return ontoModel;
}
public static OntModel getInferredModel(OntModel m) {
OntModel ontoModelInferred = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC, m);
ontoModelInferred.setStrictMode(false);
return ontoModelInferred;
}
public static Map<String,Validator> validators = new HashMap<String,Validator>();
public static Validator getValidatorFor(String type) {
Validator res = validators.get("type");
if (res != null) return res;
String xsdFullName = "src/main/resources/xsd/"+type+".xsd";
SchemaFactory factory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema;
try {
schema = factory.newSchema(new File(xsdFullName));
}
catch (SAXException ex) {
System.err.println("xsd file looks invalid...");
return null;
}
res = schema.newValidator();
validators.put(type, res);
return res;
}
public static Resource getAdmResource(Model m, String id) {
return getAdmResource(m, id, false);
}
public static Resource getAdmResource(Model m, String id, boolean same) {
Resource res = m.createResource(BDR+id);
Resource admR = m.createResource(BDA+id);
m.add(admR, RDF.type, m.createResource(ADM + "AdminData"));
m.add(admR, m.createProperty(ADM+"adminAbout"), (same ? admR : res));
return admR;
}
} |
//TODO:
//notifyNouvelleEnchere donne l'idObjet, le nouveau prix et le nouveau gagnant de l'objet au client
// faire getSalleByID
package serveur;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import commun.DejaDansLaSalleException;
import commun.InfoSalleDeVente;
import commun.Objet;
@SuppressWarnings("serial")
public class HotelDesVentes extends UnicastRemoteObject implements IHotelDesVentes {
private List<SalleDeVente> listeSalles =new ArrayList<SalleDeVente>();
private List<ClientInfo> listeClients =new ArrayList<ClientInfo>();
protected HotelDesVentes() throws RemoteException {
super();
}
@Override
public Objet rejoindreSalle(UUID roomId, ClientInfo client) throws RemoteException {
ClientInfo fetchedClient=getClientById(client.getId());
SalleDeVente salleRejointe = getSalleById(roomId);
if ( fetchedClient == client ){
ajouterClientASalle(fetchedClient,salleRejointe);
return salleRejointe.getObjetCourant();
}
return null;
}
@Override
public UUID creerSalle(ClientInfo client, Objet o, String nomDeSalle) throws RemoteException {
SalleDeVente nouvelleSDV=new SalleDeVente(o,nomDeSalle);
listeSalles.add(nouvelleSDV);
return nouvelleSDV.getId();
}
@Override
public boolean login(UUID id, String nomUtilisateur) throws RemoteException{
//Pas d'homonyme
for(ClientInfo c : listeClients){
if (( c.getNom() == nomUtilisateur ) && ( c.getId()!=id )){
return false;
}
}
for(ClientInfo c : listeClients){
if (c.getId()==id ){
return false;
}
}
listeClients.add(new ClientInfo(id,nomUtilisateur));
return true;
}
@Override
public void logout(ClientInfo client) {
//Enlever client de la liste client de l'hdv
//TODO Enlever client de chaque salle
listeClients.remove(client);
}
@Override
public void ajouterObjet(Objet objetAVendre, UUID idSDV ) throws RemoteException {
// TODO Auto-generated method stub
getSalleById(idSDV).ajouterObjet(objetAVendre);
}
@Override
public Objet getObjetEnVente(UUID idSDV) throws RemoteException {
// TODO Auto-generated method stub
return getSalleById(idSDV).getObjetCourant();
}
@Override
public void rencherir(int prix, UUID clientId, UUID idSDV) throws RemoteException {
// TODO Auto-generated method stub
Objet objEnVente = getObjetEnVente(idSDV);
if(objEnVente.getPrixCourant()<prix){
if( objEnVente.getNomGagnant()!=getClientById(clientId).getNom()){
objEnVente.setPrixCourant(prix);
objEnVente.setNomGagnant(getClientById(clientId).getNom());
}
}
}
@Override
public void renommerSalle(UUID roomId, ClientInfo client, String nomDeSalle) throws RemoteException{
getSalleById(roomId).setNom(nomDeSalle);
}
@Override
public ArrayList<InfoSalleDeVente> getListeSalles() throws RemoteException {
// TODO Auto-generated method stub
return null;
}
private void ajouterClientASalle(ClientInfo client, SalleDeVente room) throws RemoteException {
try {
room.ajouterClient(client);
}
catch (DejaDansLaSalleException e) {
}
}
private ClientInfo getClientById(UUID clientId) {
// TODO Auto-generated method stub
for ( ClientInfo client :listeClients ){
if( client.getId()==clientId){
return client;
}
}
return null;
}
public SalleDeVente getSalleById(UUID roomId) {
for (SalleDeVente sdv : listeSalles ){
if ( sdv.getId()==roomId ) return sdv;
}
return null;
// TODO Auto-generated method stub
}
} |
package de.gurkenlabs.litiengine.environment;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import de.gurkenlabs.litiengine.Game;
import de.gurkenlabs.litiengine.IUpdateable;
import de.gurkenlabs.litiengine.annotation.EntityInfo;
import de.gurkenlabs.litiengine.configuration.Quality;
import de.gurkenlabs.litiengine.entities.CollisionBox;
import de.gurkenlabs.litiengine.entities.Creature;
import de.gurkenlabs.litiengine.entities.ICollisionEntity;
import de.gurkenlabs.litiengine.entities.ICombatEntity;
import de.gurkenlabs.litiengine.entities.IEntity;
import de.gurkenlabs.litiengine.entities.IMobileEntity;
import de.gurkenlabs.litiengine.entities.Prop;
import de.gurkenlabs.litiengine.entities.Trigger;
import de.gurkenlabs.litiengine.environment.tilemap.IMap;
import de.gurkenlabs.litiengine.environment.tilemap.IMapLoader;
import de.gurkenlabs.litiengine.environment.tilemap.IMapObject;
import de.gurkenlabs.litiengine.environment.tilemap.IMapObjectLayer;
import de.gurkenlabs.litiengine.environment.tilemap.MapArea;
import de.gurkenlabs.litiengine.environment.tilemap.MapProperty;
import de.gurkenlabs.litiengine.environment.tilemap.MapUtilities;
import de.gurkenlabs.litiengine.environment.tilemap.Spawnpoint;
import de.gurkenlabs.litiengine.environment.tilemap.TmxMapLoader;
import de.gurkenlabs.litiengine.graphics.AmbientLight;
import de.gurkenlabs.litiengine.graphics.DebugRenderer;
import de.gurkenlabs.litiengine.graphics.IRenderable;
import de.gurkenlabs.litiengine.graphics.LightSource;
import de.gurkenlabs.litiengine.graphics.RenderType;
import de.gurkenlabs.litiengine.graphics.StaticShadow;
import de.gurkenlabs.litiengine.graphics.StaticShadowLayer;
import de.gurkenlabs.litiengine.graphics.StaticShadowType;
import de.gurkenlabs.litiengine.graphics.particles.Emitter;
import de.gurkenlabs.litiengine.util.TimeUtilities;
import de.gurkenlabs.litiengine.util.geom.GeometricUtilities;
import de.gurkenlabs.litiengine.util.io.FileUtilities;
public class Environment implements IEnvironment {
private static final Logger log = Logger.getLogger(Environment.class.getName());
private static final Map<String, IMapObjectLoader> mapObjectLoaders;
private final Map<Integer, ICombatEntity> combatEntities;
private final Map<Integer, IMobileEntity> mobileEntities;
private final Map<RenderType, Map<Integer, IEntity>> entities;
private final Map<String, List<IEntity>> entitiesByTag;
private final Map<RenderType, Collection<EnvironmentRenderListener>> renderListeners;
private final List<EnvironmentListener> listeners;
private final List<EnvironmentEntityListener> entityListeners;
private final Map<RenderType, Collection<IRenderable>> renderables;
private final Collection<CollisionBox> colliders;
private final Collection<LightSource> lightSources;
private final Collection<StaticShadow> staticShadows;
private final Collection<Trigger> triggers;
private final Collection<Prop> props;
private final Collection<Emitter> emitters;
private final Collection<Creature> creatures;
private final Collection<Spawnpoint> spawnPoints;
private final Collection<MapArea> mapAreas;
private AmbientLight ambientLight;
private StaticShadowLayer staticShadowLayer;
private boolean loaded;
private boolean initialized;
private IMap map;
private int localIdSequence = 0;
private int mapIdSequence;
static {
mapObjectLoaders = new ConcurrentHashMap<>();
registerDefaultMapObjectLoaders();
}
public Environment(final IMap map) {
this();
this.map = map;
this.mapIdSequence = MapUtilities.getMaxMapId(this.getMap());
Game.getPhysicsEngine().setBounds(this.getMap().getBounds());
}
public Environment(final String mapPath) {
this();
final IMap loadedMap = Game.getMap(FileUtilities.getFileName(mapPath));
if (loadedMap == null) {
final IMapLoader tmxLoader = new TmxMapLoader();
this.map = tmxLoader.loadMap(mapPath);
} else {
this.map = loadedMap;
}
this.mapIdSequence = MapUtilities.getMaxMapId(this.getMap());
Game.getPhysicsEngine().setBounds(new Rectangle(this.getMap().getSizeInPixels()));
}
private Environment() {
this.entitiesByTag = new ConcurrentHashMap<>();
this.entities = new ConcurrentHashMap<>();
this.combatEntities = new ConcurrentHashMap<>();
this.mobileEntities = new ConcurrentHashMap<>();
this.lightSources = Collections.newSetFromMap(new ConcurrentHashMap<LightSource, Boolean>());
this.colliders = Collections.newSetFromMap(new ConcurrentHashMap<CollisionBox, Boolean>());
this.triggers = Collections.newSetFromMap(new ConcurrentHashMap<Trigger, Boolean>());
this.mapAreas = Collections.newSetFromMap(new ConcurrentHashMap<MapArea, Boolean>());
this.staticShadows = Collections.newSetFromMap(new ConcurrentHashMap<StaticShadow, Boolean>());
this.props = Collections.newSetFromMap(new ConcurrentHashMap<Prop, Boolean>());
this.emitters = Collections.newSetFromMap(new ConcurrentHashMap<Emitter, Boolean>());
this.creatures = Collections.newSetFromMap(new ConcurrentHashMap<Creature, Boolean>());
this.spawnPoints = Collections.newSetFromMap(new ConcurrentHashMap<Spawnpoint, Boolean>());
this.renderables = new ConcurrentHashMap<>();
this.renderListeners = new ConcurrentHashMap<>();
this.listeners = new CopyOnWriteArrayList<>();
this.entityListeners = new CopyOnWriteArrayList<>();
for (RenderType renderType : RenderType.values()) {
this.entities.put(renderType, new ConcurrentHashMap<>());
this.renderListeners.put(renderType, Collections.newSetFromMap(new ConcurrentHashMap<EnvironmentRenderListener, Boolean>()));
this.renderables.put(renderType, Collections.newSetFromMap(new ConcurrentHashMap<IRenderable, Boolean>()));
}
}
@Override
public void addRenderListener(RenderType renderType, EnvironmentRenderListener listener) {
this.renderListeners.get(renderType).add(listener);
}
@Override
public void removeRenderListener(EnvironmentRenderListener listener) {
for (Collection<EnvironmentRenderListener> rends : this.renderListeners.values()) {
rends.remove(listener);
}
}
@Override
public void addListener(EnvironmentListener listener) {
this.listeners.add(listener);
}
@Override
public void removeListener(EnvironmentListener listener) {
this.listeners.remove(listener);
}
@Override
public void addEntityListener(EnvironmentEntityListener listener) {
this.entityListeners.add(listener);
}
@Override
public void removeEntityListener(EnvironmentEntityListener listener) {
this.entityListeners.remove(listener);
}
@Override
public void add(final IEntity entity) {
if (entity == null) {
return;
}
// set local map id if none is set for the entity
if (entity.getMapId() == 0) {
entity.setMapId(this.getLocalMapId());
}
if (entity instanceof Emitter) {
Emitter emitter = (Emitter) entity;
this.addEmitter(emitter);
}
if (entity instanceof ICombatEntity) {
this.combatEntities.put(entity.getMapId(), (ICombatEntity) entity);
}
if (entity instanceof IMobileEntity) {
this.mobileEntities.put(entity.getMapId(), (IMobileEntity) entity);
}
if (entity instanceof Prop) {
this.props.add((Prop) entity);
}
if (entity instanceof Creature) {
this.creatures.add((Creature) entity);
}
if (entity instanceof CollisionBox) {
this.colliders.add((CollisionBox) entity);
}
if (entity instanceof LightSource) {
this.lightSources.add((LightSource) entity);
}
if (entity instanceof Trigger) {
this.triggers.add((Trigger) entity);
}
if (entity instanceof Spawnpoint) {
this.spawnPoints.add((Spawnpoint) entity);
}
if (entity instanceof StaticShadow) {
this.staticShadows.add((StaticShadow) entity);
} else if (entity instanceof MapArea) {
this.mapAreas.add((MapArea) entity);
}
for (String rawTag : entity.getTags()) {
if (rawTag == null) {
continue;
}
final String tag = rawTag.trim().toLowerCase();
if (tag.isEmpty()) {
continue;
}
if (this.getEntitiesByTag().containsKey(tag)) {
this.getEntitiesByTag().get(tag).add(entity);
continue;
}
this.getEntitiesByTag().put(tag, new CopyOnWriteArrayList<>());
this.getEntitiesByTag().get(tag).add(entity);
}
// if the environment has already been loaded,
// we need to load the new entity manually
if (this.loaded) {
this.load(entity);
}
this.entities.get(entity.getRenderType()).put(entity.getMapId(), entity);
this.fireEntityEvent(l -> l.entityAdded(entity));
}
private void addEmitter(Emitter emitter) {
this.manageEmitterRenderables(emitter, (rends, instance) -> rends.add(instance));
this.emitters.add(emitter);
}
private void removeEmitter(Emitter emitter) {
this.manageEmitterRenderables(emitter, (rends, instance) -> rends.remove(instance));
this.emitters.remove(emitter);
}
private void manageEmitterRenderables(Emitter emitter, BiConsumer<Collection<IRenderable>, IRenderable> cons) {
for (RenderType renderType : RenderType.values()) {
if (renderType == RenderType.NONE) {
continue;
}
IRenderable renderable = emitter.getRenderable(renderType);
if (renderable != null) {
cons.accept(this.getRenderables(renderType), renderable);
}
}
this.emitters.remove(emitter);
}
private void updateColorLayers(IEntity entity) {
if (this.staticShadowLayer != null) {
this.staticShadowLayer.updateSection(entity.getBoundingBox());
}
if (this.ambientLight != null) {
this.ambientLight.updateSection(entity.getBoundingBox());
}
}
@Override
public void add(IRenderable renderable, RenderType renderType) {
this.getRenderables(renderType).add(renderable);
}
@Override
public void clear() {
Game.getPhysicsEngine().clear();
this.dispose(this.getEntities());
this.dispose(this.getTriggers());
this.getCombatEntities().clear();
this.getMobileEntities().clear();
this.getLightSources().clear();
this.getCollisionBoxes().clear();
this.getSpawnPoints().clear();
this.getAreas().clear();
this.getTriggers().clear();
this.getEntitiesByTag().clear();
for (Map<Integer, IEntity> type : this.entities.values())
type.clear();
this.initialized = false;
this.fireEvent(l -> l.environmentCleared(this));
}
@Override
public List<ICombatEntity> findCombatEntities(final Shape shape) {
return this.findCombatEntities(shape, entity -> true);
}
@Override
public List<ICombatEntity> findCombatEntities(final Shape shape, final Predicate<ICombatEntity> condition) {
final ArrayList<ICombatEntity> foundCombatEntities = new ArrayList<>();
if (shape == null) {
return foundCombatEntities;
}
// for rectangle we can just use the intersects method
if (shape instanceof Rectangle2D) {
final Rectangle2D rect = (Rectangle2D) shape;
for (final ICombatEntity combatEntity : this.getCombatEntities().stream().filter(condition).collect(Collectors.toList())) {
if (combatEntity.getHitBox().intersects(rect)) {
foundCombatEntities.add(combatEntity);
}
}
return foundCombatEntities;
}
// for other shapes, we check if the shape's bounds intersect the hitbox and
// if so, we then check if the actual shape intersects the hitbox
for (final ICombatEntity combatEntity : this.getCombatEntities().stream().filter(condition).collect(Collectors.toList())) {
if (combatEntity.getHitBox().intersects(shape.getBounds()) && GeometricUtilities.shapeIntersects(combatEntity.getHitBox(), shape)) {
foundCombatEntities.add(combatEntity);
}
}
return foundCombatEntities;
}
@Override
public List<IEntity> findEntities(final Shape shape) {
final ArrayList<IEntity> foundEntities = new ArrayList<>();
if (shape == null) {
return foundEntities;
}
if (shape instanceof Rectangle2D) {
final Rectangle2D rect = (Rectangle2D) shape;
for (final IEntity entity : this.getEntities()) {
if (entity.getBoundingBox().intersects(rect)) {
foundEntities.add(entity);
}
}
return foundEntities;
}
// for other shapes, we check if the shape's bounds intersect the hitbox
// and
// if so, we then check if the actual shape intersects the hitbox
for (final IEntity entity : this.getEntities()) {
if (entity.getBoundingBox().intersects(shape.getBounds()) && GeometricUtilities.shapeIntersects(entity.getBoundingBox(), shape)) {
foundEntities.add(entity);
}
}
return foundEntities;
}
@Override
public IEntity get(final int mapId) {
for (RenderType type : RenderType.values()) {
IEntity entity = this.entities.get(type).get(mapId);
if (entity != null) {
return entity;
}
}
return null;
}
@Override
public <T extends IEntity> T get(Class<T> clss, int mapId) {
IEntity ent = this.get(mapId);
if (ent == null || !clss.isInstance(ent)) {
return null;
}
return (T) ent;
}
@Override
public IEntity get(final String name) {
if (name == null || name.isEmpty()) {
return null;
}
for (RenderType type : RenderType.values()) {
for (final IEntity entity : this.entities.get(type).values()) {
if (entity.getName() != null && entity.getName().equals(name)) {
return entity;
}
}
}
return null;
}
@Override
public <T extends IEntity> T get(Class<T> clss, String name) {
IEntity ent = this.get(name);
if (ent == null || !clss.isInstance(ent)) {
return null;
}
return (T) ent;
}
@Override
public <T extends IEntity> Collection<T> getByTag(String... tags) {
return this.getByTag(null, tags);
}
@Override
public <T extends IEntity> Collection<T> getByTag(Class<T> clss, String... tags) {
List<T> foundEntities = new ArrayList<>();
for (String rawTag : tags) {
String tag = rawTag.toLowerCase();
if (!this.getEntitiesByTag().containsKey(tag)) {
continue;
}
for (IEntity ent : this.getEntitiesByTag().get(tag)) {
if ((clss == null || clss.isInstance(ent)) && !foundEntities.contains((T) ent)) {
foundEntities.add((T) ent);
}
}
}
return foundEntities;
}
@Override
public AmbientLight getAmbientLight() {
return this.ambientLight;
}
@Override
public Collection<MapArea> getAreas() {
return this.mapAreas;
}
@Override
public MapArea getArea(final int mapId) {
return getById(this.getAreas(), mapId);
}
@Override
public MapArea getArea(final String name) {
return getByName(this.getAreas(), name);
}
@Override
public Collection<Emitter> getEmitters() {
return this.emitters;
}
@Override
public Emitter getEmitter(int mapId) {
return getById(this.getEmitters(), mapId);
}
@Override
public Emitter getEmitter(String name) {
return getByName(this.getEmitters(), name);
}
@Override
public Collection<CollisionBox> getCollisionBoxes() {
return this.colliders;
}
@Override
public CollisionBox getCollisionBox(int mapId) {
return getById(this.getCollisionBoxes(), mapId);
}
@Override
public CollisionBox getCollisionBox(String name) {
return getByName(this.getCollisionBoxes(), name);
}
@Override
public Collection<ICombatEntity> getCombatEntities() {
return this.combatEntities.values();
}
@Override
public ICombatEntity getCombatEntity(final int mapId) {
return getById(this.getCombatEntities(), mapId);
}
@Override
public ICombatEntity getCombatEntity(String name) {
return getByName(this.getCombatEntities(), name);
}
@Override
public Collection<IEntity> getEntities() {
final ArrayList<IEntity> ent = new ArrayList<>();
for (Map<Integer, IEntity> type : this.entities.values())
ent.addAll(type.values());
return ent;
}
@Override
public Collection<IEntity> getEntities(final RenderType renderType) {
return this.entities.get(renderType).values();
}
public Map<String, List<IEntity>> getEntitiesByTag() {
return this.entitiesByTag;
}
@Override
public <T extends IEntity> Collection<T> getByType(Class<T> cls) {
List<T> foundEntities = new ArrayList<>();
for (IEntity ent : this.getEntities()) {
if (cls.isInstance(ent)) {
foundEntities.add((T) ent);
}
}
return foundEntities;
}
@Override
public Collection<LightSource> getLightSources() {
return this.lightSources;
}
@Override
public LightSource getLightSource(final int mapId) {
return getById(this.getLightSources(), mapId);
}
@Override
public LightSource getLightSource(String name) {
return getByName(this.getLightSources(), name);
}
/**
* Negative map ids are only used locally.
*/
@Override
public synchronized int getLocalMapId() {
return --localIdSequence;
}
@Override
public IMap getMap() {
return this.map;
}
@Override
public Collection<IMobileEntity> getMobileEntities() {
return this.mobileEntities.values();
}
@Override
public IMobileEntity getMobileEntity(final int mapId) {
return getById(this.getMobileEntities(), mapId);
}
@Override
public IMobileEntity getMobileEntity(String name) {
return getByName(this.getMobileEntities(), name);
}
@Override
public synchronized int getNextMapId() {
return ++mapIdSequence;
}
@Override
public Collection<IRenderable> getRenderables(RenderType renderType) {
return this.renderables.get(renderType);
}
@Override
public Collection<Prop> getProps() {
return this.props;
}
@Override
public Prop getProp(int mapId) {
return getById(this.getProps(), mapId);
}
@Override
public Prop getProp(String name) {
return getByName(this.getProps(), name);
}
@Override
public Creature getCreature(int mapId) {
return getById(this.getCreatures(), mapId);
}
@Override
public Creature getCreature(String name) {
return getByName(this.getCreatures(), name);
}
@Override
public Collection<Creature> getCreatures() {
return this.creatures;
}
@Override
public Spawnpoint getSpawnpoint(final int mapId) {
return getById(this.getSpawnPoints(), mapId);
}
@Override
public Spawnpoint getSpawnpoint(final String name) {
return getByName(this.getSpawnPoints(), name);
}
@Override
public Collection<Spawnpoint> getSpawnPoints() {
return this.spawnPoints;
}
@Override
public Collection<StaticShadow> getStaticShadows() {
return this.staticShadows;
}
@Override
public StaticShadow getStaticShadow(int mapId) {
return getById(this.getStaticShadows(), mapId);
}
@Override
public StaticShadow getStaticShadow(String name) {
return getByName(this.getStaticShadows(), name);
}
@Override
public StaticShadowLayer getStaticShadowLayer() {
return this.staticShadowLayer;
}
@Override
public Trigger getTrigger(final int mapId) {
return getById(this.getTriggers(), mapId);
}
@Override
public Trigger getTrigger(final String name) {
return getByName(this.getTriggers(), name);
}
@Override
public Collection<Trigger> getTriggers() {
return this.triggers;
}
@Override
public List<String> getUsedTags() {
final List<String> tags = this.getEntitiesByTag().keySet().stream().collect(Collectors.toList());
Collections.sort(tags);
return tags;
}
@Override
public final void init() {
if (this.initialized) {
return;
}
this.loadMapObjects();
this.addStaticShadows();
this.addAmbientLight();
this.fireEvent(l -> l.environmentInitialized(this));
this.initialized = true;
}
@Override
public boolean isLoaded() {
return this.loaded;
}
@Override
public void load() {
this.init();
if (this.loaded) {
return;
}
Game.getPhysicsEngine().setBounds(new Rectangle2D.Double(0, 0, this.getMap().getSizeInPixels().getWidth(), this.getMap().getSizeInPixels().getHeight()));
for (final IEntity entity : this.getEntities()) {
this.load(entity);
}
this.loaded = true;
this.fireEvent(l -> l.environmentLoaded(this));
}
@Override
public void loadFromMap(final int mapId) {
for (final IMapObjectLayer layer : this.getMap().getMapObjectLayers()) {
Optional<IMapObject> opt = layer.getMapObjects().stream().filter(mapObject -> mapObject.getType() != null && !mapObject.getType().isEmpty() && mapObject.getId() == mapId).findFirst();
if (opt.isPresent()) {
this.load(opt.get());
break;
}
}
}
/**
* Registers a custom loader instance that is responsible for loading and initializing entities of the defined
* MapObjectType.
* <br>
* <br>
* There can only be one loader for a particular type. Calling this method again for the same type will overwrite the previously registered loader.
*
* @param mapObjectLoader
* The MapObjectLoader instance to be registered.
*
* @see IMapObjectLoader#getMapObjectType()
*/
public static void registerMapObjectLoader(IMapObjectLoader mapObjectLoader) {
mapObjectLoaders.put(mapObjectLoader.getMapObjectType(), mapObjectLoader);
}
/**
* Registers a custom <code>IEntity</code> implementation to support being loaded from an <code>IMap</code> instance.
* Note that the specified class needs to be accessible in a static manner. Inner classes that aren't declared statically are not supported.
*
* This is an overload of the {@link #registerCustomEntityType(Class)} method that allows to explicitly specify the <code>MapObjectType</code>
* without
* having to provide an <code>EntityInfo</code> annotation containing this information.
*
* @param <T>
* The type of the custom entity.
* @param mapObjectType
* The custom mapobjectType that is used by <code>IMapObjects</code> to determine the target entity implementation.
* @param entityType
* The class type of the custom entity implementation.
*
* @see IMapObject#getType()
* @see EntityInfo#customMapObjectType()
*/
public static <T extends IEntity> void registerCustomEntityType(String mapObjectType, Class<T> entityType) {
CustomMapObjectLoader<T> mapObjectLoader = new CustomMapObjectLoader<>(mapObjectType, entityType);
registerMapObjectLoader(mapObjectLoader);
}
/**
* Registers a custom <code>IEntity</code> implementation to support being loaded from an <code>IMap</code> instance.
* Note that the specified class needs to be accessible in a static manner. Inner classes that aren't declared statically are not supported.
*
* This implementation uses the provided <code>EntityInfo.customMapObjectType()</code> to determine for which type the specified class should be
* used.
*
* @param <T>
* The type of the custom entity.
* @param entityType
* The class type of the custom entity implementation.
*
* @see Environment#registerCustomEntityType(String, Class)
* @see IMapObject#getType()
* @see EntityInfo#customMapObjectType()
*/
public static <T extends IEntity> void registerCustomEntityType(Class<T> entityType) {
EntityInfo info = entityType.getAnnotation(EntityInfo.class);
if (info == null || info.customMapObjectType().isEmpty()) {
throw new IllegalArgumentException(
"Cannot register a custom entity type without the related EntityInfo.customMapObjectType being specified.\n Add an EntityInfo annotation to the " + entityType + " class and provide the required information or use the registerCustomEntityType overload and provide the type explicitly.");
}
registerCustomEntityType(info.customMapObjectType(), entityType);
}
@Override
public void reloadFromMap(final int mapId) {
this.remove(mapId);
this.loadFromMap(mapId);
}
@Override
public void remove(final IEntity entity) {
if (entity == null) {
return;
}
if (this.entities.get(entity.getRenderType()) != null) {
this.entities.get(entity.getRenderType()).entrySet().removeIf(e -> e.getValue().getMapId() == entity.getMapId());
}
for (String tag : entity.getTags()) {
this.getEntitiesByTag().get(tag).remove(entity);
if (this.getEntitiesByTag().get(tag).isEmpty()) {
this.getEntitiesByTag().remove(tag);
}
}
if (entity instanceof Emitter) {
Emitter emitter = (Emitter) entity;
this.removeEmitter(emitter);
}
if (entity instanceof MapArea) {
this.mapAreas.remove(entity);
}
if (entity instanceof Prop) {
this.props.remove(entity);
}
if (entity instanceof Creature) {
this.creatures.remove(entity);
}
if (entity instanceof CollisionBox) {
this.colliders.remove(entity);
this.staticShadows.removeIf(x -> x.getOrigin() != null && x.getOrigin().equals(entity));
}
if (entity instanceof LightSource) {
this.lightSources.remove(entity);
this.updateColorLayers(entity);
}
if (entity instanceof Trigger) {
this.triggers.remove(entity);
}
if (entity instanceof Spawnpoint) {
this.spawnPoints.remove(entity);
}
if (entity instanceof StaticShadow) {
this.staticShadows.remove(entity);
this.updateColorLayers(entity);
}
if (entity instanceof IMobileEntity) {
this.mobileEntities.values().remove(entity);
}
if (entity instanceof ICombatEntity) {
this.combatEntities.values().remove(entity);
}
this.unload(entity);
this.fireEntityEvent(l -> l.entityRemoved(entity));
}
@Override
public void remove(final int mapId) {
final IEntity ent = this.get(mapId);
if (ent == null) {
return;
}
this.remove(ent);
}
@Override
public <T extends IEntity> void remove(Collection<T> entities) {
if (entities == null) {
return;
}
for (T ent : entities) {
this.remove(ent);
}
}
@Override
public void removeRenderable(final IRenderable renderable) {
for (Collection<IRenderable> rends : this.renderables.values()) {
rends.remove(renderable);
}
}
@Override
public void render(final Graphics2D g) {
g.scale(Game.getCamera().getRenderScale(), Game.getCamera().getRenderScale());
StringBuilder renderDetails = new StringBuilder();
long renderStart = System.nanoTime();
renderDetails.append(this.render(g, RenderType.BACKGROUND));
renderDetails.append(this.render(g, RenderType.GROUND));
if (Game.getConfiguration().debug().isDebug()) {
DebugRenderer.renderMapDebugInfo(g, this.getMap());
}
renderDetails.append(this.render(g, RenderType.SURFACE));
renderDetails.append(this.render(g, RenderType.NORMAL));
long shadowRenderStart = System.nanoTime();
if (this.getStaticShadows().stream().anyMatch(x -> x.getShadowType() != StaticShadowType.NONE)) {
this.getStaticShadowLayer().render(g);
}
final double shadowTime = TimeUtilities.nanoToMs(System.nanoTime() - shadowRenderStart);
renderDetails.append(this.render(g, RenderType.OVERLAY));
long ambientStart = System.nanoTime();
if (Game.getConfiguration().graphics().getGraphicQuality().ordinal() >= Quality.MEDIUM.ordinal() && this.getAmbientLight() != null && this.getAmbientLight().getAlpha() != 0) {
this.getAmbientLight().render(g);
}
final double ambientTime = TimeUtilities.nanoToMs(System.nanoTime() - ambientStart);
renderDetails.append(this.render(g, RenderType.UI));
if (Game.getConfiguration().debug().isLogDetailedRenderTimes()) {
final double totalRenderTime = TimeUtilities.nanoToMs(System.nanoTime() - renderStart);
log.log(Level.INFO, "total render time: {0}ms \n{1} \tSHADOWS: {2}ms \n\tAMBIENT: {3}ms ", new Object[] { totalRenderTime, renderDetails, shadowTime, ambientTime });
}
g.scale(1.0 / Game.getCamera().getRenderScale(), 1.0 / Game.getCamera().getRenderScale());
}
private void fireEvent(Consumer<EnvironmentListener> cons) {
for (EnvironmentListener listener : this.listeners) {
cons.accept(listener);
}
}
private void fireRenderEvent(Graphics2D g, RenderType type) {
for (EnvironmentRenderListener listener : this.renderListeners.get(type)) {
listener.rendered(g, type);
}
}
private void fireEntityEvent(Consumer<EnvironmentEntityListener> cons) {
for (EnvironmentEntityListener listener : this.entityListeners) {
cons.accept(listener);
}
}
@Override
public void unload() {
if (!this.loaded) {
return;
}
// unregister all updatable entities from the current environment
for (final IEntity entity : this.getEntities()) {
this.unload(entity);
}
this.loaded = false;
this.fireEvent(l -> l.environmentUnloaded(this));
}
@Override
public Collection<IEntity> load(final IMapObject mapObject) {
if (mapObjectLoaders.containsKey(mapObject.getType())) {
Collection<IEntity> loadedEntities = mapObjectLoaders.get(mapObject.getType()).load(this, mapObject);
for (IEntity entity : loadedEntities) {
if (entity != null) {
this.add(entity);
}
}
return loadedEntities;
}
return new ArrayList<>();
}
private static <T extends IEntity> T getById(Collection<T> entities, int mapId) {
for (final T m : entities) {
if (m.getMapId() == mapId) {
return m;
}
}
return null;
}
private static <T extends IEntity> T getByName(Collection<T> entities, String name) {
if (name == null || name.isEmpty()) {
return null;
}
for (final T m : entities) {
if (m.getName() != null && m.getName().equals(name)) {
return m;
}
}
return null;
}
private String render(Graphics2D g, RenderType renderType) {
long renderStart = System.nanoTime();
// 1. Render map layers
Game.getRenderEngine().render(g, this.getMap(), renderType);
// 2. Render renderables
for (final IRenderable rend : this.getRenderables(renderType)) {
rend.render(g);
}
// 3. Render entities
Game.getRenderEngine().renderEntities(g, this.entities.get(renderType).values(), renderType == RenderType.NORMAL);
// 4. fire event
this.fireRenderEvent(g, renderType);
if (Game.getConfiguration().debug().isLogDetailedRenderTimes()) {
final double renderTime = TimeUtilities.nanoToMs(System.nanoTime() - renderStart);
return "\t" + renderType + ": " + renderTime + "ms ("
+ this.getMap().getRenderLayers().stream().filter(m -> m.getRenderType() == renderType).count() + " layers, "
+ this.getRenderables(renderType).size() + " renderables, "
+ this.entities.get(renderType).size() + " entities)\n";
}
return null;
}
private void addAmbientLight() {
final int ambientAlpha = this.getMap().getCustomPropertyInt(MapProperty.AMBIENTALPHA);
final Color ambientColor = this.getMap().getCustomPropertyColor(MapProperty.AMBIENTCOLOR, Color.WHITE);
this.ambientLight = new AmbientLight(this, ambientColor, ambientAlpha);
}
private void addStaticShadows() {
final int alpha = this.getMap().getCustomPropertyInt(MapProperty.SHADOWALPHA, StaticShadow.DEFAULT_ALPHA);
final Color color = this.getMap().getCustomPropertyColor(MapProperty.SHADOWCOLOR, StaticShadow.DEFAULT_COLOR);
this.staticShadowLayer = new StaticShadowLayer(this, alpha, color);
}
private void dispose(final Collection<? extends IEntity> entities) {
for (final IEntity entity : entities) {
if (entity instanceof IUpdateable) {
Game.getLoop().detach((IUpdateable) entity);
}
entity.detachControllers();
}
}
/**
* Loads the specified entity by performing the following steps:
* <ol>
* <li>add to physics engine</li>
* <li>register entity for update</li>
* <li>register animation controller for update</li>
* <li>register movement controller for update</li>
* <li>register AI controller for update</li>
* </ol>
*
* @param entity
*/
private void load(final IEntity entity) {
// 1. add to physics engine
this.loadPhysicsEntity(entity);
// 2. register for update or activate
this.loadUpdatableOrEmitterEntity(entity);
// 3. attach all controllers
entity.attachControllers();
if (entity instanceof LightSource || entity instanceof StaticShadow) {
this.updateColorLayers(entity);
}
}
private void loadPhysicsEntity(IEntity entity) {
if (entity instanceof CollisionBox) {
final CollisionBox coll = (CollisionBox) entity;
if (coll.isObstacle()) {
Game.getPhysicsEngine().add(coll.getBoundingBox());
} else {
Game.getPhysicsEngine().add(coll);
}
} else if (entity instanceof ICollisionEntity) {
final ICollisionEntity coll = (ICollisionEntity) entity;
if (coll.hasCollision()) {
Game.getPhysicsEngine().add(coll);
}
}
}
private void loadUpdatableOrEmitterEntity(IEntity entity) {
if (entity instanceof Emitter) {
final Emitter emitter = (Emitter) entity;
if (emitter.isActivateOnInit()) {
emitter.activate();
}
} else if (entity instanceof IUpdateable) {
Game.getLoop().attach((IUpdateable) entity);
}
}
private void loadMapObjects() {
for (final IMapObjectLayer layer : this.getMap().getMapObjectLayers()) {
for (final IMapObject mapObject : layer.getMapObjects()) {
if (mapObject.getType() == null || mapObject.getType().isEmpty()) {
continue;
}
this.load(mapObject);
}
}
}
private static void registerDefaultMapObjectLoaders() {
registerMapObjectLoader(new PropMapObjectLoader());
registerMapObjectLoader(new CollisionBoxMapObjectLoader());
registerMapObjectLoader(new TriggerMapObjectLoader());
registerMapObjectLoader(new EmitterMapObjectLoader());
registerMapObjectLoader(new LightSourceMapObjectLoader());
registerMapObjectLoader(new SpawnpointMapObjectLoader());
registerMapObjectLoader(new MapAreaMapObjectLoader());
registerMapObjectLoader(new StaticShadowMapObjectLoader());
registerMapObjectLoader(new CreatureMapObjectLoader());
}
/**
* Unload the specified entity by performing the following steps:
* <ol>
* <li>remove entities from physics engine</li>
* <li>unregister units from update</li>
* <li>unregister ai controller from update</li>
* <li>unregister animation controller from update</li>
* <li>unregister movement controller from update</li>
* </ol>
*
* @param entity
*/
private void unload(final IEntity entity) {
// 1. remove from physics engine
if (entity instanceof CollisionBox) {
final CollisionBox coll = (CollisionBox) entity;
if (coll.isObstacle()) {
Game.getPhysicsEngine().remove(coll.getBoundingBox());
} else {
Game.getPhysicsEngine().remove(coll);
}
} else if (entity instanceof ICollisionEntity) {
final ICollisionEntity coll = (ICollisionEntity) entity;
Game.getPhysicsEngine().remove(coll);
}
// 2. unregister from update
if (entity instanceof IUpdateable) {
Game.getLoop().detach((IUpdateable) entity);
}
// 3. detach all controllers
entity.detachControllers();
if (entity instanceof Emitter) {
Emitter em = (Emitter) entity;
em.deactivate();
}
}
} |
package net.imagej.ops.convolve;
import static org.junit.Assert.assertSame;
import net.imagej.ops.AbstractOpTest;
import net.imagej.ops.Op;
import net.imglib2.img.Img;
import net.imglib2.img.array.ArrayImgFactory;
import net.imglib2.type.numeric.integer.ByteType;
import org.junit.Test;
/**
* Tests involving convolvers.
*/
public class ConvolveTest extends AbstractOpTest {
/** Tests that the correct convolver is selected. */
@Test
public void testConvolveMethodSelection() {
final Img<ByteType> in =
new ArrayImgFactory<ByteType>().create(new int[] { 20, 20 },
new ByteType());
final Img<ByteType> out = in.copy();
// testing for a small kernel
Img<ByteType> kernel =
new ArrayImgFactory<ByteType>()
.create(new int[] { 3, 3 }, new ByteType());
Op op = ops.op("convolve", out, in, kernel);
assertSame(ConvolveNaive.class, op.getClass());
// testing for a 'bigger' kernel
kernel =
new ArrayImgFactory<ByteType>().create(new int[] { 10, 10 },
new ByteType());
op = ops.op("convolve", in, out, kernel);
assertSame(ConvolveFourier.class, op.getClass());
}
} |
package de.mrunde.bachelorthesis.basics;
/**
* Categories of landmarks (e.g. gas station, hospital, post office)
*
* @author Marius Runde
*/
public abstract class LandmarkCategory {
/**
* Church
*/
public final static String CHURCH = "church";
/**
* Cinema
*/
public final static String CINEMA = "cinema";
/**
* Gas station
*/
public final static String GAS_STATION = "gas station";
/**
* Hospital
*/
public final static String HOSPITAL = "hospital";
/**
* Monument - should be always replaced with the real name of the landmark
*/
public final static String MONUMENT = "monument";
/**
* Post office
*/
public final static String POST_OFFICE = "post office";
/**
* Train station
*/
public final static String TRAIN_STATION = "train station";
/**
* Check if a category is a valid Landmark category
*
* @param category
* Category to be controlled
* @return TRUE: <code>category</code> is valid<br/>
* FALSE: <code>category</code> is not valid
*/
public static boolean isCategory(String category) {
if (category.equals(CHURCH))
return true;
if (category.equals(CINEMA))
return true;
if (category.equals(GAS_STATION))
return true;
if (category.equals(HOSPITAL))
return true;
if (category.equals(MONUMENT))
return true;
if (category.equals(POST_OFFICE))
return true;
if (category.equals(TRAIN_STATION))
return true;
return false;
}
} |
package org.apps8os.trafficsense.first;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public class JourneyParser {
private JsonObject _mainObj ; // Declare the JSON object
private JsonArray _segmentsArray;
private ArrayList<String> _textArray = new ArrayList<String>();
private int _nline = 0 ; // Line number of txt file
private String _txtLine ; // the line read it from the txt
public JourneyParser() {
_mainObj = new JsonObject();
_segmentsArray = new JsonArray();
}
private int getLine(){
return _nline ;
}
private void incrementLine(){
_nline++;
}
private String getTxtLine(){
return _txtLine ;
}
private void setTxtLine(String txtLine){
_txtLine = txtLine ;
}
private ArrayList<String> getTextArray(){
return _textArray ;
}
private void flushTextArray(){
this.getTextArray().clear();
}
private void addTextArray(String line){
// trim removes the white space at the beginning and end
this.getTextArray().add(line.trim());
}
public JsonObject getJsonObj(){
return _mainObj ;
}
private void setJsonObj(String key, String value){
_mainObj.addProperty(key, value);
}
private void setJsonObj(String key, JsonElement element) {
_mainObj.add(key, element);
}
private JsonArray getSegmentsArray(){
return _segmentsArray;
}
private void setSegmentsArray(JsonElement value){
_segmentsArray.add(value);
}
public void addJsonObject(){
if(this.getLine() == 1){
this.setJsonObj("date", this.getTxtLine());
return;
}
if(this.getLine() == 3){
String[] parts = this.getTxtLine().split(" ",2);
this.setJsonObj("start",parts[1]);
return;
}
// The str has the time and location and will split into two parts
String str;
String[] str_split;
try {
str = getTextArray().get(0);
str_split = str.split(" ",2); // will just split one time = 2 parts
} catch (IndexOutOfBoundsException ex) {
// this is an extra blank line, just ignore it
return;
}
if(! getTextArray().get(1).equals("Arrival")){
JsonObject SegmentsObj = new JsonObject();
SegmentsObj.addProperty("startTime", str_split[0]);
SegmentsObj.addProperty("startPoint", str_split[1]);
SegmentsObj.addProperty("mode", getTextArray().get(1));
this.setSegmentsArray(SegmentsObj);
JsonArray waypointsArray = new JsonArray();
for(int i=2 ; i < getTextArray().size() ; i++) {
JsonObject waypointObj = new JsonObject();
str_split = getTextArray().get(i).split(" ",2);
waypointObj.addProperty("time",str_split[0]);
waypointObj.addProperty("name",str_split[1]);
if(! getTextArray().get(1).contains("Walking")){
// If the user is not walking will have a stopCode for each point
;
String stopCode ;
int start,end;
start = str_split[1].indexOf( "(" )+1;
end = str_split[1].indexOf( ")" );
stopCode = str_split[1].substring(start,end);
waypointObj.remove("name");
waypointObj.addProperty("name",str_split[1].substring(0, start-1));
waypointObj.addProperty("stopCode",stopCode);
}
waypointsArray.add(waypointObj);
}
SegmentsObj.add("waypoints", waypointsArray);
}else{
// Last line of the file, "Arrival" line
//System.out.println("ARRAY " + this.getSegmentsArray());
this.setJsonObj("dest",str_split[1]);
this.setJsonObj("arrivalTime",str_split[0]);
this.setJsonObj("segments", this.getSegmentsArray());
}
}
/**
*Will add the different objects and arrays to JSON file
*/
public void organizeJson(String line){
switch(this.getLine()){
case 1 : this.addJsonObject();return; // Add to json object the key value "date"
case 2: return; // "Departure" line
case 3: this.addJsonObject(); // Add to json object the key value "start"
}
/* isNotBlank - Checks if a String is not empty (""), not null and not whitespace only
*
*/
if(line.trim().equals("")){
// The line is blank
this.addJsonObject();
//System.out.println("ARRAY: " + text);
this.flushTextArray();
return;
}else{
this.addTextArray(line);
}
if( this.getTxtLine().equals("Arrival")) {
this.addJsonObject();
this.flushTextArray();
}
}
public String getJsonText() {
return _mainObj.toString();
}
public void writeJsonFile(String outFileName){
try {
FileWriter file = new FileWriter(outFileName);
file.write(this.getJsonObj().toString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void parseOneLine(String line) {
//System.out.println("Line: "+line);
this.setTxtLine(line);
this.incrementLine(); // will increment a read line on txt file, counter starts 0
this.organizeJson(line);
}
/* parse a journey supplied in a String */
public void parseString(String jsonText) {
Scanner scanner = new Scanner(jsonText);
while (scanner.hasNextLine()) {
String line=scanner.nextLine();
parseOneLine(line);
if(line.equals("Arrival")){
break;
}
}
scanner.close();
}
/* parse a journey in a text file */
public void parsingFile(String fileName){
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding and wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
while((line = bufferedReader.readLine()) != null) {
parseOneLine(line);
if(getTxtLine().equals("Arrival")){
// Document it was already all parsed
break;
}
}
bufferedReader.close(); // Close the file
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
}
catch(IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
// ex.printStackTrace();
}
}
} |
package moses.client.preferences;
import moses.client.R;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ImageView;
public class ImageArrayAdapter extends ArrayAdapter<CharSequence> {
private boolean[] index = null;
private int[] resourceIds = null;
public ImageArrayAdapter(Context context, int textViewResourceId, CharSequence[] objects, int[] ids, boolean[] i) {
super(context, textViewResourceId, objects);
index = i;
resourceIds = ids;
}
/**
* {@inheritDoc}
*/
@Override
public View getView(int position, View convertView, final ViewGroup parent) {
final int realposition = position - 1;
LayoutInflater inflater = ((Activity) getContext()).getLayoutInflater();
View row = inflater.inflate(R.layout.list_preference_multi_select, parent, false);
if (realposition >= 0) {
ImageView imageView = (ImageView) row.findViewById(R.id.image);
imageView.setImageResource(resourceIds[realposition]);
}
CheckedTextView checkedTextView = (CheckedTextView) row.findViewById(R.id.check);
checkedTextView.setText(getItem(position));
if (realposition >= 0 && index[realposition]) {
checkedTextView.setChecked(true);
} else {
boolean somethingsFalse = true;
for (boolean b : index) {
if (!b)
somethingsFalse = false;
}
if (somethingsFalse)
checkedTextView.setChecked(true);
}
if (realposition >= 0) {
row.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
CheckedTextView checkedTextView = (CheckedTextView) v.findViewById(R.id.check);
index[realposition] = !index[realposition];
checkedTextView.setChecked(index[realposition]);
ImageArrayAdapter.this.notifyDataSetChanged();
}
});
} else {
row.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
boolean somethingsFalse = false;
for (boolean b : index) {
if (!b)
somethingsFalse = true;
}
if (somethingsFalse) {
for (int i = 0; i < index.length; ++i) {
index[i] = true;
}
} else {
for (int i = 0; i < index.length; ++i) {
index[i] = false;
}
}
CheckedTextView checkedTextView = (CheckedTextView) v.findViewById(R.id.check);
checkedTextView.setChecked(!checkedTextView.isChecked());
ImageArrayAdapter.this.notifyDataSetChanged();
}
});
}
return row;
}
} |
package org.mwg.ml.common;
import org.mwg.Callback;
import org.mwg.Graph;
import org.mwg.ml.common.mathexp.KMathExpressionEngine;
import org.mwg.ml.common.mathexp.impl.MathExpressionEngine;
import org.mwg.plugin.AbstractNode;
public abstract class AbstractMLNode extends AbstractNode {
public static String FROM_SEPARATOR=";";
public static String FROM="FROM";
public AbstractMLNode(long p_world, long p_time, long p_id, Graph p_graph, long[] currentResolution) {
super(p_world, p_time, p_id, p_graph, currentResolution);
}
@Override
public Object get(String propertyName) {
if (propertyName != null && propertyName.startsWith("$")) {
Object expressionObj = super.get(propertyName.substring(1));
//ToDo this is dangerous for infinite loops or circular dependency, to fix
KMathExpressionEngine localEngine = MathExpressionEngine.parse(expressionObj.toString());
return localEngine.eval(this);
} else {
return super.get(propertyName);
}
}
public void extractFeatures(Callback<double[]> callback){
String query= (String)super.get(FROM);
double[] result;
if(query!=null) {
String[] split = query.split(FROM_SEPARATOR);
result = new double[split.length];
for (int i = 0; i < result.length; i++) {
KMathExpressionEngine localEngine = MathExpressionEngine.parse(split[i]);
result[i] = localEngine.eval(this);
}
callback.on(result);
}
else {
callback.on(null);
}
}
} |
package io.schinzel.basicutils.state;
import com.google.common.collect.Streams;
import io.schinzel.basicutils.EmptyObjects;
import io.schinzel.basicutils.Thrower;
import io.schinzel.basicutils.str.Str;
import org.json.JSONArray;
import java.util.*;
import java.util.stream.Collectors;
/**
* The purpose of this class is to build state instances.
*
* @author schinzel
*/
public class StateBuilder {
/**
* A list of properties.
*/
List<Property> mProperties = new ArrayList<>();
/**
* Named children of state being built.
*/
Map<String, State> mChildren = new HashMap<>();
/**
* Named lists of children of the state being built.
*/
Map<String, List<State>> mChildLists = new HashMap<>();
// CONSTRUCTION
/**
* Package private constructor so that this cannot be used outside this
* package.
*/
StateBuilder() {
}
/**
* @param state A seed to copy. Typically a super state that you want to append to in a sub class.
*/
StateBuilder(State state) {
mProperties = new ArrayList<>(state.mProperties);
mChildren = new HashMap<>(mChildren);
mChildLists = new HashMap<>(mChildLists);
}
/**
* @return An instance of the class state.
*/
public State build() {
return new State(this);
}
// ADD PROPERTIES
/**
* @param key The key of the argument value.
* @param val The value to add.
* @return This for chaining.
*/
public StateBuilder add(String key, String val) {
Thrower.throwIfTrue(val == null, "Cannot add a null as a State String value.");
mProperties.add(new Property(key, val, val));
return this;
}
/**
* @param key The key of the argument value.
* @param val The value to add.
* @return This for chaining.
*/
public StateBuilder add(String key, int val) {
return this.add(key, (long) val);
}
/**
* @param key The key of the argument value.
* @param val The value to add.
* @return This for chaining.
*/
public StateBuilder add(String key, long val) {
String valAsStr = Str.create().a(val).toString();
mProperties.add(new Property(key, valAsStr, val));
return this;
}
/**
* @param key The key of the argument value.
* @param val The value to add.
* @param numOfDecimals The number of decimals to display in the string
* representation of the argument value.
* @return This for chaining.
*/
public StateBuilder add(String key, float val, int numOfDecimals) {
return this.add(key, (double) val, numOfDecimals);
}
/**
* @param key The key of the argument value.
* @param val The value to add.
* @param numOfDecimals The number of decimals to display in the string
* representation of the argument value.
* @return This for chaining.
*/
public StateBuilder add(String key, double val, int numOfDecimals) {
String valAsStr = Str.create().a(val, numOfDecimals).toString();
mProperties.add(new Property(key, valAsStr, val));
return this;
}
/**
* @param key The key of the argument value.
* @param val The value to add.
* @return This for chaining.
*/
public StateBuilder add(String key, boolean val) {
String valAsStr = String.valueOf(val);
mProperties.add(new Property(key, valAsStr, val));
return this;
}
public StateBuilder add(String key, String[] values) {
mProperties.add(new Property(key, String.join(", ", values), new JSONArray(values)));
return this;
}
public StateBuilder add(String key, List<String> values) {
return this.add(key, values.toArray(EmptyObjects.EMPTY_STRING_ARRAY));
}
// ADD CHILDREN
/**
* Adds a child state. This so that an hierarchy of state can be
* constructed.
*
* @param key The key of the argument child.
* @param child The child to add.
* @return This for chaining.
*/
public StateBuilder add(String key, IStateNode child) {
mChildren.put(key, child.getState());
return this;
}
/**
* Adds a collection of children. This so that an hierarchy of state can be
* constructed.
*
* @param key The key of the argument children.
* @param children The children to add.
* @return This for chaining.
*/
public StateBuilder add(String key, Iterator<? extends IStateNode> children) {
List<State> childList = Streams.stream(children)
.map(IStateNode::getState)
.collect(Collectors.toList());
if (!childList.isEmpty()) {
mChildLists.put(key, childList);
}
return this;
}
} |
package com.rho.rubyext;
import com.rho.RhoEmptyLogger;
import com.rho.RhoLogger;
import com.xruby.runtime.builtin.RubyArray;
import com.xruby.runtime.builtin.RubyString;
import com.xruby.runtime.builtin.RubyHash;
import com.xruby.runtime.builtin.ObjectFactory;
import com.xruby.runtime.lang.*;
import javax.microedition.pim.*;
//@RubyLevelClass(name="Phonebook")
public class RhoPhonebook extends RubyBasic {
private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() :
new RhoLogger("Phonebook");
private ContactList m_contactList;
static final RubyString RUBY_PB_ID = ObjectFactory.createString("id");
static final RubyString RUBY_PB_FIRST_NAME = ObjectFactory.createString("first_name");
static final RubyString RUBY_PB_LAST_NAME = ObjectFactory.createString("last_name");
static final RubyString RUBY_PB_MOBILE_NUMBER = ObjectFactory.createString("mobile_number");
static final RubyString RUBY_PB_HOME_NUMBER = ObjectFactory.createString("home_number");
static final RubyString RUBY_PB_BUSINESS_NUMBER = ObjectFactory.createString("business_number");
static final RubyString RUBY_PB_EMAIL_ADDRESS = ObjectFactory.createString("email_address");
static final RubyString RUBY_PB_COMPANY_NAME = ObjectFactory.createString("company_name");
public static class PBRecord extends RubyBasic {
Contact m_contact;
public PBRecord(RubyClass arg0) {
super(arg0);
}
public PBRecord(Contact contact) {
super(RubyRuntime.PBRecordClass);
m_contact = contact;
}
}
public RhoPhonebook(RubyClass arg0) {
super(arg0);
try {
m_contactList = (ContactList) PIM.getInstance().openPIMList(
PIM.CONTACT_LIST, PIM.READ_WRITE);
} catch (PIMException e) {
new RubyException(e.getMessage());
}
}
//@RubyAllocMethod
public static RhoPhonebook alloc(RubyValue receiver) {
return new RhoPhonebook(RubyRuntime.PhonebookClass);
}
public static RubyValue openPhonebook() {
RhoPhonebook pb = alloc(null);
return pb;
}
public static RubyValue closePhonebook(RubyValue arg0) {
try {
RhoPhonebook pb = (RhoPhonebook)arg0;
pb.m_contactList.close();
pb.m_contactList = null;
} catch (PIMException e) {
new RubyException(e.getMessage());
}
return RubyConstant.QNIL;
}
RubyHash getPBRecord( Contact contact ){
RubyHash record = ObjectFactory.createHash();
if ( m_contactList.isSupportedField(Contact.UID) &&
contact.countValues(Contact.UID) > 0 ){
String strValue = "{" + contact.getString(Contact.UID, 0) + "}";
record.add(RUBY_PB_ID, ObjectFactory.createString(strValue));
}
if ( m_contactList.isSupportedField(Contact.TEL) ){
for (int i = 0, size = contact.countValues(Contact.TEL); i < size; i++) {
String strValue = contact.getString(Contact.TEL, i);
if ( strValue.length() == 0 )
continue;
int attr = contact.getAttributes(Contact.TEL, i);
if ((attr & Contact.ATTR_MOBILE) != 0)
record.add(RUBY_PB_MOBILE_NUMBER, ObjectFactory.createString(strValue));
else if ((attr & Contact.ATTR_HOME) != 0)
record.add(RUBY_PB_HOME_NUMBER, ObjectFactory.createString(strValue));
else if ((attr & Contact.ATTR_WORK) != 0)
record.add(RUBY_PB_BUSINESS_NUMBER, ObjectFactory.createString(strValue));
}
}
if ( m_contactList.isSupportedField(Contact.EMAIL) ){
for (int i = 0, size = contact.countValues(Contact.EMAIL); i < size; i++) {
String strValue = contact.getString(Contact.EMAIL, i);
if ( strValue.length() == 0 )
continue;
record.add(RUBY_PB_EMAIL_ADDRESS, ObjectFactory.createString(strValue));
break;
}
}
if ( m_contactList.isSupportedField(Contact.ORG) &&
contact.countValues(Contact.ORG) > 0 ){
String strValue = contact.getString(Contact.ORG, 0);
if ( strValue.length() > 0 )
record.add(RUBY_PB_COMPANY_NAME, ObjectFactory.createString(strValue));
}
boolean bNameFound = false;
if ( m_contactList.isSupportedField(Contact.NAME) &&
contact.countValues(Contact.NAME) > 0 ){
String[] names = contact.getStringArray(Contact.NAME, 0);
if ( names != null ){
if (names[Contact.NAME_GIVEN] != null){
record.add(RUBY_PB_FIRST_NAME, ObjectFactory.createString(names[Contact.NAME_GIVEN]));
bNameFound = true;
}
if (names[Contact.NAME_FAMILY] != null){
record.add(RUBY_PB_LAST_NAME, ObjectFactory.createString(names[Contact.NAME_FAMILY]));
bNameFound = true;
}
}
}
if ( !bNameFound && m_contactList.isSupportedField(Contact.FORMATTED_NAME) &&
contact.countValues(Contact.FORMATTED_NAME) > 0 ){
String strValue = contact.getString(Contact.FORMATTED_NAME, 0);
if ( strValue.length() > 0 )
record.add(RUBY_PB_FIRST_NAME, ObjectFactory.createString(strValue));
}
return record;
}
public static RubyValue getallPhonebookRecords(RubyValue arg0) {
RhoPhonebook pb = (RhoPhonebook)arg0;
RubyHash res = ObjectFactory.createHash();
try {
java.util.Enumeration contacts = pb.m_contactList.items();
while (contacts.hasMoreElements()) {
Contact contact = (Contact) contacts.nextElement();
RubyHash record = pb.getPBRecord( contact );
res.add(record.get(RUBY_PB_ID), record);
}
} catch (PIMException e) {
new RubyException(e.getMessage());
}
return res;
}
private Contact findContactByID(RubyValue arg0, RubyValue arg1 ){
Contact contact = null;
try {
Contact matching = m_contactList.createContact();
String id = arg1.toString();
id = id.substring(1, id.length()-1);
matching.addString(Contact.UID, Contact.ATTR_NONE, id);
java.util.Enumeration contacts = m_contactList.items(matching);
if (contacts.hasMoreElements())
contact = (Contact) contacts.nextElement();
} catch (PIMException e) {
new RubyException(e.getMessage());
}
return contact;
}
public static RubyValue getPhonebookRecord(RubyValue arg0, RubyValue arg1) {
RhoPhonebook pb = (RhoPhonebook)arg0;
RubyHash record = ObjectFactory.createHash();
Contact contact = pb.findContactByID(arg0,arg1);
if ( contact != null )
record = pb.getPBRecord( contact );
return record;
}
public static RubyValue openPhonebookRecord(RubyValue arg0, RubyValue arg1) {
RhoPhonebook pb = (RhoPhonebook)arg0;
Contact contact = pb.findContactByID(arg0,arg1);
if ( contact != null )
return new PBRecord(contact);
return RubyConstant.QNIL;
}
public static RubyValue setRecordValue(RubyArray ar) {
if ( ar.get(0) == RubyConstant.QNIL || ar.get(0) == null )
return RubyConstant.QFALSE;
PBRecord record = (PBRecord)ar.get(0);
RubyString strKey = ar.get(1).toRubyString();
String strValue = ar.get(2).toStr();
Contact contact = record.m_contact;
int field = 0, index = 0, attributes = Contact.ATTR_NONE;
if ( strKey.opEql(RUBY_PB_ID) == RubyConstant.QTRUE )
return RubyConstant.QFALSE;
if ( contact.getPIMList().isSupportedField(Contact.NAME) ){
if ( strKey.opEql(RUBY_PB_FIRST_NAME) == RubyConstant.QTRUE ){
if ( contact.countValues(Contact.NAME) > 0 ){
String[] names = contact.getStringArray(Contact.NAME, 0);
names[Contact.NAME_GIVEN] = strValue;
contact.setStringArray(Contact.NAME, 0, Contact.ATTR_NONE, names);
}else{
String[] names = new String[contact.getPIMList().stringArraySize(Contact.NAME)];
names[Contact.NAME_GIVEN] = strValue;
contact.addStringArray(Contact.NAME, Contact.ATTR_NONE, names);
}
return RubyConstant.QTRUE;
}else if ( strKey.opEql(RUBY_PB_LAST_NAME) == RubyConstant.QTRUE ){
if ( contact.countValues(Contact.NAME) > 0 ){
String[] names = contact.getStringArray(Contact.NAME, 0);
names[Contact.NAME_FAMILY] = strValue;
contact.setStringArray(Contact.NAME, 0, Contact.ATTR_NONE, names);
}else{
String[] names = new String[contact.getPIMList().stringArraySize(Contact.NAME)];
names[Contact.NAME_FAMILY] = strValue;
contact.addStringArray(Contact.NAME, Contact.ATTR_NONE, names);
}
return RubyConstant.QTRUE;
}
}
if ( strKey.opEql(RUBY_PB_EMAIL_ADDRESS) == RubyConstant.QTRUE ){
field = Contact.EMAIL;
}else if ( strKey.opEql(RUBY_PB_COMPANY_NAME) == RubyConstant.QTRUE ){
field = Contact.ORG;
}else if ( strKey.opEql(RUBY_PB_MOBILE_NUMBER) == RubyConstant.QTRUE ){
field = Contact.TEL;
attributes = Contact.ATTR_MOBILE;
boolean bFound = false;
if ( contact.getPIMList().isSupportedField(Contact.TEL) ){
for (int i = 0, size = contact.countValues(Contact.TEL); i < size; i++) {
int attr = contact.getAttributes(Contact.TEL, i);
if ((attr & Contact.ATTR_MOBILE) != 0){
index = i;
bFound = true;
break;
}
}
}
if ( !bFound )
index = -1;
}else if ( strKey.opEql(RUBY_PB_HOME_NUMBER) == RubyConstant.QTRUE ){
field = Contact.TEL;
attributes = Contact.ATTR_HOME;
boolean bFound = false;
if ( contact.getPIMList().isSupportedField(Contact.TEL) ){
for (int i = 0, size = contact.countValues(Contact.TEL); i < size; i++) {
int attr = contact.getAttributes(Contact.TEL, i);
if ((attr & Contact.ATTR_HOME) != 0){
index = i;
bFound = true;
break;
}
}
}
if ( !bFound )
index = -1;
}else if ( strKey.opEql(RUBY_PB_BUSINESS_NUMBER) == RubyConstant.QTRUE ){
field = Contact.TEL;
attributes = Contact.ATTR_WORK;
boolean bFound = false;
if ( contact.getPIMList().isSupportedField(Contact.TEL) ){
for (int i = 0, size = contact.countValues(Contact.TEL); i < size; i++) {
int attr = contact.getAttributes(Contact.TEL, i);
if ((attr & Contact.ATTR_WORK) != 0){
index = i;
bFound = true;
break;
}
}
}
if ( !bFound )
index = -1;
}else
return RubyConstant.QFALSE;
if ( index == -1 )
contact.addString(field, attributes, strValue);
else if ( contact.countValues(field) > 0 ){
contact.removeValue(field, index);
contact.addString(field, attributes, strValue);
//contact.setString(field, index, attributes, strValue);
}
else
contact.addString(field, attributes, strValue);
return RubyConstant.QTRUE;
}
public static RubyValue saveRecord(RubyValue arg0, RubyValue arg1) {
PBRecord record = (PBRecord)arg1;
try {
record.m_contact.commit();
} catch (PIMException e) {
new RubyException(e.getMessage());
}
return RubyConstant.QTRUE;
}
public static RubyValue createRecord(RubyValue arg0) {
RhoPhonebook pb = (RhoPhonebook)arg0;
Contact contact = pb.m_contactList.createContact();
if ( contact != null )
return new PBRecord(contact);
return RubyConstant.QNIL;
}
public static RubyValue addRecord(RubyValue arg0, RubyValue arg1) {
return saveRecord(arg0, arg1);
}
public static RubyValue deleteRecord(RubyValue arg0, RubyValue arg1) {
RhoPhonebook pb = (RhoPhonebook)arg0;
PBRecord record = (PBRecord)arg1;
try {
pb.m_contactList.removeContact(record.m_contact);
} catch (PIMException e) {
new RubyException(e.getMessage());
}
return RubyConstant.QTRUE;
}
public static void initMethods( RubyClass klass){
klass.defineAllocMethod(new RubyNoArgMethod(){
protected RubyValue run(RubyValue receiver, RubyBlock block ) {
return RhoPhonebook.alloc(receiver);}
});
klass.getSingletonClass().defineMethod("openPhonebook", new RubyNoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyBlock block)
{
try {
return RhoPhonebook.openPhonebook();
} catch(Exception e) {
LOG.ERROR("openPhonebook failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
klass.getSingletonClass().defineMethod("closePhonebook", new RubyOneArgMethod() {
protected RubyValue run(RubyValue receiver, RubyValue arg0, RubyBlock block)
{
try {
return RhoPhonebook.closePhonebook(arg0);
} catch(Exception e) {
LOG.ERROR("closePhonebook failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
klass.getSingletonClass().defineMethod("allRecords", new RubyOneArgMethod() {
protected RubyValue run(RubyValue receiver, RubyValue arg0, RubyBlock block)
{
try {
return RhoPhonebook.getallPhonebookRecords(arg0);
} catch(Exception e) {
LOG.ERROR("allRecords failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
klass.getSingletonClass().defineMethod("openRecord", new RubyTwoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyValue arg0, RubyValue arg1, RubyBlock block)
{
try {
return RhoPhonebook.openPhonebookRecord(arg0, arg1);
} catch(Exception e) {
LOG.ERROR("openRecord failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
klass.getSingletonClass().defineMethod("getRecord", new RubyTwoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyValue arg0, RubyValue arg1, RubyBlock block)
{
try {
return RhoPhonebook.getPhonebookRecord(arg0, arg1);
} catch(Exception e) {
LOG.ERROR("getRecord failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
klass.getSingletonClass().defineMethod("createRecord", new RubyOneArgMethod() {
protected RubyValue run(RubyValue receiver, RubyValue arg0, RubyBlock block)
{
try {
return RhoPhonebook.createRecord(arg0);
} catch(Exception e) {
LOG.ERROR("createRecord failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
klass.getSingletonClass().defineMethod("setRecordValue", new RubyVarArgMethod() {
protected RubyValue run(RubyValue receiver, RubyArray ar, RubyBlock block)
{
try {
return RhoPhonebook.setRecordValue(ar);
} catch(Exception e) {
LOG.ERROR("setRecordValue failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
klass.getSingletonClass().defineMethod("addRecord", new RubyTwoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyValue arg0, RubyValue arg1, RubyBlock block)
{
try {
return RhoPhonebook.addRecord(arg0, arg1);
} catch(Exception e) {
LOG.ERROR("addRecord failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
klass.getSingletonClass().defineMethod("saveRecord", new RubyTwoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyValue arg0, RubyValue arg1, RubyBlock block)
{
try {
return RhoPhonebook.saveRecord(arg0, arg1);
} catch(Exception e) {
LOG.ERROR("saveRecord failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
klass.getSingletonClass().defineMethod("deleteRecord", new RubyTwoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyValue arg0, RubyValue arg1, RubyBlock block)
{
try {
return RhoPhonebook.deleteRecord(arg0, arg1);
} catch(Exception e) {
LOG.ERROR("deleteRecord failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
}
} |
package dr.app.beauti.treespanel;
import dr.app.beauti.BeautiFrame;
import dr.app.beauti.options.BeautiOptions;
import dr.app.beauti.options.ClockModelGroup;
import dr.app.beauti.options.PartitionTreeModel;
import dr.app.beauti.types.FixRateType;
import dr.app.beauti.types.StartingTreeType;
import dr.app.beauti.util.PanelUtils;
import dr.app.beauti.util.TextUtil;
import dr.app.gui.components.RealNumberField;
import dr.app.gui.tree.JTreeDisplay;
import dr.app.gui.tree.JTreePanel;
import dr.app.gui.tree.SquareTreePainter;
import dr.app.util.OSType;
import dr.evolution.datatype.DataType;
import dr.evolution.datatype.PloidyType;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import jam.panels.OptionsPanel;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
/**
* @author Andrew Rambaut
* @author Alexei Drummond
* @author Walter Xie
* @version $Id: PriorsPanel.java,v 1.9 2006/09/05 13:29:34 rambaut Exp $
*/
public class PartitionTreeModelPanel extends OptionsPanel {
private static final long serialVersionUID = 8096349200725353543L;
private final String NO_TREE = "no tree loaded";
private JComboBox ploidyTypeCombo = new JComboBox(PloidyType.values());
private ButtonGroup startingTreeGroup = new ButtonGroup();
private JRadioButton randomTreeRadio = new JRadioButton("Random starting tree");
private JRadioButton upgmaTreeRadio = new JRadioButton("UPGMA starting tree");
private JRadioButton userTreeRadio = new JRadioButton("User-specified starting tree");
private JLabel userTreeLabel = new JLabel("Select user-specified tree:");
private JComboBox userTreeCombo = new JComboBox();
private JLabel treeFormatLabel = new JLabel("Export format for tree:");
private JComboBox treeFormatCombo = new JComboBox(new String[] {"Newick", "XML"});
private JLabel userTreeInfo = new JLabel("<html>" +
"Import user-specified starting trees from <b>NEXUS</b><br>" +
"format data files using the 'Import Data' menu option.<br>" +
"Trees must be rooted and strictly bifurcating (binary).</html>");
// private JButton treeDisplayButton = new JButton("Display selected tree");
// private JButton correctBranchLengthButton = new JButton("Correct branch lengths to get ultrametric tree");
private RealNumberField initRootHeightField = new RealNumberField(Double.MIN_VALUE, Double.POSITIVE_INFINITY);
private BeautiOptions options = null;
private final BeautiFrame parent;
private boolean settingOptions = false;
PartitionTreeModel partitionTreeModel;
public PartitionTreeModelPanel(final BeautiFrame parent, PartitionTreeModel parTreeModel, final BeautiOptions options) {
super(12, (OSType.isMac() ? 6 : 24));
this.partitionTreeModel = parTreeModel;
this.options = options;
this.parent = parent;
PanelUtils.setupComponent(initRootHeightField);
initRootHeightField.setColumns(10);
initRootHeightField.setEnabled(false);
PanelUtils.setupComponent(ploidyTypeCombo);
ploidyTypeCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
partitionTreeModel.setPloidyType((PloidyType) ploidyTypeCombo.getSelectedItem());
}
});
if (options.isEBSPSharingSamePrior() || options.useStarBEAST) {
ploidyTypeCombo.setSelectedItem(partitionTreeModel.getPloidyType());
}
PanelUtils.setupComponent(randomTreeRadio);
PanelUtils.setupComponent(upgmaTreeRadio);
PanelUtils.setupComponent(userTreeRadio);
startingTreeGroup.add(randomTreeRadio);
startingTreeGroup.add(upgmaTreeRadio);
startingTreeGroup.add(userTreeRadio);
randomTreeRadio.setSelected(partitionTreeModel.getStartingTreeType() == StartingTreeType.RANDOM);
upgmaTreeRadio.setSelected(partitionTreeModel.getStartingTreeType() == StartingTreeType.UPGMA);
userTreeRadio.setSelected(partitionTreeModel.getStartingTreeType() == StartingTreeType.USER);
userTreeRadio.setEnabled(options.userTrees.size() > 0);
boolean enabled = partitionTreeModel.getStartingTreeType() == StartingTreeType.USER;
userTreeLabel.setEnabled(enabled);
userTreeCombo.setEnabled(enabled);
treeFormatLabel.setEnabled(enabled);
treeFormatCombo.setEnabled(enabled);
userTreeInfo.setEnabled(enabled);
PanelUtils.setupComponent(treeFormatCombo);
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
if (randomTreeRadio.isSelected()) {
partitionTreeModel.setStartingTreeType(StartingTreeType.RANDOM);
} else if (upgmaTreeRadio.isSelected()) {
partitionTreeModel.setStartingTreeType(StartingTreeType.UPGMA);
} else if (userTreeRadio.isSelected()) {
partitionTreeModel.setStartingTreeType(StartingTreeType.USER);
}
boolean enabled = partitionTreeModel.getStartingTreeType() == StartingTreeType.USER;
userTreeLabel.setEnabled(enabled);
userTreeCombo.setEnabled(enabled);
treeFormatLabel.setEnabled(enabled);
treeFormatCombo.setEnabled(enabled);
userTreeInfo.setEnabled(enabled);
}
};
randomTreeRadio.addActionListener(listener);
upgmaTreeRadio.addActionListener(listener);
userTreeRadio.addActionListener(listener);
treeFormatCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent itemEvent) {
partitionTreeModel.setNewick(treeFormatCombo.getSelectedItem().equals("Newick"));
}
});
PanelUtils.setupComponent(userTreeCombo);
userTreeCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
setUserSpecifiedStartingTree();
}
});
// PanelUtils.setupComponent(treeDisplayButton);
// treeDisplayButton.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// SquareTreePainter treePainter = new SquareTreePainter();
// treePainter.setColorAttribute("color");
// treePainter.setLineAttribute("line");
//// treePainter.setShapeAttribute("shape");
// treePainter.setLabelAttribute("label");
// Tree tree = getSelectedUserTree();
// JTreeDisplay treeDisplay = new JTreeDisplay(treePainter, tree);
// JTreePanel treePanel = new JTreePanel(treeDisplay);
// JOptionPane optionPane = new JOptionPane(treePanel,
// JOptionPane.PLAIN_MESSAGE,
// JOptionPane.OK_OPTION,
// null,
// null,
// null);
// optionPane.setBorder(new EmptyBorder(12, 12, 12, 12));
// final JDialog dialog = optionPane.createDialog(parent, "Display the selected starting tree - " + tree.getId());
// dialog.setSize(600, 400);
// dialog.setResizable(true);
// dialog.setVisible(true);
// PanelUtils.setupComponent(correctBranchLengthButton);
// correctBranchLengthButton.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// Tree tree = getSelectedUserTree();
// Tree.Utils.correctBranchLengthToGetUltrametricTree(tree);
// partitionTreeModel.setUserStartingTree(tree);
setupPanel();
}
private void setUserSpecifiedStartingTree() {
if (userTreeCombo.getSelectedItem() != null && (!userTreeCombo.getSelectedItem().toString().equalsIgnoreCase(NO_TREE))) {
Tree seleTree = getSelectedUserTree();
if (seleTree == null || isBifurcatingTree(seleTree, seleTree.getRoot())) {
partitionTreeModel.setUserStartingTree(seleTree);
} else {
JOptionPane.showMessageDialog(parent, "The selected user-specified starting tree " +
"is not fully bifurcating.\nBEAST requires rooted, bifurcating (binary) trees.",
"Illegal user-specified starting tree",
JOptionPane.ERROR_MESSAGE);
userTreeCombo.setSelectedItem(NO_TREE);
partitionTreeModel.setUserStartingTree(null);
}
}
}
public void setupPanel() {
removeAll();
ClockModelGroup group = null;
if (options.getDataPartitions(partitionTreeModel).size() > 0)
group = options.getDataPartitions(partitionTreeModel).get(0).getPartitionClockModel().getClockModelGroup();
if (group != null && (group.getRateTypeOption() == FixRateType.FIX_MEAN
|| group.getRateTypeOption() == FixRateType.RELATIVE_TO)) {
addComponentWithLabel("The estimated initial root height:", initRootHeightField);
}
if (options.isEBSPSharingSamePrior() || options.useStarBEAST) {
addComponentWithLabel("Ploidy type:", ploidyTypeCombo);
}
if (partitionTreeModel.getDataType().getType() != DataType.MICRO_SAT) {
addSpanningComponent(randomTreeRadio);
addSpanningComponent(upgmaTreeRadio);
addSpanningComponent(userTreeRadio);
addComponents(userTreeLabel, userTreeCombo);
userTreeCombo.removeAllItems();
if (options.userTrees.size() < 1) {
userTreeCombo.addItem(NO_TREE);
} else {
Object selectedItem = userTreeCombo.getSelectedItem();
for (Tree tree : options.userTrees) {
userTreeCombo.addItem(tree.getId());
}
if (selectedItem != null) {
userTreeCombo.setSelectedItem(selectedItem);
} else {
userTreeCombo.setSelectedIndex(0);
}
}
// addComponent(treeDisplayButton); // todo JTreeDisplay not work properly
addComponents(treeFormatLabel, treeFormatCombo);
addComponent(userTreeInfo);
}
// generateTreeAction.setEnabled(options != null && options.dataPartitions.size() > 0);
setOptions();
validate();
repaint();
}
public void setOptions() {
if (partitionTreeModel == null) {
return;
}
// setupPanel();
settingOptions = true;
initRootHeightField.setValue(partitionTreeModel.getInitialRootHeight());
// if (options.isEBSPSharingSamePrior() || options.useStarBEAST) {
// ploidyTypeCombo.setSelectedItem(partitionTreeModel.getPloidyType());
// startingTreeCombo.setSelectedItem(partitionTreeModel.getStartingTreeType());
// if (partitionTreeModel.getUserStartingTree() == null) {
// userTreeCombo.setSelectedItem(NO_TREE);
// } else {
// userTreeCombo.setSelectedItem(partitionTreeModel.getUserStartingTree().getId());
userTreeRadio.setEnabled(options.userTrees.size() > 0);
settingOptions = false;
}
public void getOptions(BeautiOptions options) {
if (settingOptions) return;
// all moved to event
// if (options.isEBSPSharingSamePrior() || options.starBEASTOptions.isSpeciesAnalysis()) {
// partitionTreeModel.setPloidyType( (PloidyType) ploidyTypeCombo.getSelectedItem());
// partitionTreeModel.setStartingTreeType( (StartingTreeType) startingTreeCombo.getSelectedItem());
// partitionTreeModel.setUserStartingTree(getSelectedUserTree(options));
}
public boolean isBifurcatingTree(Tree tree, NodeRef node) {
if (tree.getChildCount(node) > 2) return false;
for (int i = 0; i < tree.getChildCount(node); i++) {
if (!isBifurcatingTree(tree, tree.getChild(node, i))) return false;
}
return true;
}
private Tree getSelectedUserTree() {
String treeId = (String) userTreeCombo.getSelectedItem();
for (Tree tree : options.userTrees) {
if (tree.getId().equals(treeId)) {
return tree;
}
}
return null;
}
} |
package ${package}.${service1Name}.impl;
import akka.cluster.sharding.typed.javadsl.EntityContext;
import akka.cluster.sharding.typed.javadsl.EntityTypeKey;
import akka.persistence.typed.PersistenceId;
import akka.persistence.typed.javadsl.*;
import com.lightbend.lagom.javadsl.persistence.AkkaTaggerAdapter;
import ${package}.${service1Name}.impl.${service1ClassName}Command.Hello;
import ${package}.${service1Name}.impl.${service1ClassName}Command.UseGreetingMessage;
import ${package}.${service1Name}.impl.${service1ClassName}Event.GreetingMessageChanged;
import java.util.Set;
/**
* This is an event sourced aggregate. It has a state, {@link ${service1ClassName}State}, which
* stores what the greeting should be (eg, "Hello").
* <p>
* Event sourced aggregate are interacted with by sending them commands. This
* aggregate supports two commands, a {@link UseGreetingMessage} command, which is
* used to change the greeting, and a {@link Hello} command, which is a read
* only command which returns a greeting to the name specified by the command.
* <p>
* Commands may emit events, and it's the events that get persisted.
* Each event will have an event handler registered for it, and an
* event handler simply applies an event to the current state. This will be done
* when the event is first created, and it will also be done when the entity is
* loaded from the database - each event will be replayed to recreate the state
* of the aggregate.
* <p>
* This aggregate defines one event, the {@link GreetingMessageChanged} event,
* which is emitted when a {@link UseGreetingMessage} command is received.
*/
public class ${service1ClassName}Aggregate extends EventSourcedBehaviorWithEnforcedReplies<${service1ClassName}Command, ${service1ClassName}Event, ${service1ClassName}State> {
public static EntityTypeKey<${service1ClassName}Command> ENTITY_TYPE_KEY =
EntityTypeKey
.create(${service1ClassName}Command.class, "${service1ClassName}Aggregate");
final private EntityContext<${service1ClassName}Command> entityContext;
final private String entityId;
${service1ClassName}Aggregate(EntityContext<${service1ClassName}Command> entityContext) {
super(
PersistenceId.of(
entityContext.getEntityTypeKey().name(),
entityContext.getEntityId()
)
);
this.entityContext = entityContext;
this.entityId = entityContext.getEntityId();
}
public static ${service1ClassName}Aggregate create(EntityContext<${service1ClassName}Command> entityContext) {
return new ${service1ClassName}Aggregate(entityContext);
}
@Override
public ${service1ClassName}State emptyState() {
return ${service1ClassName}State.INITIAL;
}
@Override
public CommandHandlerWithReply<${service1ClassName}Command, ${service1ClassName}Event, ${service1ClassName}State> commandHandler() {
CommandHandlerWithReplyBuilder<${service1ClassName}Command, ${service1ClassName}Event, ${service1ClassName}State> builder = newCommandHandlerWithReplyBuilder();
/*
* Command handler for the UseGreetingMessage command.
*/
builder.forAnyState()
.onCommand(UseGreetingMessage.class, (state, cmd) ->
Effect()
// In response to this command, we want to first persist it as a
// GreetingMessageChanged event
.persist(new GreetingMessageChanged(entityId, cmd.message))
// Then once the event is successfully persisted, we respond with done.
.thenReply(cmd.replyTo, __ -> new ${service1ClassName}Command.Accepted())
);
/*
* Command handler for the Hello command.
*/
builder.forAnyState()
.onCommand(Hello.class, (state, cmd) ->
Effect().none()
// Get the greeting from the current state, and prepend it to the name
// that we're sending a greeting to, and reply with that message.
.thenReply(cmd.replyTo, __ -> new ${service1ClassName}Command.Greeting(state.message + ", " + cmd.name + "!"))
);
return builder.build();
}
@Override
public EventHandler<${service1ClassName}State, ${service1ClassName}Event> eventHandler() {
EventHandlerBuilder<${service1ClassName}State, ${service1ClassName}Event> builder = newEventHandlerBuilder();
/*
* Event handler for the GreetingMessageChanged event.
*/
builder.forAnyState()
.onEvent(GreetingMessageChanged.class, (state, evt) ->
// We simply update the current state to use the greeting message from
// the event.
state.withMessage(evt.message)
);
return builder.build();
}
@Override
public Set<String> tagsFor(${service1ClassName}Event shoppingCartEvent) {
return AkkaTaggerAdapter.fromLagom(entityContext, ${service1ClassName}Event.TAG).apply(shoppingCartEvent);
}
} |
package org.eclipse.xtext;
public interface Constants {
public final static String LANGUAGE_NAME = "languageName";
public final static String FILE_EXTENSIONS = "file.extensions";
public final static String WORKFLOW_FILE = "workflow.file";
} |
package jenkins.plugins.git;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.*;
import hudson.plugins.git.GitTool;
import hudson.plugins.git.util.GitUtils;
import org.jenkinsci.plugins.gitclient.GitClient;
import java.io.File;
import java.io.IOException;
import java.util.Map;
public interface GitCredentialBindings {
/**
* Sets secret or public pair value(s)
* @param credentials The credentials {@link com.cloudbees.plugins.credentials.common.StandardCredentials}. Cannot be null
* @param secretValues The values{@link java.util.Map} to be hidden in build logs
* @param publicValues The values{@link java.util.Map} to be visible in build logs
**/
void setCredentialPairBindings(@NonNull StandardCredentials credentials, Map<String,String> secretValues, Map<String,String> publicValues);
/**
* Set Git specific environment variable
* @param git GitClient {@link org.jenkinsci.plugins.gitclient.GitClient}. Cannot be null.
* @param secretValues The values{@link java.util.Map} to be hidden in build logs
* @param publicValues The values{@link java.util.Map} to be visible in build logs
**/
void setGitEnvironmentVariables(@NonNull GitClient git, Map<String,String> secretValues, Map<String,String> publicValues) throws IOException, InterruptedException;
/**
* Performed operations on a git repository. Using Git implementations JGit/JGit Apache/Cli Git
* @param gitExe The path {@link java.lang.String} to git executable {@link org.jenkinsci.plugins.gitclient.Git#using(String)}
* @param repository The path {@link java.lang.String} to working directory {@link org.jenkinsci.plugins.gitclient.Git#in(File)}
* @param env The environment values {@link hudson.EnvVars}
* @param listener The task listener.
* @return a GitClient implementation {@link org.jenkinsci.plugins.gitclient.GitClient}
**/
GitClient getGitClientInstance(String gitExe, FilePath repository,
EnvVars env, TaskListener listener) throws IOException, InterruptedException;
/**
* Checks the OS environment of the node/controller
* @param launcher The launcher.Cannot be null
* @return false if current node/controller is not running in windows environment
**/
default boolean isCurrentNodeOSUnix(@NonNull Launcher launcher){
return launcher.isUnix();
}
/**
* Ensures that the gitTool available is of type cli git/GitTool.class {@link hudson.plugins.git.GitTool}.
* @param run The build {@link hudson.model.Run}. Cannot be null
* @param gitToolName The name of the git tool {@link java.lang.String}
* @param listener The task listener. Cannot be null.
* @return A git tool of type GitTool.class {@link hudson.plugins.git.GitTool} or null
**/
default GitTool getCliGitTool(Run<?, ?> run, String gitToolName,
TaskListener listener) throws IOException, InterruptedException {
Executor buildExecutor = run.getExecutor();
if (buildExecutor != null) {
Node currentNode = buildExecutor.getOwner().getNode();
//Check node is not null
if (currentNode != null) {
GitTool nameSpecificGitTool = GitUtils.resolveGitTool(gitToolName,currentNode,new EnvVars(),listener);
if(nameSpecificGitTool != null) {
GitTool typeSpecificGitTool = nameSpecificGitTool.getDescriptor().getInstallation(gitToolName);
//Check if tool is of type GitTool
if (typeSpecificGitTool != null && typeSpecificGitTool.getClass().equals(GitTool.class)) {
return nameSpecificGitTool;
}
}
}
}
return null;
}
} |
package net.happybrackets.device;
import net.happybrackets.controller.network.DeviceConnection;
import net.happybrackets.core.Device;
import net.happybrackets.core.Synchronizer;
import net.happybrackets.device.network.NetworkCommunication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Manages sending log messages to the controller as they appear in a log file.
* A record is maintained of which log messages have been sent so far.
* Upon starting only new log messages will be sent.
* As new log messages appear they will be sent to the controller (via a separate thread).
*
* See {@link NetworkCommunication#sendLogs(boolean)}.
*/
public class LogSender {
final static Logger logger = LoggerFactory.getLogger(LogSender.class);
private NetworkCommunication networkCommunication;
private File logPath; // path to log file.
private File logPathDir; // path to log file folder.
private volatile boolean send;
private volatile boolean dispose = false;
RandomAccessFile fileReader;
private WatchService watcher; // Service to monitor the file for changes.
private Sender sender;
public LogSender(NetworkCommunication networkCommunication, String logLocation) {
this.networkCommunication = networkCommunication;
send = false;
try {
// Set-up a file change monitor.
watcher = FileSystems.getDefault().newWatchService();
logPath = new File(logLocation);
if (!logPath.exists() || !logPath.isFile()) {
logger.error("An error occurred monitoring the log file " + logPath.getAbsolutePath() + " for changes: it does not exist or is a directory.");
return;
}
fileReader = new RandomAccessFile(logPath, "r");
logPathDir = logPath.getParentFile();
logPathDir.toPath().register(watcher, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
// Set-up the monitor handler/log sender.
sender = new Sender();
sender.start();
logger.info("LogSender initialised for log file " + logPath.getAbsolutePath());
} catch (IOException e) {
System.err.println("Unable to monitor file for changes. Error occurred: " + e.getMessage());
throw new RuntimeException(e);
}
}
/**
* @param send true to start sending log messages to the controller.
*/
public void setSend(boolean send) {
this.send = send;
synchronized (sender) {
sender.notify();
}
}
/**
* Dispose of the thread handling sending of messages.
*/
public void dispose() {
send = false;
dispose = true;
synchronized (sender) {
sender.notify();
}
}
private class Sender extends Thread {
public void run() {
// Flag to indicate if we've sent the existing contents, if any.
boolean sentInitial = false;
while (!dispose) {
while (send) {
// Send initial file contents if we haven't already.
if (!sentInitial) {
sendLatest();
sentInitial = true;
}
try {
WatchKey key = watcher.take();
// For each changed/deleted file in the log file directory (if any).
for (WatchEvent<?> event : key.pollEvents()) {
File modifiedFile = logPathDir.toPath().resolve((Path) event.context()).toFile();
// If the log file has changed.
if (modifiedFile.equals(logPath)) {
if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
logger.info("The log file was deleted.");
return;
} else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
sendLatest();
}
}
}
boolean valid = key.reset();
if (!valid) {
throw new IllegalStateException("The watch service key has become invalid.");
}
}
catch (ClosedWatchServiceException cwse) {
// This is expected if the watch service is closed when terminate() is called.
}
catch (Exception ex) {
logger.error("An error occurred monitoring the log file for changes.", ex);
return;
}
}
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private void sendLatest() {
try {
StringBuilder sb = new StringBuilder();
// Send the new lines in the log file.
String line;
while ((line = fileReader.readLine()) != null) {
sb.append(line).append("\n");
}
networkCommunication.send("/device/log",
new Object[] {
networkCommunication.getID(),
sb.toString()
});
}
catch (Exception ex) {
logger.error("Error sending new log message.", ex);
}
}
}
} |
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
/***
* Main window of the application. Please notice that this window is implementing
* the interface MouseMotionListener
* @author rherlt
*
*
*/
public class MainFrame extends JFrame implements MouseMotionListener, MouseListener{
private static final long serialVersionUID = -979691148534081065L;
private JLabel label;
private int clickCount = 0;
/**
* constructor of the window
* @param title which is displayed as window title
*/
public MainFrame(String title) {
super(title);
//add a listener for mouse motions. Use this class as
//listener which is called by the framework when a mouse
//motion is detected
this.addMouseMotionListener(this);
this.addMouseListener(this);
label = new JLabel("Clicks: 0");
this.getContentPane().add(label);
}
/**
* Override the mouseDragged method of the interface MouseMotionListener.
* This method is called by the framework when the mouse is dragged
*/
@Override
public void mouseDragged(MouseEvent e) {
//get the x and y coordinates of the current mouse position
double xCoord = e.getPoint().getX();
double yCoord = e.getPoint().getY();
//create a text containing the positions and write them to the current frame title
String position = String.format("Mouse dragged: X: %.2f - Y: %.2f ", xCoord, yCoord);
this.setTitle(position);
}
/**
* Override the mouseMoved method of the interface MouseMotionListener.
* This method is called by the framework when the mouse is moved
*/
@Override
public void mouseMoved(MouseEvent args) {
//get the x and y coordinates of the current mouse position
double xCoord = args.getPoint().getX();
double yCoord = args.getPoint().getY();
//create a text containing the positions and write them to the current frame title
String position = String.format("X: %.2f - Y: %.2f ", xCoord, yCoord);
this.setTitle(position);
}
/**
* Override the mouseClicked method of the interface MouseListener.
* This method is called by the framework when the mouse is clicked
*/
@Override
public void mouseClicked(MouseEvent e) {
clickCount++;
String text = String.format("Clicks: %d", clickCount);
label.setText(text);
}
/**
* Override the mousePressed method of the interface MouseListener.
* This method is called by the framework when the mouse button is pressed
*/
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
/**
* Override the mouseReleased method of the interface MouseListener.
* This method is called by the framework when the mouse button is released
*/
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
/**
* Override the mouseEntered method of the interface MouseListener.
* This method is called by the framework when the mouse entered this component
*/
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
/**
* Override the mouseExited method of the interface MouseListener.
* This method is called by the framework when the mouse exited this component
*/
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
} |
package jfdi.logic.commands;
import java.time.Duration;
import java.time.LocalDateTime;
import jfdi.logic.events.RescheduleTaskDoneEvent;
import jfdi.logic.events.RescheduleTaskFailedEvent;
import jfdi.logic.interfaces.Command;
import jfdi.storage.apis.TaskAttributes;
import jfdi.storage.apis.TaskDb;
import jfdi.storage.exceptions.DuplicateTaskException;
import jfdi.storage.exceptions.InvalidIdException;
import jfdi.storage.exceptions.InvalidTaskParametersException;
import jfdi.storage.exceptions.NoAttributesChangedException;
import jfdi.ui.UI;
/**
* @author Liu Xinan
*/
public class RescheduleTaskCommand extends Command {
private int screenId;
private boolean isShiftedDateSpecified;
private boolean isShiftedTimeSpecified;
private LocalDateTime shiftedDateTime;
private LocalDateTime startDateTime;
private LocalDateTime endDateTime;
private LocalDateTime oldStartDateTime;
private LocalDateTime oldEndDateTime;
private RescheduleTaskCommand(Builder builder) {
this.screenId = builder.screenId;
this.isShiftedDateSpecified = builder.isShiftedDateSpecified;
this.isShiftedTimeSpecified = builder.isShiftedTimeSpecified;
this.shiftedDateTime = builder.shiftedDateTime;
this.startDateTime = builder.startDateTime;
this.endDateTime = builder.endDateTime;
}
public static class Builder {
int screenId;
boolean isShiftedDateSpecified;
boolean isShiftedTimeSpecified;
LocalDateTime shiftedDateTime;
LocalDateTime startDateTime;
LocalDateTime endDateTime;
public Builder setId(int screenId) {
this.screenId = screenId;
return this;
}
public void setShiftedDateSpecified(boolean isShiftedDateSpecified) {
this.isShiftedDateSpecified = isShiftedDateSpecified;
}
public void setShiftedTimeSpecified(boolean isShiftedTimeSpecified) {
this.isShiftedTimeSpecified = isShiftedTimeSpecified;
}
public Builder setShiftedDateTime(LocalDateTime shiftedDateTime) {
this.shiftedDateTime = shiftedDateTime;
return this;
}
public Builder setStartDateTime(LocalDateTime startDateTime) {
this.startDateTime = startDateTime;
return this;
}
public Builder setEndDateTime(LocalDateTime endDateTime) {
this.endDateTime = endDateTime;
return this;
}
public RescheduleTaskCommand build() {
return new RescheduleTaskCommand(this);
}
}
@Override
public void execute() {
int taskId = UI.getInstance().getTaskId(screenId);
try {
TaskAttributes task = TaskDb.getInstance().getById(taskId);
oldStartDateTime = task.getStartDateTime();
oldEndDateTime = task.getEndDateTime();
if (shiftedDateTime != null) {
shiftStartAndEndDateTimes(task);
}
task.setStartDateTime(startDateTime);
task.setEndDateTime(endDateTime);
task.save();
pushToUndoStack();
eventBus.post(new RescheduleTaskDoneEvent(task));
} catch (InvalidIdException e) {
eventBus.post(new RescheduleTaskFailedEvent(screenId,
startDateTime, endDateTime,
RescheduleTaskFailedEvent.Error.NON_EXISTENT_ID));
} catch (InvalidTaskParametersException e) {
// Should not happen
assert false;
} catch (NoAttributesChangedException e) {
eventBus.post(new RescheduleTaskFailedEvent(screenId,
startDateTime, endDateTime,
RescheduleTaskFailedEvent.Error.NO_CHANGES));
} catch (DuplicateTaskException e) {
eventBus.post(new RescheduleTaskFailedEvent(screenId,
startDateTime, endDateTime,
RescheduleTaskFailedEvent.Error.DUPLICATED_TASK));
}
}
@Override
public void undo() {
int taskId = UI.getInstance().getTaskId(screenId);
try {
TaskAttributes task = TaskDb.getInstance().getById(taskId);
task.setStartDateTime(oldStartDateTime);
task.setEndDateTime(oldEndDateTime);
task.save();
pushToRedoStack();
} catch (InvalidIdException | InvalidTaskParametersException
| NoAttributesChangedException | DuplicateTaskException e) {
assert false;
}
}
private void shiftStartAndEndDateTimes(TaskAttributes task) {
assert shiftedDateTime != null;
assert isShiftedDateSpecified || isShiftedTimeSpecified;
LocalDateTime taskStart = task.getStartDateTime();
LocalDateTime taskEnd = task.getEndDateTime();
// Set floating task to point task
if (taskStart == null && taskEnd == null) {
startDateTime = shiftedDateTime;
endDateTime = null;
// Shift point task
} else if (taskStart != null && taskEnd == null) {
startDateTime = getShiftedDateTime(task.getStartDateTime());
endDateTime = null;
// Shift deadline task
} else if (taskStart == null && taskEnd != null) {
startDateTime = null;
endDateTime = getShiftedDateTime(task.getEndDateTime());
// Shift event, preserving duration
} else {
Duration eventDuration = Duration.between(taskStart, taskEnd);
startDateTime = getShiftedDateTime(task.getStartDateTime());
endDateTime = startDateTime.plus(eventDuration);
}
}
private LocalDateTime getShiftedDateTime(LocalDateTime dateTime) {
if (isShiftedDateSpecified && isShiftedTimeSpecified) {
return shiftedDateTime;
} else if (isShiftedDateSpecified && !isShiftedTimeSpecified) {
return shiftDate(dateTime);
} else if (!isShiftedDateSpecified && isShiftedTimeSpecified) {
return shiftTime(dateTime);
}
assert false;
return null;
}
private LocalDateTime shiftTime(LocalDateTime originalDateTime) {
assert originalDateTime != null && shiftedDateTime != null;
return LocalDateTime.of(originalDateTime.toLocalDate(), shiftedDateTime.toLocalTime());
}
private LocalDateTime shiftDate(LocalDateTime originalDateTime) {
assert originalDateTime != null && shiftedDateTime != null;
return LocalDateTime.of(shiftedDateTime.toLocalDate(), originalDateTime.toLocalTime());
}
} |
package edu.mit.streamjit.impl.compiler2;
import java.lang.invoke.MethodHandle;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
/**
* An actual buffer or other storage element. (Contrast with Storage, which is
* an IR-level object.)
*
* This class provides two sets of functions: one that performs an operation
* directly, and one that provides a MethodHandle that performs the operation
* when called. Depending on the implementation, one set of operations may be
* implemented in terms of the other. The direct methods are used primarily
* during initialization and draining, while the indirect methods provide
* MethodHandles for generated code. Note that there is no indirect form of
* {@link #sync()}.
*
* Indices used with ConcreteStorage methods have already been translated
* through index functions ("physical indices"). Readers and writers use the
* same indices; that is, writers must use offsets to avoid writing at indices
* that will be read by readers. The {@link #adjust()} method shifts indices
* towards negative infinity to prepare for the next steady state iteration.
* (Physical indices may be further adjusted by implementations to account for
* e.g. circular buffers, but such details are not visible to users of this
* interface.) Note that indices may be negative.
*
* ConcreteStorage implementations used for external Storage must permit
* multiple concurrent readers and writers (e.g., not throwing
* {@link ConcurrentModificationException}). Implementations are guaranteed
* that indices will be written at most once between calls to adjust() and that
* indices written will not be read until the next call to sync() or adjust().
* Further, implementations may assume that calls to sync() and adjust() are
* synchronized externally with calls to read or write (i.e., there is a
* global barrier at the end of each steady-state iteration). Thus
* implementations may not need any synchronization of their own. (For example,
* an implementation using an array will not require synchronization, but a
* Map<Integer, Object>-based implementation must use {@link ConcurrentHashMap}
* rather than a plain {@link HashMap} to avoid throwing
* ConcurrentModificationException.)
*
* ConcreteStorage implementations used for internal Storage objects or during
* the initialization schedule are used only within a single thread, so they
* need not worry about synchronization; normal happens-before ordering in a
* single thread is enough to ensure readers see preceding writes.
* @author Jeffrey Bosboom <jeffreybosboom@gmail.com>
* @since 10/10/2013
*/
public interface ConcreteStorage {
/**
* Returns the type of elements stored in this ConcreteStorage.
* @return the type of elements stored in this ConcreteStorage
*/
public Class<?> type();
/**
* Returns the element at the given index, boxed if necessary.
* @param index the index to read
* @return the element at the given index
*/
public Object read(int index);
/**
* Writes the given element at the given index, unboxing if necessary.
* @param index the index to write
* @param data the element to write
*/
public void write(int index, Object data);
/**
* Shifts indices toward negative infinity and ensures that subsequent calls
* to read will see items written by previous calls to write. (These are
* the end-of-steady-state adjustments.)
*/
public void adjust();
/**
* Ensures that subsequent calls to read will see items written by previous
* calls to write, but does not adjust indices. Despite the name, this
* method need not perform any synchronization actions unless required by
* the implementation.
*/
public void sync();
/**
* Returns a MethodHandle of int -> T type, where T is the type of elements
* stored in this storage, that maps a physical index to the element stored
* at that index.
* @return a handle that reads from this storage
*/
public MethodHandle readHandle();
/**
* Returns a MethodHandle of int, T -> void type, where T is the type of
* elements stored in this storage, that stores an element at the given
* physical index.
* @return a handle that writes to this storage
*/
public MethodHandle writeHandle();
/**
* Returns a MethodHandle of void -> void type that shifts indices toward
* negative infinity and ensures that subsequent calls to read will see
* items written by previous calls to write.
* @return a handle that adjusts this storage
*/
public MethodHandle adjustHandle();
} |
package de.ecspride.pep;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.ArrayType;
import soot.Body;
import soot.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.DoubleType;
import soot.FloatType;
import soot.IdentityUnit;
import soot.IntType;
import soot.Local;
import soot.LongType;
import soot.PrimType;
import soot.RefType;
import soot.Scene;
import soot.ShortType;
import soot.SootClass;
import soot.SootMethod;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.javaToJimple.LocalGenerator;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.DefinitionStmt;
import soot.jimple.IdentityStmt;
import soot.jimple.IfStmt;
import soot.jimple.IntConstant;
import soot.jimple.InterfaceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.Jimple;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.NopStmt;
import soot.jimple.NullConstant;
import soot.jimple.ParameterRef;
import soot.jimple.SpecialInvokeExpr;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.infoflow.android.data.AndroidMethod;
import soot.jimple.infoflow.android.data.AndroidMethod.CATEGORY;
import soot.jimple.infoflow.android.source.data.SourceSinkDefinition;
import soot.jimple.infoflow.entryPointCreators.AndroidEntryPointCreator;
import soot.jimple.infoflow.handlers.ResultsAvailableHandler;
import soot.jimple.infoflow.results.InfoflowResults;
import soot.jimple.infoflow.results.ResultSinkInfo;
import soot.jimple.infoflow.results.ResultSourceInfo;
import soot.jimple.infoflow.solver.cfg.IInfoflowCFG;
import soot.jimple.toolkits.ide.icfg.BiDiInterproceduralCFG;
import soot.util.MultiMap;
import de.ecspride.Main;
import de.ecspride.Settings;
import de.ecspride.events.EventInformation;
import de.ecspride.events.Pair;
import de.ecspride.instrumentation.Instrumentation;
import de.ecspride.util.UpdateManifestAndCodeForWaitPDP;
import de.ecspride.util.Util;
/**
* Responsible for instrumenting statements which will trigger the PDP and waits for a
* response from it. The response could be either: statement execution is allowed or
* statement execution is not allowed.
* @author Siegfried Rasthofer
*/
public class PolicyEnforcementPoint implements ResultsAvailableHandler{
private static Logger log = LoggerFactory.getLogger(PolicyEnforcementPoint.class);
/**
* key: method-signature indicating the statement which needs some instrumentation
* value: event-information about the event which will be triggered at the method-signature
*/
private final Map<String, EventInformation> allEventInformation;
private final Set<SourceSinkDefinition> sources;
private final Set<SourceSinkDefinition> sinks;
private final AndroidEntryPointCreator entryPointCreator;
private int sourceSinkConnectionCounter = 0;
private InfoflowResults results = null;
private final String unknownCategory = "UNKNOWN_BUNDLE_DATA";
public PolicyEnforcementPoint(Map<String, EventInformation> eventInformation,
Set<SourceSinkDefinition> sources,
Set<SourceSinkDefinition> sinks,
AndroidEntryPointCreator entryPointCreator){
this.allEventInformation = eventInformation;
this.sources = sources;
this.sinks = sinks;
this.entryPointCreator = entryPointCreator;
}
@Override
public void onResultsAvailable(IInfoflowCFG cfg, InfoflowResults results) {
log.info("FlowDroid has finished. Duration: " + (System.currentTimeMillis() - Main.startTime) +" ms.");
Main.startTime = System.currentTimeMillis();
Settings.instance.setDummyMainToLibraryClass();
this.results = results;
if (log.isDebugEnabled()) {
log.debug("");
log.debug("InfoFlow Results");
MultiMap<ResultSinkInfo, ResultSourceInfo> r = results.getResults();
for (ResultSinkInfo k : r.keySet()) {
log.debug("ResultSinkInfo: "+ k);
for (ResultSourceInfo rsi: r.get(k)) {
log.debug(" source: "+ rsi);
}
}
log.debug("");
}
log.info("Starting bytecode instrumentation.");
log.info("Adding code to initialize PEPs.");
Util.initializePePInAllPossibleClasses(Settings.instance.getApkPath());
log.info("Redirect main activity");
String mainActivityClass = UpdateManifestAndCodeForWaitPDP.redirectMainActivity(Settings.instance.getApkPath());
UpdateManifestAndCodeForWaitPDP.updateWaitPDPActivity(mainActivityClass);
log.info("Adding Policy Enforcement Points (PEPs).");
doAccessControlChecks(cfg);
log.info("Instrumentation is done.");
if (Settings.mustOutputJimple()) {
log.info("
Main.dumpJimple();
log.info("
}
}
/**
* For a concrete method (declared in an application class), find statements
* containing an invoke expression for which the method is one of the method
* in 'allEventInformation' (i.e., getLine1Number(), ...).
*
* @param cfg
*/
private void doAccessControlChecks(BiDiInterproceduralCFG<Unit, SootMethod> cfg){
for(SootClass sc : Scene.v().getApplicationClasses()){
for(SootMethod sm : sc.getMethods()){
if(sm.isConcrete()){
Body body = sm.retrieveActiveBody();
// only instrument application methods (i.e., not methods declared in PEP helper classes
// or in a Java library classes or in an Android classes, ...)
if(isInstrumentationNecessary(sm)){
// important to use snapshotIterator here
Iterator<Unit> i = body.getUnits().snapshotIterator();
log.debug("method: "+ sm);
while(i.hasNext()){
Stmt s = (Stmt) i.next();
if(s.containsInvokeExpr()) {
InvokeExpr invExpr = s.getInvokeExpr();
String methodSignature = invExpr.getMethod().getSignature();
if(allEventInformation.containsKey(methodSignature)){
log.debug("statement "+ s +" matches "+ methodSignature +".");
ResultSinkInfo sink = null;
outer:
for(ResultSinkInfo sinkInfo : results.getResults().keySet()) {
// iterate over all the arguments of the invoke expression
// and check if an argument is a tainted sink. If one is
// set variable 'sink' to the ResultSinkInfo key.
for (Value v : invExpr.getArgs()) {
Value pathValue = sinkInfo.getAccessPath().getPlainValue();
if (v == pathValue) {
sink = sinkInfo;
log.debug("found a sink: "+ pathValue);
break outer;
}
}
}
if(sink != null){
instrumentWithNoDataFlowInformation(methodSignature, s, invExpr, body, s instanceof AssignStmt);
instrumentSourceToSinkConnections(cfg, sink, s instanceof AssignStmt);
} else {
instrumentWithNoDataFlowInformation(methodSignature, s, invExpr, body, s instanceof AssignStmt);
}
}
} // if stmt containts invoke expression
} // loop on statements
}
}
}
}
}
private List<Unit> instrumentIntentAddings(BiDiInterproceduralCFG<Unit, SootMethod> cfg,
Unit unit, InvokeExpr sinkExpr, Set<ResultSourceInfo> sourceInfo){
if(isMethodInterComponentSink(sinkExpr.getMethod())){
SootMethod method = cfg.getMethodOf(unit);
Body body = null;
if(method.hasActiveBody())
body = method.retrieveActiveBody();
else
throw new RuntimeException("No body found!");
Set<String> sourceCategories = getDataIdList(sourceInfo);
final String hashSetType = "java.util.HashSet";
List<Unit> generated = new ArrayList<Unit>();
//HashSet initialization
Local hashSetLocal = generateFreshLocal(body, RefType.v(hashSetType));
NewExpr newExpr = Jimple.v().newNewExpr(RefType.v(hashSetType));
AssignStmt assignStmt = Jimple.v().newAssignStmt(hashSetLocal, newExpr);
generated.add(assignStmt);
//constructor call
SpecialInvokeExpr constructorCall = Jimple.v().newSpecialInvokeExpr(hashSetLocal, Scene.v().getMethod("<java.util.HashSet: void <init>()>").makeRef());
InvokeStmt constructorCallStmt = Jimple.v().newInvokeStmt(constructorCall);
generated.add(constructorCallStmt);
//add categories to HashSet
for(String cat : sourceCategories){
InterfaceInvokeExpr addCall = Jimple.v().newInterfaceInvokeExpr(hashSetLocal, Scene.v().getMethod("<java.util.Set: boolean add(java.lang.Object)>").makeRef(), StringConstant.v(cat));
InvokeStmt addCallStmt = Jimple.v().newInvokeStmt(addCall);
generated.add(addCallStmt);
}
//get Intent
Value intent = sinkExpr.getArg(0);
StaticInvokeExpr sie = Instrumentation.createJimpleStaticInvokeExpr(
Settings.INSTRUMENTATION_HELPER_JAVA,
"addTaintInformationToIntent",
RefType.v("android.content.Intent"),
intent,
RefType.v(hashSetType), hashSetLocal);
InvokeStmt invStmt = Jimple.v().newInvokeStmt(sie);
generated.add(invStmt);
return generated;
}
return Collections.emptyList();
}
/**
*
* @param cfg
* @param sink
* @param assignmentStatement
*/
private void instrumentSourceToSinkConnections(BiDiInterproceduralCFG<Unit, SootMethod> cfg,
ResultSinkInfo sink, boolean assignmentStatement){
sourceSinkConnectionCounter += 1;
// loop through the sinks
for (ResultSinkInfo sinkInfo : results.getResults().keySet()) {
log.debug("compare: "+ sinkInfo);
log.debug(" to: "+ sink);
// if the current sink is the sink at the unit tagged with 'sink'
if(sinkInfo.equals(sink)){
// loop through the sources
for(ResultSourceInfo si : results.getResults().get(sinkInfo)){
Stmt stmt = si.getSource();
SootMethod sm = cfg.getMethodOf(stmt);
Body body = sm.retrieveActiveBody();
// Source instrumentation. The three type categories for the source are:
// - callback
// - ICC source method (i.e., Intent.getExtras())
// - not a callback and not an ICC source method (i.e., getLine1Number())
if (isInterComponentSourceCallback(si, cfg)) {
throw new RuntimeException("Callbacks as sources are not supported right now");
} else if (isInterComponentSourceNoCallback(si, cfg)) {
//only invoke expression are treated here
if (stmt.containsInvokeExpr()) {
//only statements that return a android.os.Bundle are currently supported
if (stmt instanceof DefinitionStmt) {
DefinitionStmt defStmt = (DefinitionStmt)stmt;
Value leftValue = defStmt.getLeftOp();
if (leftValue.getType().equals(RefType.v("android.os.Bundle"))) {
InvokeExpr invExpr = Instrumentation.createJimpleStaticInvokeExpr(
Settings.INSTRUMENTATION_HELPER_JAVA,
"registerNewSourceSinkConnection",
IntType.v(),
IntConstant.v(sourceSinkConnectionCounter),
RefType.v("android.os.Bundle"),
leftValue);
InvokeStmt invStmt = Jimple.v().newInvokeStmt(invExpr);
Unit instrumentationPoint = null;
if (stmt instanceof IdentityStmt) {
instrumentationPoint = getLastIdentityStmt(body);
} else {
instrumentationPoint = stmt;
}
body.getUnits().insertAfter(invStmt, instrumentationPoint);
log.debug("insert a: "+ invStmt);
} else {
System.err.println("We do only support android.os.Bundle right now!");
}
}
}
} else {
String sourceCat = getSourceCategory(si);
if(sourceCat != null){
InvokeExpr invExpr = Instrumentation.createJimpleStaticInvokeExpr(
Settings.INSTRUMENTATION_HELPER_JAVA,
"registerNewSourceSinkConnection",
IntType.v(),
IntConstant.v(sourceSinkConnectionCounter),
RefType.v("java.lang.String"),
StringConstant.v(sourceCat));
InvokeStmt invStmt = Jimple.v().newInvokeStmt(invExpr);
Unit instrumentationPoint = null;
if(stmt instanceof IdentityStmt)
instrumentationPoint = getLastIdentityStmt(body);
else
instrumentationPoint = stmt;
body.getUnits().insertAfter(invStmt, instrumentationPoint);
log.debug("insert b: "+ invStmt);
}
}
// sink instrumentation
if(sink.getSink().containsInvokeExpr()){
Body bodyOfSink = cfg.getMethodOf(sinkInfo.getSink()).getActiveBody();
InvokeExpr invExpr = sink.getSink().getInvokeExpr();
List<Unit> generated = new ArrayList<Unit>();
generated.addAll(instrumentIntentAddings(cfg, stmt, invExpr,
results.getResults().get(sinkInfo)));
EventInformation eventInfo = allEventInformation.get(invExpr.getMethod().getSignature());
generated.addAll(generatePolicyEnforcementPoint(sinkInfo.getSink(), invExpr,
bodyOfSink, sourceSinkConnectionCounter, assignmentStatement));
log.debug("body with data flow:\n"+body);
for (Unit u: generated) {
log.debug("gen: "+ u);
}
if(eventInfo.isInstrumentAfterStatement())
bodyOfSink.getUnits().insertAfter(generated, sinkInfo.getSink());
else
bodyOfSink.getUnits().insertBefore(generated, sinkInfo.getSink());
}
else
throw new RuntimeException("Double-Check the assumption");
} // loop through the sources
} // if the sink at the unit is the current sink
} // loop through the sinks
}
/**
* Add Policy Enforcement Point (PEP) for Unit 'unit'.
* @param methodSignature
* @param unit
* @param invExpr
* @param body
* @param assignmentStatement
*/
private void instrumentWithNoDataFlowInformation(String methodSignature, Unit unit, InvokeExpr invExpr, Body body, boolean assignmentStatement){
log.debug("add PEP without dataflow information for unit "+ unit);
EventInformation eventInfo = allEventInformation.get(methodSignature);
List<Unit> generated = generatePolicyEnforcementPoint(unit, invExpr, body, -1, assignmentStatement);
log.debug("body no data flow:\n"+body);
for (Unit u: generated) {
log.debug("gen: "+ u);
}
if(eventInfo.isInstrumentAfterStatement()) {
body.getUnits().insertAfter(generated, unit);
} else {
body.getUnits().insertBefore(generated, unit);
}
}
/**
* Generate Policy Enforcement Point (PEP) for Unit 'unit'.
* @param unit
* @param invExpr
* @param body
* @param dataFlowAvailable
* @param assignmentStatement
* @return
*/
private List<Unit> generatePolicyEnforcementPoint(Unit unit, InvokeExpr invExpr, Body body, int dataFlowAvailable, boolean assignmentStatement){
log.debug("Dataflow available: "+ dataFlowAvailable);
List<Unit> generated = new ArrayList<Unit>(); // store all new units that are generated
String methodSignature = invExpr.getMethod().getSignature();
EventInformation eventInfo = allEventInformation.get(methodSignature);
String eventName = eventInfo.getEventName();
Set<Pair<Integer, String>> allParameterInformation = eventInfo.getParameterInformation();
// This list containts types and parameters that are used to build the
// invoke expression to "isStmtExecutionAllowed':
// java.lang.String "eventName"
// IntType "dataFlowAvailable"
// java.lang.Object[] "parameters"
List<Object> parameterForHelperMethod = new ArrayList<Object>();
// add event name information
Type eventNameType = RefType.v("java.lang.String");
parameterForHelperMethod.add(eventNameType);
StringConstant eventNameConstant = StringConstant.v(eventName);
parameterForHelperMethod.add(eventNameConstant);
// add information about dataflow availability
parameterForHelperMethod.add(IntType.v());
parameterForHelperMethod.add(IntConstant.v(dataFlowAvailable));
// add information about parameters
parameterForHelperMethod.add(getParameterArrayType());
List<Value> paramValues = new ArrayList<Value>();
for(Pair<Integer, String> parameterInfo : allParameterInformation){
paramValues.add(StringConstant.v("param" + parameterInfo.getLeft() + "value"));
paramValues.add(invExpr.getArg(parameterInfo.getLeft()));
}
Pair<Value, List<Unit>> arrayRefAndInstrumentation = generateParameterArray(paramValues, body);
generated.addAll(arrayRefAndInstrumentation.getRight());
parameterForHelperMethod.add(arrayRefAndInstrumentation.getLeft());
// Generate PEP call to the PDP. Store the result send by the PDP to 'resultPDPLocal'
// Pseudo code looks like this:
// resultPDPLocal = isStmtExecutionAllowed(eventName, dataFlowAvailable, parameters);
StaticInvokeExpr sie = Instrumentation.createJimpleStaticInvokeExpr(
Settings.INSTRUMENTATION_HELPER_JAVA,
"isStmtExecutionAllowed",
parameterForHelperMethod.toArray());
Local resultPDPLocal = generateFreshLocal(body, soot.IntType.v());
AssignStmt asssCondition = Jimple.v().newAssignStmt(resultPDPLocal, sie);
generated.add(asssCondition);
if(assignmentStatement){
// If the method call before which the PEP in inserted is an assignment statement of
// the form "resultPDPLocal = originalCallThatIsChecked()", generate a new assignment
// statement that stores a default value to "resultPDPLocal" if the PDP does not
// allow the call of method originalCallThatIsChecked().
// Pseudo-code:
// if(resultPDPLocal == 0) goto dummyLabel:
// result = originalCallThatIsChecked();
// goto dummyLabel2:
// dummyLabel:
// result = dummyValue (i.e., 0 for IntType, false for BooleanType, ...)
// dummyLabel2:
// nop
if(unit instanceof DefinitionStmt){
DefinitionStmt defStmt = (DefinitionStmt)unit;
Value pepCondition = Jimple.v().newEqExpr(resultPDPLocal, IntConstant.v(0));
// insert nop
Unit label2Nop = Jimple.v().newNopStmt();
body.getUnits().insertAfter(label2Nop, unit);
// insert result = dummyValue
Unit dummyStatement = createCorrectDummyAssignment((Local)defStmt.getLeftOp());
body.getUnits().insertAfter(dummyStatement, unit);
log.debug("insert c: "+ dummyStatement);
// insert goto dummyLabel2:
body.getUnits().insertAfter(Jimple.v().newGotoStmt(label2Nop), unit);
IfStmt ifStmt = Jimple.v().newIfStmt(pepCondition, dummyStatement);
generated.add(ifStmt);
} else {
throw new RuntimeException("error: expected DefinitionStmt got "+ unit +" -> "+ unit.getClass());
}
} else {
// If the method call before which the PEP in inserted is a call statement of
// the form "originalCallThatIsChecked()", generate a new nop statement
// to jump to if the PDP does not allow the call of method originalCallThatIsChecked().
// Pseudo-code:
// if(resultPDPLocal == 0) goto nopLabel:
// result = originalCallThatIsChecked();
// nopLabel:
// nop
Value pepCondition = Jimple.v().newEqExpr(resultPDPLocal, IntConstant.v(0));
NopStmt nopStmt = Jimple.v().newNopStmt();
body.getUnits().insertAfter(nopStmt, unit);
log.debug("insert d: "+ nopStmt);
IfStmt ifStmt = Jimple.v().newIfStmt(pepCondition, nopStmt);
generated.add(ifStmt);
}
return generated;
}
/**
*
* @param parameter
* @param body
* @return
*/
private Pair<Value, List<Unit>> generateParameterArray(List<Value> parameter, Body body){
List<Unit> generated = new ArrayList<Unit>();
NewArrayExpr arrayExpr = Jimple.v().newNewArrayExpr(RefType.v("java.lang.Object"), IntConstant.v(parameter.size()));
Value newArrayLocal = generateFreshLocal(body, getParameterArrayType());
Unit newAssignStmt = Jimple.v().newAssignStmt(newArrayLocal, arrayExpr);
generated.add(newAssignStmt);
for(int i = 0; i < parameter.size(); i++){
Value index = IntConstant.v(i);
ArrayRef leftSide = Jimple.v().newArrayRef(newArrayLocal, index);
Value rightSide = generateCorrectObject(body, parameter.get(i), generated);
Unit parameterInArray = Jimple.v().newAssignStmt(leftSide, rightSide);
generated.add(parameterInArray);
}
return new Pair<Value, List<Unit>>(newArrayLocal, generated);
}
private Type getParameterArrayType(){
Type parameterArrayType = RefType.v("java.lang.Object");
Type parameterArray = ArrayType.v(parameterArrayType, 1);
return parameterArray;
}
private Value generateCorrectObject(Body body, Value value, List<Unit> generated){
if(value.getType() instanceof PrimType){
//in case of a primitive type, we use boxing (I know it is not nice, but it works...) in order to use the Object type
if(value.getType() instanceof BooleanType){
Local booleanLocal = generateFreshLocal(body, RefType.v("java.lang.Boolean"));
SootClass sootClass = Scene.v().getSootClass("java.lang.Boolean");
SootMethod valueOfMethod = sootClass.getMethod("java.lang.Boolean valueOf(boolean)");
StaticInvokeExpr staticInvokeExpr = Jimple.v().newStaticInvokeExpr(valueOfMethod.makeRef(), value);
Unit newAssignStmt = Jimple.v().newAssignStmt(booleanLocal, staticInvokeExpr);
generated.add(newAssignStmt);
return booleanLocal;
}
else if(value.getType() instanceof ByteType){
Local byteLocal = generateFreshLocal(body, RefType.v("java.lang.Byte"));
SootClass sootClass = Scene.v().getSootClass("java.lang.Byte");
SootMethod valueOfMethod = sootClass.getMethod("java.lang.Byte valueOf(byte)");
StaticInvokeExpr staticInvokeExpr = Jimple.v().newStaticInvokeExpr(valueOfMethod.makeRef(), value);
Unit newAssignStmt = Jimple.v().newAssignStmt(byteLocal, staticInvokeExpr);
generated.add(newAssignStmt);
return byteLocal;
}
else if(value.getType() instanceof CharType){
Local characterLocal = generateFreshLocal(body, RefType.v("java.lang.Character"));
SootClass sootClass = Scene.v().getSootClass("java.lang.Character");
SootMethod valueOfMethod = sootClass.getMethod("java.lang.Character valueOf(char)");
StaticInvokeExpr staticInvokeExpr = Jimple.v().newStaticInvokeExpr(valueOfMethod.makeRef(), value);
Unit newAssignStmt = Jimple.v().newAssignStmt(characterLocal, staticInvokeExpr);
generated.add(newAssignStmt);
return characterLocal;
}
else if(value.getType() instanceof DoubleType){
Local doubleLocal = generateFreshLocal(body, RefType.v("java.lang.Double"));
SootClass sootClass = Scene.v().getSootClass("java.lang.Double");
SootMethod valueOfMethod = sootClass.getMethod("java.lang.Double valueOf(double)");
StaticInvokeExpr staticInvokeExpr = Jimple.v().newStaticInvokeExpr(valueOfMethod.makeRef(), value);
Unit newAssignStmt = Jimple.v().newAssignStmt(doubleLocal, staticInvokeExpr);
generated.add(newAssignStmt);
return doubleLocal;
}
else if(value.getType() instanceof FloatType){
Local floatLocal = generateFreshLocal(body, RefType.v("java.lang.Float"));
SootClass sootClass = Scene.v().getSootClass("java.lang.Float");
SootMethod valueOfMethod = sootClass.getMethod("java.lang.Float valueOf(float)");
StaticInvokeExpr staticInvokeExpr = Jimple.v().newStaticInvokeExpr(valueOfMethod.makeRef(), value);
Unit newAssignStmt = Jimple.v().newAssignStmt(floatLocal, staticInvokeExpr);
generated.add(newAssignStmt);
return floatLocal;
}
else if(value.getType() instanceof IntType){
Local integerLocal = generateFreshLocal(body, RefType.v("java.lang.Integer"));
SootClass sootClass = Scene.v().getSootClass("java.lang.Integer");
SootMethod valueOfMethod = sootClass.getMethod("java.lang.Integer valueOf(int)");
StaticInvokeExpr staticInvokeExpr = Jimple.v().newStaticInvokeExpr(valueOfMethod.makeRef(), value);
Unit newAssignStmt = Jimple.v().newAssignStmt(integerLocal, staticInvokeExpr);
generated.add(newAssignStmt);
return integerLocal;
}
else if(value.getType() instanceof LongType){
Local longLocal = generateFreshLocal(body, RefType.v("java.lang.Long"));
SootClass sootClass = Scene.v().getSootClass("java.lang.Long");
SootMethod valueOfMethod = sootClass.getMethod("java.lang.Long valueOf(long)");
StaticInvokeExpr staticInvokeExpr = Jimple.v().newStaticInvokeExpr(valueOfMethod.makeRef(), value);
Unit newAssignStmt = Jimple.v().newAssignStmt(longLocal, staticInvokeExpr);
generated.add(newAssignStmt);
return longLocal;
}
else if(value.getType() instanceof ShortType){
Local shortLocal = generateFreshLocal(body, RefType.v("java.lang.Short"));
SootClass sootClass = Scene.v().getSootClass("java.lang.Short");
SootMethod valueOfMethod = sootClass.getMethod("java.lang.Short valueOf(short)");
StaticInvokeExpr staticInvokeExpr = Jimple.v().newStaticInvokeExpr(valueOfMethod.makeRef(), value);
Unit newAssignStmt = Jimple.v().newAssignStmt(shortLocal, staticInvokeExpr);
generated.add(newAssignStmt);
return shortLocal;
}
else
throw new RuntimeException("Ooops, something went all wonky!");
}
else
//just return the value, there is nothing to box
return value;
}
private Local generateFreshLocal(Body b, Type type){
LocalGenerator lg = new LocalGenerator(b);
return lg.generateLocal(type);
}
private boolean isInstrumentationNecessary(SootMethod method){
if (method.getDeclaringClass().isJavaLibraryClass())
return false;
if (method.getDeclaringClass().toString().startsWith("android."))
return false;
for (String cn: Settings.class2AddList) {
if (method.getDeclaringClass().toString().startsWith(cn))
return false;
}
return true;
}
/**
* This method iterates over all sources from the FlowDroid-results and extracts the
* category of the specific source. If there is no category found, it will return an empty set,
* otherwise the correct categories will be added.
* @param sourcesInfo: all possible sources from which we try to identify the category
* @return: set of categories for specific sink
*/
private Set<String> getDataIdList(Set<ResultSourceInfo> sourcesInfo){
Set<String> dataIdList = new HashSet<String>();
for(ResultSourceInfo sInfo : sourcesInfo){
if(sInfo.getSource().containsInvokeExpr()){
InvokeExpr invExpr = sInfo.getSource().getInvokeExpr();
for(SourceSinkDefinition meth : sources) {
AndroidMethod am = (AndroidMethod) meth.getMethod();
if(am.getSignature().equals(invExpr.getMethod().getSignature())) {
dataIdList.add(am.getCategory().toString());
}
}
}
else if (isSourceInfoParameter(sInfo)){
dataIdList.add(unknownCategory);
}
else
throw new RuntimeException("Currently not supported");
}
return dataIdList;
}
private boolean isSourceInfoParameter(ResultSourceInfo sInfo) {
return sInfo.getSource() instanceof IdentityStmt
&& ((IdentityStmt) sInfo.getSource()).getRightOp() instanceof ParameterRef;
}
private String getSourceCategory(ResultSourceInfo sourceInfo){
if(sourceInfo.getSource().containsInvokeExpr()){
InvokeExpr invExpr = sourceInfo.getSource().getInvokeExpr();
for(SourceSinkDefinition meth : sources) {
AndroidMethod am = (AndroidMethod) meth.getMethod();
if(am.getSignature().equals(invExpr.getMethod().getSignature())){
return am.getCategory().toString();
}
}
}
else if(isSourceInfoParameter(sourceInfo)){
return unknownCategory;
}
else
throw new RuntimeException("Currently not supported");
return null;
}
private boolean isMethodInterComponentSink(SootMethod sm) {
for (SourceSinkDefinition meth : sinks) {
AndroidMethod am = (AndroidMethod) meth.getMethod();
if(am.getCategory() == CATEGORY.INTER_APP_COMMUNICATION){
if(am.getSubSignature().equals(sm.getSubSignature()))
return true;
}
}
return false;
}
/**
* Return true if the method corresponding to the source 'si' is an
* Inter Component Communication source method such as "Intent.getExtras()".
* @param si
* @param cfg
* @return
*/
private boolean isInterComponentSourceNoCallback(ResultSourceInfo si, BiDiInterproceduralCFG<Unit, SootMethod> cfg){
if(!si.getSource().containsInvokeExpr())
return false;
InvokeExpr invExpr = si.getSource().getInvokeExpr();
SootMethod sm = invExpr.getMethod();
for(SourceSinkDefinition meth : sources){
AndroidMethod am = (AndroidMethod) meth.getMethod();
if(am.getCategory() == CATEGORY.INTER_APP_COMMUNICATION){
if(am.getSubSignature().equals(sm.getSubSignature())) {
log.info("source is: "+ am);
return true;
}
}
}
return false;
}
private boolean isInterComponentSourceCallback(ResultSourceInfo si,
BiDiInterproceduralCFG<Unit, SootMethod> cfg){
if(isSourceInfoParameter(si)){
SootMethod sm = cfg.getMethodOf(si.getSource());
if(entryPointCreator.getCallbackFunctions().containsKey(sm.getDeclaringClass())){
if(entryPointCreator.getCallbackFunctions().get(sm.getDeclaringClass()).contains(sm.getSignature()))
return true;
}
}
return false;
}
/**
* Generate a default assignment with 'local' as left-hand-side value.
* @param local
* @return
*/
private Unit createCorrectDummyAssignment(Local local){
Unit dummyAssignemnt = null;
if(local.getType() instanceof PrimType){
if(local.getType() instanceof IntType){
StaticInvokeExpr sie = Instrumentation.createJimpleStaticInvokeExpr(
Settings.SANITIZER, "dummyInteger");
dummyAssignemnt = Jimple.v().newAssignStmt(local, sie);
}
else if(local.getType() instanceof BooleanType){
StaticInvokeExpr sie = Instrumentation.createJimpleStaticInvokeExpr(
Settings.SANITIZER, "dummyBoolean");
dummyAssignemnt = Jimple.v().newAssignStmt(local, sie);
}
else if(local.getType() instanceof ByteType){
StaticInvokeExpr sie = Instrumentation.createJimpleStaticInvokeExpr(
Settings.SANITIZER, "dummyByte");
dummyAssignemnt = Jimple.v().newAssignStmt(local, sie);
}
else if(local.getType() instanceof CharType){
StaticInvokeExpr sie = Instrumentation.createJimpleStaticInvokeExpr(
Settings.SANITIZER, "dummyCharacter");
dummyAssignemnt = Jimple.v().newAssignStmt(local, sie);
}
else if(local.getType() instanceof DoubleType){
StaticInvokeExpr sie = Instrumentation.createJimpleStaticInvokeExpr(
Settings.SANITIZER, "dummyDouble");
dummyAssignemnt = Jimple.v().newAssignStmt(local, sie);
}
else if(local.getType() instanceof FloatType){
StaticInvokeExpr sie = Instrumentation.createJimpleStaticInvokeExpr(
Settings.SANITIZER, "dummyFloat");
dummyAssignemnt = Jimple.v().newAssignStmt(local, sie);
}
else if(local.getType() instanceof LongType){
StaticInvokeExpr sie = Instrumentation.createJimpleStaticInvokeExpr(
Settings.SANITIZER, "dummyLong");
dummyAssignemnt = Jimple.v().newAssignStmt(local, sie);
}
else if(local.getType() instanceof ShortType){
StaticInvokeExpr sie = Instrumentation.createJimpleStaticInvokeExpr(
Settings.SANITIZER, "dummyShort");
dummyAssignemnt = Jimple.v().newAssignStmt(local, sie);
}
else
throw new RuntimeException("Oops, the primitive type is not correct");
}
else{
if(local.getType().equals(RefType.v("java.lang.String")))
dummyAssignemnt = Jimple.v().newAssignStmt(local, StringConstant.v(""));
else
dummyAssignemnt = Jimple.v().newAssignStmt(local, NullConstant.v());
}
return dummyAssignemnt;
}
private Unit getLastIdentityStmt(Body b) {
Unit u = b.getUnits().getFirst();
while (u instanceof IdentityUnit)
u = b.getUnits().getSuccOf(u);
return b.getUnits().getPredOf(u);
}
} |
package org.osiam.client;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseOperation;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.DatabaseTearDown;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.osiam.client.exception.ConflictException;
import org.osiam.client.query.Query;
import org.osiam.client.query.SortOrder;
import org.osiam.client.query.metamodel.User_;
import org.osiam.resources.scim.SCIMSearchResult;
import org.osiam.resources.scim.User;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import java.io.UnsupportedEncodingException;
import java.util.*;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/context.xml")
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
DbUnitTestExecutionListener.class })
@DatabaseTearDown(value = "/database_tear_down.xml", type = DatabaseOperation.DELETE_ALL)
public class SearchUserServiceIT extends AbstractIntegrationTestBase {
private static final int ITEMS_PER_PAGE = 3;
private static final int STARTINDEX_SECOND_PAGE = 4;
private SCIMSearchResult<User> queryResult;
@Test
@DatabaseSetup("/database_seeds/SearchUserServiceIT/user_by_username.xml")
public void search_for_user_by_username_with_query_string_works() {
String userName = "bjensen";
String query = encodeExpected("userName eq \"" + userName + "\"");
SCIMSearchResult<User> result = oConnector.searchUsers("filter=" + query, accessToken);
assertThat(result.getTotalResults(), is(equalTo(1L)));
User transmittedUser = result.getResources().get(0);
assertThat(transmittedUser.getUserName(), is(equalTo(userName)));
}
@Test
@DatabaseSetup("/database_seeds/SearchUserServiceIT/user_by_username.xml")
public void search_for_user_by_nonexistent_username_with_query_string_fails() {
String query = encodeExpected("userName eq \"" + INVALID_STRING + "\"");
SCIMSearchResult<User> result = oConnector.searchUsers("filter=" + query, accessToken);
assertThat(result.getTotalResults(), is(equalTo(0L)));
}
@Test
@DatabaseSetup("/database_seeds/SearchUserServiceIT/user_by_username.xml")
public void search_for_all_users_ordered_by_user_name_with_query_builder_works()
throws UnsupportedEncodingException {
Query.Builder queryBuilder = new Query.Builder(User.class);
queryBuilder.setSortBy(User_.userName).setSortOrder(SortOrder.ASCENDING);
queryResult = oConnector.searchUsers(queryBuilder.build(), accessToken);
ArrayList<String> sortedUserNames = new ArrayList<>();
sortedUserNames.add("bjensen");
sortedUserNames.add("jcambell");
sortedUserNames.add("adavies");
sortedUserNames.add("cmiller");
sortedUserNames.add("dcooper");
sortedUserNames.add("epalmer");
sortedUserNames.add("gparker");
sortedUserNames.add("hsimpson");
sortedUserNames.add("kmorris");
sortedUserNames.add("ewilley");
sortedUserNames.add("marissa");
Collections.sort(sortedUserNames);
assertEquals(sortedUserNames.size(), queryResult.getTotalResults());
int count = 0;
for (User actUser : queryResult.getResources()) {
assertEquals(sortedUserNames.get(count++), actUser.getUserName());
}
}
@Test
@DatabaseSetup("/database_seeds/SearchUserServiceIT/user_by_email.xml")
public void search_for_user_by_emails_value_with_query_string_works() {
String email = "bjensen@example.com";
String query = encodeExpected("emails.value eq \"" + email + "\"");
SCIMSearchResult<User> result = oConnector.searchUsers("filter=" + query, accessToken);
assertThat(result.getTotalResults(), is(equalTo(1L)));
User transmittedUser = result.getResources().get(0);
assertThat(transmittedUser.getEmails().get(0).getValue(), is(equalTo(email)));
}
@Test
@DatabaseSetup("/database_seeds/SearchUserServiceIT/user_by_last_modified.xml")
public void search_for_all_users_ordered_by_last_modified_with_query_builder_works()
throws UnsupportedEncodingException {
Query.Builder queryBuilder = new Query.Builder(User.class);
queryBuilder.setSortBy(User_.Meta.lastModified).setSortOrder(SortOrder.ASCENDING);
SCIMSearchResult<User> result = oConnector.searchUsers(queryBuilder.build(), accessToken);
ArrayList<String> sortedUserNames = new ArrayList<>();
sortedUserNames.add("marissa");
sortedUserNames.add("adavies");
sortedUserNames.add("bjensen");
sortedUserNames.add("cmiller");
sortedUserNames.add("dcooper");
sortedUserNames.add("epalmer");
assertThat(result.getTotalResults(), is(equalTo((long) sortedUserNames.size())));
int count = 0;
for (User currentUser : result.getResources()) {
Assert.assertThat(currentUser.getUserName(), is(equalTo(sortedUserNames.get(count++))));
}
}
@Test
@DatabaseSetup("/database_seeds/SearchUserServiceIT/database_seed.xml")
public void search_for_user_with_multiple_fields() throws UnsupportedEncodingException {
Query.Filter filter = new Query.Filter(User.class, User_.title.equalTo("Dr."))
.and(User_.nickName.equalTo("Barbara")).and(User_.displayName.equalTo("BarbaraJ."));
Query query = new Query.Builder(User.class).setFilter(filter).build();
whenSearchedIsDoneByQuery(query);
assertThatQueryResultContainsOnlyValidUser();
}
@Test
@DatabaseSetup("/database_seeds/SearchUserServiceIT/database_seed.xml")
public void search_for_3_users_by_username_using_and() {
String user01 = "cmiller";
String user02 = "hsimpson";
String user03 = "kmorris";
String searchString = encodeExpected("userName eq \"" + user01 + "\" and userName eq \"" + user02
+ "\" and userName eq \"" + user03 + "\"");
whenSearchIsDoneByString(searchString);
assertThatQueryResultDoesNotContainValidUsers();
}
@Test
@DatabaseSetup("/database_seeds/SearchUserServiceIT/database_seed.xml")
public void search_for_3_users_by_username_using_or() {
String user01 = "cmiller";
String user02 = "hsimpson";
String user03 = "kmorris";
String searchString = encodeExpected("userName eq \"" + user01 + "\" or userName eq \"" + user02 + "\" or userName eq \""
+ user03 + "\"");
whenSearchIsDoneByString(searchString);
assertThatQueryResultContainsUser(user01);
assertThatQueryResultContainsUser(user02);
assertThatQueryResultContainsUser(user03);
}
@Test
@DatabaseSetup("/database_seeds/SearchUserServiceIT/database_seed.xml")
public void search_with_braces() throws Exception {
Query.Filter innerFilter = new Query.Filter(User.class, User_.userName.equalTo("marissa"))
.or(User_.userName.equalTo("hsimpson"));
DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTimeParser();
// DateTimeFormatter dateFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
DateTime date = dateTimeFormatter.parseDateTime("2000-05-23T13:12:45.672Z");
Query.Filter mainFilter = new Query.Filter(User.class, User_.Meta.created.greaterThan(date))
.and(innerFilter);
Query.Builder queryBuilder = new Query.Builder(User.class);
queryBuilder.setFilter(mainFilter);
queryResult = oConnector.searchUsers(queryBuilder.build(), accessToken);
assertEquals(2, queryResult.getTotalResults());
assertThatQueryResultContainsUser("marissa");
assertThatQueryResultContainsUser("hsimpson");
}
@Test
@DatabaseSetup("/database_seeds/SearchUserServiceIT/database_seed.xml")
public void nextPage_scrolls_forward() throws UnsupportedEncodingException {
Query.Builder builder = new Query.Builder(User.class).setCountPerPage(ITEMS_PER_PAGE);
Query query = builder.build().nextPage();
whenSearchedIsDoneByQuery(query);
assertEquals(STARTINDEX_SECOND_PAGE, queryResult.getStartIndex());
}
@Test
@DatabaseSetup("/database_seeds/SearchUserServiceIT/database_seed.xml")
public void prevPage_scrolls_backward() throws UnsupportedEncodingException {
// since OSIAMs default startIndex is wrongly '0' using ITEMS_PER_PAGE works here.
Query.Builder builder = new Query.Builder(User.class).setCountPerPage(ITEMS_PER_PAGE).setStartIndex(
STARTINDEX_SECOND_PAGE);
Query query = builder.build().previousPage();
whenSearchedIsDoneByQuery(query);
assertEquals(1, queryResult.getStartIndex());
}
@Test
@DatabaseSetup("/database_seeds/SearchUserServiceIT/database_seed.xml")
public void get_all_user_if_over_hundert_user_exists() {
create100NewUser();
List<User> allUsers = oConnector.getAllUsers(accessToken);
assertEquals(111, allUsers.size());
}
@Test
@DatabaseSetup("/database_seeds/SearchUserServiceIT/database_seed_groups.xml")
public void searching_for_users_belonging_to_a_specific_group_by_displayname() {
Query.Builder queryBuilder = new Query.Builder(User.class);
queryBuilder.setFilter("groups.display eq \"test_group01\"");
Set<String> expectedUserNames = new HashSet<>(Arrays.asList("bjensen", "jcambell", "adavies"));
queryResult = oConnector.searchUsers(queryBuilder.build(), accessToken);
assertThat(queryResult.getResources().size(), is(equalTo(expectedUserNames.size())));
for (User user : queryResult.getResources()) {
assertThat(expectedUserNames, hasItem(user.getUserName()));
}
}
@Test
@DatabaseSetup("/database_seeds/SearchUserServiceIT/database_seed_groups.xml")
public void searching_for_users_belonging_to_a_specific_group_by_id() {
Query.Builder queryBuilder = new Query.Builder(User.class);
queryBuilder.setFilter("groups eq \"69e1a5dc-89be-4343-976c-b5541af249f4\"");
Set<String> expectedUserNames = new HashSet<>(Arrays.asList("bjensen", "jcambell", "adavies"));
queryResult = oConnector.searchUsers(queryBuilder.build(), accessToken);
assertThat(queryResult.getResources().size(), is(equalTo(expectedUserNames.size())));
for (User user : queryResult.getResources()) {
assertThat(expectedUserNames, hasItem(user.getUserName()));
}
}
@Test(expected = ConflictException.class)
@DatabaseSetup("/database_seeds/SearchUserServiceIT/database_seed.xml")
public void search_for_user_by_Password_with_query_string_fails() {
String query = encodeExpected("password eq \"" + INVALID_STRING + "\"");
oConnector.searchUsers("filter=" + query, accessToken);
fail("Exception should be thrown");
}
private void create100NewUser() {
for (int count = 0; count < 100; count++) {
User user = new User.Builder("user" + count).build();
oConnector.createUser(user, accessToken);
}
}
private void assertThatQueryResultContainsUser(String userName) {
assertTrue(queryResult != null);
for (User actUser : queryResult.getResources()) {
if (actUser.getUserName().equals(userName)) {
return;
}
}
fail("User " + userName + " could not be found.");
}
private void assertThatQueryResultContainsOnlyValidUser() {
assertTrue(queryResult != null);
assertEquals(1, queryResult.getTotalResults());
assertThatQueryResultContainsValidUser();
}
private void assertThatQueryResultDoesNotContainValidUsers() {
assertTrue(queryResult != null);
assertEquals(0, queryResult.getTotalResults());
}
private void whenSearchIsDoneByString(String queryString) {
queryResult = oConnector.searchUsers("filter=" + queryString, accessToken);
}
private void whenSearchedIsDoneByQuery(Query query) {
queryResult = oConnector.searchUsers(query, accessToken);
}
private void assertThatQueryResultContainsValidUser() {
assertTrue(queryResult != null);
for (User actUser : queryResult.getResources()) {
if (actUser.getId().equals(VALID_USER_ID)) {
return;
}
}
fail("Valid user could not be found.");
}
} |
package lemming.context.inbound;
import lemming.context.Context;
import lemming.data.EntityManagerListener;
import lemming.data.GenericDao;
import org.hibernate.StaleObjectStateException;
import org.hibernate.UnresolvableObjectException;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a Data Access Object providing data operations for inbound contexts.
*/
@SuppressWarnings("unused")
public class InboundContextDao extends GenericDao<InboundContext> implements IInboundContextDao {
/**
* {@inheritDoc}
*/
@Override
public Boolean isTransient(InboundContext context) {
return context.getId() == null;
}
/**
* {@inheritDoc}
*
* @throws RuntimeException
*/
public void persist(InboundContext context) throws RuntimeException {
EntityManager entityManager = EntityManagerListener.createEntityManager();
EntityTransaction transaction = null;
try {
transaction = entityManager.getTransaction();
transaction.begin();
entityManager.persist(context);
transaction.commit();
} catch (RuntimeException e) {
e.printStackTrace();
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
if (e instanceof StaleObjectStateException) {
panicOnSaveLockingError(context, e);
} else if (e instanceof UnresolvableObjectException) {
panicOnSaveUnresolvableObjectError(context, e);
} else {
throw e;
}
} finally {
entityManager.close();
}
}
/**
* {@inheritDoc}
*
* @throws RuntimeException
*/
public void batchPersist(List<InboundContext> contexts) throws RuntimeException {
EntityManager entityManager = EntityManagerListener.createEntityManager();
EntityTransaction transaction = null;
InboundContext currentContext = null;
Integer batchSize = 50;
Integer counter = 0;
try {
transaction = entityManager.getTransaction();
transaction.begin();
for (InboundContext context : contexts) {
currentContext = context;
entityManager.persist(context);
counter++;
if (counter % batchSize == 0) {
entityManager.flush();
entityManager.clear();
}
}
transaction.commit();
} catch (RuntimeException e) {
e.printStackTrace();
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
if (e instanceof StaleObjectStateException) {
panicOnSaveLockingError(currentContext, e);
} else if (e instanceof UnresolvableObjectException) {
panicOnSaveUnresolvableObjectError(currentContext, e);
} else {
throw e;
}
} finally {
entityManager.close();
}
}
/**
* {@inheritDoc}
*
* @throws RuntimeException
*/
public InboundContext merge(InboundContext context) throws RuntimeException {
EntityManager entityManager = EntityManagerListener.createEntityManager();
EntityTransaction transaction = null;
try {
transaction = entityManager.getTransaction();
transaction.begin();
InboundContext mergedContext = entityManager.merge(context);
transaction.commit();
return mergedContext;
} catch (RuntimeException e) {
e.printStackTrace();
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
if (e instanceof StaleObjectStateException) {
panicOnSaveLockingError(context, e);
} else if (e instanceof UnresolvableObjectException) {
panicOnSaveUnresolvableObjectError(context, e);
} else {
throw e;
}
return null;
} finally {
entityManager.close();
}
}
/**
* {@inheritDoc}
*
* @throws RuntimeException
*/
public InboundContext refresh(InboundContext context) throws RuntimeException {
EntityManager entityManager = EntityManagerListener.createEntityManager();
EntityTransaction transaction = null;
try {
transaction = entityManager.getTransaction();
transaction.begin();
if (isTransient(context)) {
throw new IllegalArgumentException();
}
TypedQuery<InboundContext> query = entityManager.createQuery("SELECT i FROM InboundContext i " +
"LEFT JOIN FETCH i.match WHERE i.id = :id", InboundContext.class);
InboundContext refreshedContext = query.setParameter("id", context.getId()).getSingleResult();
transaction.commit();
return refreshedContext;
} catch (RuntimeException e) {
e.printStackTrace();
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
throw e;
} finally {
entityManager.close();
}
}
/**
* Finds the ancestor of an inbound context with the same package and location.
*
* @param entityManager entity manager
* @param context an inbound context
* @return An inbound context or null.
*/
private InboundContext findAncestor(EntityManager entityManager, InboundContext context) {
TypedQuery<InboundContext> query = entityManager.createQuery("SELECT i FROM InboundContext i " +
"LEFT JOIN FETCH i.match WHERE i._package = :package AND i.location = :location " +
"AND i.number < :number ORDER BY i.number DESC", InboundContext.class);
List<InboundContext> ancestors = query.setParameter("package", context.getPackage())
.setParameter("location", context.getLocation()).setParameter("number", context.getNumber())
.setMaxResults(1).getResultList();
return ancestors.isEmpty() ? null : ancestors.get(0);
}
/**
* Finds the successor of an inbound context with the same package and location.
*
* @param entityManager entity manager
* @param context an inbound context
* @return An inbound context or null.
*/
private InboundContext findSuccessor(EntityManager entityManager, InboundContext context) {
TypedQuery<InboundContext> query = entityManager.createQuery("SELECT i FROM InboundContext i " +
"LEFT JOIN FETCH i.match WHERE i._package = :package AND i.location = :location " +
"AND i.number > :number ORDER BY i.number ASC", InboundContext.class);
List<InboundContext> successors = query.setParameter("package", context.getPackage())
.setParameter("location", context.getLocation()).setParameter("number", context.getNumber())
.setMaxResults(1).getResultList();
return successors.isEmpty() ? null : successors.get(0);
}
/**
* Finds a matching context for an inbound context.
*
* @param context an inbound context
* @return A matching context or null.
*/
private Context findMatch(InboundContext context) {
if (context == null) {
return null;
} else {
return context.getMatch();
}
}
/**
* Finds contexts before a successor.
*
* @param entityManager entity manager
* @param successor successor of contexts
* @return A list of contexts.
*/
public List<Context> findBefore(EntityManager entityManager, Context successor) {
if (successor == null) {
throw new IllegalStateException();
}
TypedQuery<Context> query = entityManager.createQuery("SELECT i FROM Context i " +
"WHERE i.location = :location AND i.number < :number ORDER BY i.number ASC", Context.class);
List<Context> contexts = query.setParameter("location", successor.getLocation())
.setParameter("number", successor.getNumber()).getResultList();
return contexts;
}
/**
* Finds contexts after an ancestor.
*
* @param entityManager entity manager
* @param ancestor ancestor of contexts
* @return A list of contexts.
*/
public List<Context> findAfter(EntityManager entityManager, Context ancestor) {
if (ancestor == null) {
throw new IllegalStateException();
}
TypedQuery<Context> query = entityManager.createQuery("SELECT i FROM Context i " +
"WHERE i.location = :location AND i.number > :number ORDER BY i.number ASC", Context.class);
List<Context> contexts = query.setParameter("location", ancestor.getLocation())
.setParameter("number", ancestor.getNumber()).getResultList();
return contexts;
}
/**
* Finds contexts between an ancestor and a successor.
*
* @param entityManager entity manager
* @param ancestor ancestor of contexts
* @param successor successor of contexts
* @return A list of contexts.
*/
private List<Context> findBetween(EntityManager entityManager, Context ancestor, Context successor) {
if (ancestor == null && successor == null) {
throw new IllegalArgumentException();
} else if (ancestor == null) {
return findBefore(entityManager, successor);
} else if (successor == null) {
return findAfter(entityManager, ancestor);
} else {
if (!ancestor.getLocation().equals(successor.getLocation())) {
throw new IllegalArgumentException();
}
if (ancestor.getNumber() >= successor.getNumber()) {
throw new IllegalArgumentException();
}
}
TypedQuery<Context> query = entityManager.createQuery("SELECT i FROM Context i " +
"WHERE i.location = :location AND i.number > :number1 AND i.number < :number2 " +
"ORDER BY i.number ASC", Context.class);
List<Context> contexts = query.setParameter("location", ancestor.getLocation())
.setParameter("number1", ancestor.getNumber()).setParameter("number2", successor.getNumber())
.getResultList();
return contexts;
}
/**
* {@inheritDoc}
*
* @throws RuntimeException
*/
@Override
public List<Context> findPossibleComplements(List<InboundContext> unmatchedContexts) {
InboundContext firstUnmatchedContext = unmatchedContexts.get(0);
InboundContext lastUnmatchedContext = unmatchedContexts.get(unmatchedContexts.size() - 1);
EntityManager entityManager = EntityManagerListener.createEntityManager();
EntityTransaction transaction = null;
try {
transaction = entityManager.getTransaction();
transaction.begin();
InboundContext ancestor = findAncestor(entityManager, firstUnmatchedContext);
InboundContext successor = findSuccessor(entityManager, lastUnmatchedContext);
Context ancestorMatch = findMatch(ancestor);
Context successorMatch = findMatch(successor);
List<Context> complements = new ArrayList<>();
if (ancestorMatch != null || successorMatch != null) {
complements = findBetween(entityManager, ancestorMatch, successorMatch);
}
transaction.commit();
return complements;
} catch (RuntimeException e) {
e.printStackTrace();
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
throw e;
} finally {
entityManager.close();
}
}
} |
package edu.ucsb.cs56.projects.games.minesweeper;
import java.awt.*;
import java.awt.event.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.swing.*;
/** MineGUI.java is a base that calls all GUI objects and handles tasks
such as pausing the game, creating the GUI, making the escape key functional,
and allowing for a new game.
@author David Acevedo
@version 2015/03/04 for lab07, cs56, W15
@see MineGUI
*/
public class MineGUI {
JToolBar toolbar;
JButton mainMenu;
JButton quitMine;
JButton inGameHelp;
JButton refresh;
JButton easyGame;
JButton medGame;
JButton hardGame;
JButton load; //loads game
JButton help; //Main Menu Help Button
//JButton clearPause; //Pause Menu New Game Button
//JButton helpPause; //Pause Menu Help Button
//JButton resume; //Pause Menu Resume Button
JButton save;
JFrame frame; //The frame is where all the good stuff is displayed e.g. Everything
JPanel menu; //Menu Panel, initial panel at initial creation of the game e.g. Main Menu
JPanel game; //Game Panel, where the game is played
//JPanel pause; //Pause Menu JPanel, hopefully we can remove this after toolbar works.
boolean inUse; //if pause menu is started and in use
MineComponent mc; //MineComponent is the actual layout of the game, and what makes the game function
//JLabel status; //the game status label that is displayed during the game
/** no-arg constructor which creates the GUI of the Main Menu for Minesweeper
* This menu includes a start and help button
*/
public MineGUI() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createPausePanel();
createMainMenu();
frame.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
frame.setSize(650, 600);
frame.setVisible(true);
}
/**
* Starts a new Minesweeper game from the main menu
*/
public void newGame() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
game = new JPanel(new BorderLayout()); //our game panel e.g. where everything will be put in for this display
//escapeListener(); //listens for the esc button
//status= new JLabel("Press esc to pause game"); //Our good label
Grid grid = new Grid(true);
//Messager m = new SOMessager();
mc = new MineComponent(grid, this); //creates our game interface
frame.setSize((65*mc.getGrid().getSize() > screenSize.width
? screenSize.width : 65*mc.getGrid().getSize()),
(60*mc.getGrid().getSize() > screenSize.height-40
? screenSize.height-40 : 60*mc.getGrid().getSize()));
game.add(mc); //puts the game in the jPanel
game.add(toolbar,BorderLayout.NORTH); //puts the game toolbar at the top of the screen
menu.setVisible(false); //puts the menu away
//pause.setVisible(false); //puts the pause menu away
frame.getContentPane().add(game);
}
public void newGame(int difficulty) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
game = new JPanel(new BorderLayout()); //our game panel e.g. where everything will be put in for this display
//escapeListener(); //listens for the esc button
//status= new JLabel("Press esc to pause game"); //Our good label
Grid grid = new Grid(true, difficulty);
//Messager m = new SOMessager();
mc = new MineComponent(grid, this); //creates our game interface
frame.setSize((65*mc.getGrid().getSize() > screenSize.width
? screenSize.width : 65*mc.getGrid().getSize()),
(60*mc.getGrid().getSize() > screenSize.height-30
? screenSize.height-30 : 60*mc.getGrid().getSize()));
game.add(mc); //puts the game in the jPanel
game.add(toolbar,BorderLayout.NORTH); //puts the game toolbar label at the top of the screen
menu.setVisible(false); //puts the menu away
//pause.setVisible(false); //puts the pause menu away
frame.getContentPane().add(game);
}
/**
* Pauses the game and brings up the pause menu
*/
// public void pause() {
// frame.setSize(650, 600);
// inUse=true; //the pause menu is now in use
// frame.getContentPane().add(pause); //frame now puts pause in its dear list of importance
// game.setVisible(false); //put the game away for a bit
// pause.setVisible(true); //show the good ol pause menu
/**
* Resumes the game and takes you back to the game
*/
// public void resume() {
// pause.setVisible(false); //put the pause menu back in its box
// game.setVisible(true); //bring the game back out of its box
/**
* creates a Pause menu for when you want to pause the game
*/
// public void createPausePanel(){
// pause = new JPanel(new GridLayout(3,0)); //our 3 section grid layout for our pause menu
// resume = new JButton("Resume"); //create Button
// clearPause = new JButton("Clear Game"); //create Button
// helpPause = new JButton("Help"); //create Button
// load=new JButton("load last game"); //create Button
// save = new JButton("save game"); //create Button
// addActionListener(resume, "Resume"); //Give Button#1 purpose
// addActionListener(clearPause, "Clear Game");//Give Button#2 purpose
// addActionListener(helpPause, "Help"); //Give Button#3 purpose
// addActionListener(load,"Load"); //Give Button#4 purpose
// addActionListener(save, "Save");
// //adds from order of importance e.g. top==more important than bottom
// //pause.add(resume); //Add Button#1 to our top section
// //pause.add(clearPause); //Add Button#2 to our middle section
// //pause.add(helpPause); //Add Button#3 to our bottom section
// //pause.add(load); //Add Button#3 to our bottom section
// //pause.add(save);
// frame.getContentPane().add(pause);
/**
* Creates the main menu, the menu when you launch the application
*/
public void createMainMenu(){
frame.setSize(650, 600);
menu = new JPanel(new GridLayout(4,0)); //our 2 section grid layout for our main menu
easyGame = new JButton("New Easy Game");
medGame = new JButton("New Medium Game");
hardGame = new JButton("New Hard Game");
help = new JButton("Help");
load = new JButton("load last game");
addActionListener(easyGame, "New Easy Game");
addActionListener(medGame, "New Medium Game");
addActionListener(hardGame, "New Hard Game");
addActionListener(help, "Help");
addActionListener(load,"Load");
addActionListener(save, "Save");
menu.add(easyGame);
menu.add(medGame);
menu.add(hardGame);
menu.add(load);
menu.add(help);
//pause.setVisible(false);
frame.getContentPane().add(menu);
}
public void createToolbar(){
JToolBar toolbar = new JToolBar(); //make toolbar
//make buttons
refresh = new JButton("Reset Game");
mainMenu = new JButton("Main Menu");
//quitMine = new JButton("Quit Minesweeper"); //based on principle that we complete toolbar
inGameHelp = = new JButton("Help");
addActionListener(refresh, "Reset Game");
addActionListener(mainMenu, "Main Menu");
addActionListener(inGameHelp, "Help");
toolbar.add(mainMenu);
toolbar.add(refresh);
toolbar.add(inGameHelp);
}
/**
* Allows the escape button to function as a pause key
*/
public void escapeListener() {
AbstractAction escapeAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if(mc.getStatus()==0)
pause();
else{
game.setVisible(false);
createMainMenu();
}
}
};
String key = "ESCAPE";
KeyStroke keyStroke = KeyStroke.getKeyStroke(key);
game.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, key);
game.getActionMap().put(key, escapeAction);
}
/**
* Sets a message on the status bar on the top of the GUI
*
* @param status - message you wish the status bar to display
*/
public void setLabel(String status){
this.status.setText(status);
}
/**
* Creates a specified task for the buttons
* @param button - The JButton that you want to assign a task to
* @param action - the action you would like to give the button
*/
public void addActionListener(JButton button, String action){
if(action == "New Easy Game")
{
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
newGame(0);
}
});
}
else if(action == "New Medium Game")
{
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
newGame(1);
}
});
}
else if(action == "New Hard Game")
{
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
newGame(2);
}
});
}
else if(action == ("Main Menu")
{
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
createMainMenu();
}
});
}
else if(action == ("Reset Game")
{
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
int diff = mc.getGrid().getSize();
if (diff ==10)
{
newGame(0);
}
else if (diff ==15)
{
newGame(1);
}
else if (diff ==20)
{
newGame(2);
}
}
});
}
else if(action == "Help")
{
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
if(inUse==false){
HelpScreen helpScreen=new HelpScreen(frame, menu);
}
else{
HelpScreen helpScreen = new HelpScreen(frame, pause);
}
}
});
}
// else if(action == "Resume"){
// button.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// // Execute when button is pressed
// resume();
else if(action == "Load"){
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
System.out.println("load");
load();
}
});
}
else if(action == "Save"){
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
System.out.println("save");
save();
}
});
}
}
public void load(){
try {
FileInputStream fileStream = new FileInputStream("MyGame.ser");
ObjectInputStream os = new ObjectInputStream(fileStream);
Object one;
try {
one = os.readObject();
Grid grid=(Grid)one;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
game = new JPanel(new BorderLayout()); //our game panel e.g. where everything will be put in for this display
escapeListener(); //listens for the esc button
//status= new JLabel("Press esc to pause game"); //Our good label
//Messager m = new SOMessager();
mc = new MineComponent(grid, this); //creates our game interface
frame.setSize((65*mc.getGrid().getSize() > screenSize.width
? screenSize.width : 65*mc.getGrid().getSize()),
(60*mc.getGrid().getSize() > screenSize.height-30
? screenSize.height-30 : 60*mc.getGrid().getSize()));
game.add(mc); //puts the game in the jPanel
game.add(toolbar,BorderLayout.NORTH); //puts the game toolbar at the top of the screen
menu.setVisible(false); //puts the menu away
pause.setVisible(false); //puts the pause menu away
frame.getContentPane().add(game);
mc.refresh();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void save(){
try{
FileOutputStream fileStream=new FileOutputStream("MyGame.ser");
ObjectOutputStream os = new ObjectOutputStream(fileStream);
os.writeObject(mc.getGrid());
os.close();
}
catch(Exception ex){
ex.printStackTrace();
}
}
public static void main (String[] args) {
MineGUI frame = new MineGUI();
}
} |
package com.intellij.xml.impl.schema;
import com.intellij.codeInsight.daemon.Validator;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiSubstitutor;
import com.intellij.psi.meta.PsiMetaData;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.scope.util.PsiScopesUtil;
import com.intellij.psi.util.CachedValue;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlDocument;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.xml.XmlElementDescriptor;
import com.intellij.xml.XmlNSDescriptor;
import com.intellij.xml.impl.ExternalDocumentValidator;
import com.intellij.xml.util.XmlUtil;
import java.util.*;
/**
* @author Mike
*/
@SuppressWarnings({"HardCodedStringLiteral"})
public class XmlNSDescriptorImpl implements XmlNSDescriptor,Validator {
private static final Set<String> STD_TYPES = new HashSet<String>();
XmlFile myFile;
private String myTargetNamespace;
public XmlNSDescriptorImpl(XmlFile file) {
init(file.getDocument());
}
public XmlNSDescriptorImpl() {
}
public XmlFile getDescriptorFile() {
return myFile;
}
public boolean isHierarhyEnabled() {
return true;
}
public String getDefaultNamespace(){
return myTargetNamespace != null ? myTargetNamespace : "";
}
private final Map<Pair<String, String>, CachedValue<XmlElementDescriptor>> myDescriptorsMap = new HashMap<Pair<String,String>, CachedValue<XmlElementDescriptor>>();
private final Map<Pair<String, XmlTag>, CachedValue<TypeDescriptor>> myTypesMap = new HashMap<Pair<String,XmlTag>, CachedValue<TypeDescriptor>>();
public XmlElementDescriptor getElementDescriptor(String localName, String namespace) {
return getElementDescriptor(localName, namespace, new HashSet<XmlNSDescriptorImpl>(),false);
}
public XmlElementDescriptor getElementDescriptor(String localName, String namespace, Set<XmlNSDescriptorImpl> visited, boolean reference) {
if(visited.contains(this)) return null;
final Pair<String, String> pair = new Pair<String, String>(namespace, localName);
final CachedValue<XmlElementDescriptor> descriptor = myDescriptorsMap.get(pair);
if(descriptor != null) return descriptor.getValue();
XmlDocument document = myFile.getDocument();
XmlTag rootTag = document.getRootTag();
if (rootTag == null) return null;
XmlTag[] tags = rootTag.getSubTags();
visited.add( this );
for (final XmlTag tag : tags) {
if (equalsToSchemaName(tag, "element")) {
String name = tag.getAttributeValue("name");
if (name != null) {
if (checkElementNameEquivalence(localName, namespace, name, tag)) {
final CachedValue<XmlElementDescriptor> cachedValue =
tag.getManager().getCachedValuesManager().createCachedValue(new CachedValueProvider<XmlElementDescriptor>() {
public Result<XmlElementDescriptor> compute() {
final XmlElementDescriptor xmlElementDescriptor = createElementDescriptor(tag);
return new Result<XmlElementDescriptor>(xmlElementDescriptor, xmlElementDescriptor.getDependences());
}
}, false);
myDescriptorsMap.put(pair, cachedValue);
return cachedValue.getValue();
}
}
}
else if (equalsToSchemaName(tag, "include") ||
(reference &&
equalsToSchemaName(tag, "import") &&
namespace.equals(tag.getAttributeValue("namespace"))
)
) {
final XmlAttribute schemaLocation = tag.getAttribute("schemaLocation", tag.getNamespace());
if (schemaLocation != null) {
final XmlFile xmlFile = XmlUtil.findXmlFile(rootTag.getContainingFile(), schemaLocation.getValue());
if (xmlFile != null) {
final XmlDocument includedDocument = xmlFile.getDocument();
if (includedDocument != null) {
final PsiMetaData data = includedDocument.getMetaData();
if (data instanceof XmlNSDescriptorImpl) {
final XmlElementDescriptor elementDescriptor =
((XmlNSDescriptorImpl)data).getElementDescriptor(localName, namespace, visited, reference);
if (elementDescriptor != null) {
final CachedValue<XmlElementDescriptor> value = includedDocument.getManager().getCachedValuesManager()
.createCachedValue(new CachedValueProvider<XmlElementDescriptor>() {
public Result<XmlElementDescriptor> compute() {
return new Result<XmlElementDescriptor>(elementDescriptor, elementDescriptor.getDependences());
}
}, false);
return value.getValue();
}
}
}
}
}
}
}
return null;
}
protected XmlElementDescriptor createElementDescriptor(final XmlTag tag) {
return new XmlElementDescriptorImpl(tag);
}
private boolean checkElementNameEquivalence(String localName, String namespace, String fqn, XmlTag context){
final String localAttrName = XmlUtil.findLocalNameByQualifiedName(fqn);
if (!localAttrName.equals(localName)) return false;
if(myTargetNamespace == null){
final String attrNamespace = context.getNamespaceByPrefix(XmlUtil.findPrefixByQualifiedName(fqn));
if(attrNamespace.equals(namespace))
return true;
}
else return myTargetNamespace.equals(namespace);
return false;
}
public XmlAttributeDescriptorImpl getAttribute(String localName, String namespace) {
return getAttributeImpl(localName, namespace,null);
}
private XmlAttributeDescriptorImpl getAttributeImpl(String localName, String namespace, Set<XmlTag> visited) {
XmlDocument document = myFile.getDocument();
XmlTag rootTag = document.getRootTag();
if (rootTag == null) return null;
XmlNSDescriptorImpl nsDescriptor = (XmlNSDescriptorImpl)rootTag.getNSDescriptor(namespace, true);
if (nsDescriptor != this && nsDescriptor != null) {
return nsDescriptor.getAttribute(
localName,
namespace
);
}
if (visited == null) visited = new HashSet<XmlTag>(1);
else if(visited.contains(rootTag)) return null;
visited.add(rootTag);
XmlTag[] tags = rootTag.getSubTags();
for (XmlTag tag : tags) {
if (equalsToSchemaName(tag, "attribute")) {
String name = tag.getAttributeValue("name");
if (name != null) {
if (checkElementNameEquivalence(localName, namespace, name, tag)) {
return createAttributeDescriptor(tag);
}
}
}
else if (equalsToSchemaName(tag, "include") ||
(equalsToSchemaName(tag, "import") &&
namespace.equals(tag.getAttributeValue("namespace"))
)
) {
final XmlAttribute schemaLocation = tag.getAttribute("schemaLocation", tag.getNamespace());
if (schemaLocation != null) {
final XmlFile xmlFile = XmlUtil.findXmlFile(rootTag.getContainingFile(), schemaLocation.getValue());
if (xmlFile != null) {
final XmlDocument includedDocument = xmlFile.getDocument();
if (includedDocument != null) {
final PsiMetaData data = includedDocument.getMetaData();
if (data instanceof XmlNSDescriptorImpl) {
final XmlAttributeDescriptorImpl attributeDescriptor = ((XmlNSDescriptorImpl)data).getAttributeImpl(localName, namespace,visited);
if (attributeDescriptor != null) {
final CachedValue<XmlAttributeDescriptorImpl> value =
includedDocument.getManager().getCachedValuesManager().createCachedValue(
new CachedValueProvider<XmlAttributeDescriptorImpl>() {
public Result<XmlAttributeDescriptorImpl> compute() {
return new Result<XmlAttributeDescriptorImpl>(attributeDescriptor, attributeDescriptor.getDependences());
}
},
false
);
return value.getValue();
}
}
}
}
}
}
}
return null;
}
protected XmlAttributeDescriptorImpl createAttributeDescriptor(final XmlTag tag) {
return new XmlAttributeDescriptorImpl(tag);
}
protected TypeDescriptor getTypeDescriptor(XmlTag descriptorTag) {
String type = descriptorTag.getAttributeValue("type");
if (type != null) {
return getTypeDescriptor(type, descriptorTag);
}
return findTypeDescriptor(descriptorTag, null);
}
public TypeDescriptor getTypeDescriptor(final String name, XmlTag context) {
if(checkSchemaNamespace(name, context) && STD_TYPES.contains(name)){
return new StdTypeDescriptor(name);
}
final XmlDocument document = myFile.getDocument();
if (document == null) return null;
return findTypeDescriptor(document.getRootTag(), name);
}
public XmlElementDescriptor getDescriptorByType(String qName, XmlTag instanceTag){
final XmlDocument document = myFile.getDocument();
if(document == null) return null;
final XmlTag tag = document.getRootTag();
if(tag == null) return null;
final TypeDescriptor typeDescriptor = findTypeDescriptor(tag, qName);
if(!(typeDescriptor instanceof ComplexTypeDescriptor)) return null;
return new XmlElementDescriptorByType(instanceTag, (ComplexTypeDescriptor)typeDescriptor);
}
private boolean checkSchemaNamespace(String name, XmlTag context){
final String namespace = context.getNamespaceByPrefix(XmlUtil.findPrefixByQualifiedName(name));
if(namespace != null && namespace.length() > 0){
return checkSchemaNamespace(namespace);
}
return "xsd".equals(XmlUtil.findPrefixByQualifiedName(name));
}
private static boolean checkSchemaNamespace(String namespace) {
return XmlUtil.XML_SCHEMA_URI.equals(namespace) ||
XmlUtil.XML_SCHEMA_URI2.equals(namespace) ||
XmlUtil.XML_SCHEMA_URI3.equals(namespace);
}
private static boolean checkSchemaNamespace(XmlTag context){
final String namespace = context.getNamespace();
if(namespace != null && namespace.length() > 0){
return checkSchemaNamespace(namespace);
}
return context.getName().startsWith("xsd:");
}
private static XmlNSDescriptorImpl getNSDescriptorToSearchIn(XmlTag rootTag, final String name, XmlNSDescriptorImpl defaultNSDescriptor) {
if (name == null) return defaultNSDescriptor;
final String namespacePrefix = XmlUtil.findPrefixByQualifiedName(name);
if (namespacePrefix != null && namespacePrefix.length() > 0) {
final String namespace = rootTag.getNamespaceByPrefix(namespacePrefix);
final XmlNSDescriptor nsDescriptor = rootTag.getNSDescriptor(namespace, true);
if (nsDescriptor instanceof XmlNSDescriptorImpl) {
return (XmlNSDescriptorImpl)nsDescriptor;
}
}
return defaultNSDescriptor;
}
protected TypeDescriptor findTypeDescriptor(XmlTag rootTag, final String name) {
return findTypeDescriptorImpl(rootTag, name, null);
}
protected TypeDescriptor findTypeDescriptorImpl(XmlTag rootTag, final String name, Set<XmlTag> visited) {
XmlNSDescriptorImpl nsDescriptor = getNSDescriptorToSearchIn(rootTag, name, this);
if (nsDescriptor != this) {
return nsDescriptor.findTypeDescriptor(
nsDescriptor.getDescriptorFile().getDocument().getRootTag(),
XmlUtil.findLocalNameByQualifiedName(name)
);
}
final Pair<String, XmlTag> pair = new Pair<String, XmlTag>(name, rootTag);
final CachedValue<TypeDescriptor> descriptor = myTypesMap.get(pair);
if(descriptor != null) return descriptor.getValue();
if (rootTag == null) return null;
XmlTag[] tags = rootTag.getSubTags();
if (visited == null) visited = new HashSet<XmlTag>(1);
else if (visited.contains(rootTag)) return null;
visited.add(rootTag);
for (final XmlTag tag : tags) {
if (equalsToSchemaName(tag, "complexType")) {
if (name == null) {
CachedValue<TypeDescriptor> value = createAndPutTypesCachedValue(tag, pair);
return value.getValue();
}
String nameAttribute = tag.getAttributeValue("name");
if (nameAttribute != null) {
if (nameAttribute.equals(name)
|| (name.indexOf(":") >= 0 && nameAttribute.equals(name.substring(name.indexOf(":") + 1)))
) {
CachedValue<TypeDescriptor> cachedValue = createAndPutTypesCachedValue(tag, pair);
return cachedValue.getValue();
}
}
}
else if (equalsToSchemaName(tag, "simpleType")) {
if (name == null) {
CachedValue<TypeDescriptor> value = createAndPutTypesCachedValueSimpleType(tag, pair);
return value.getValue();
}
String nameAttribute = tag.getAttributeValue("name");
if (name.equals(nameAttribute)
|| name.indexOf(":") >= 0 && name.substring(name.indexOf(":") + 1).equals(nameAttribute)
) {
CachedValue<TypeDescriptor> cachedValue = createAndPutTypesCachedValue(tag, pair);
return cachedValue.getValue();
}
}
else if (equalsToSchemaName(tag, "include") ||
(equalsToSchemaName(tag, "import") &&
rootTag.getNamespaceByPrefix(
XmlUtil.findPrefixByQualifiedName(name)
).equals(tag.getAttributeValue("namespace"))
)
) {
final String schemaLocation = tag.getAttributeValue("schemaLocation");
if (schemaLocation != null) {
final XmlFile xmlFile = XmlUtil.findXmlFile(rootTag.getContainingFile(), schemaLocation);
if (xmlFile != null) {
final XmlDocument document = xmlFile.getDocument();
if (document != null) {
final XmlTag rTag = document.getRootTag();
if ("import".equals(tag.getLocalName())) {
final XmlNSDescriptor importedDescriptor = (XmlNSDescriptor)document.getMetaData();
nsDescriptor = (importedDescriptor instanceof XmlNSDescriptorImpl) ?
(XmlNSDescriptorImpl)importedDescriptor :
this;
}
else {
nsDescriptor = this;
}
final Set<XmlTag> visited1 = visited;
final XmlNSDescriptorImpl nsDescriptor1 = nsDescriptor;
final CachedValue<TypeDescriptor> value =
tag.getManager().getCachedValuesManager().createCachedValue(new CachedValueProvider<TypeDescriptor>() {
public Result<TypeDescriptor> compute() {
final TypeDescriptor complexTypeDescriptor =
(nsDescriptor1 != XmlNSDescriptorImpl.this)?
nsDescriptor1.findTypeDescriptor(rTag, name):
nsDescriptor1.findTypeDescriptorImpl(rTag, name,visited1);
return new Result<TypeDescriptor>(complexTypeDescriptor, new Object[]{rTag});
}
}, false
);
if (value.getValue() != null) {
myTypesMap.put(pair, value);
return value.getValue();
}
}
}
}
}
}
return null;
}
private CachedValue<TypeDescriptor> createAndPutTypesCachedValueSimpleType(final XmlTag tag, final Pair<String, XmlTag> pair) {
final CachedValue<TypeDescriptor> value = tag.getManager().getCachedValuesManager().createCachedValue(new CachedValueProvider<TypeDescriptor>() {
public CachedValueProvider.Result<TypeDescriptor> compute() {
final SimpleTypeDescriptor simpleTypeDescriptor = new SimpleTypeDescriptor(tag);
return new Result<TypeDescriptor>(simpleTypeDescriptor, new Object[]{tag});
}
}, false);
myTypesMap.put(pair, value);
return value;
}
private CachedValue<TypeDescriptor> createAndPutTypesCachedValue(final XmlTag tag, final Pair<String, XmlTag> pair) {
final CachedValue<TypeDescriptor> value = tag.getManager().getCachedValuesManager().createCachedValue(new CachedValueProvider<TypeDescriptor>() {
public CachedValueProvider.Result<TypeDescriptor> compute() {
final ComplexTypeDescriptor complexTypeDescriptor = new ComplexTypeDescriptor(XmlNSDescriptorImpl.this, tag);
return new Result<TypeDescriptor>(complexTypeDescriptor, new Object[]{tag});
}
}, false);
myTypesMap.put(pair, value);
return value;
}
public XmlElementDescriptor getElementDescriptor(XmlTag tag) {
PsiElement parent = tag.getParent();
final String namespace = tag.getNamespace();
while(parent instanceof XmlTag && !namespace.equals(((XmlTag)parent).getNamespace()))
parent = parent.getContext();
if (parent instanceof XmlTag) {
final XmlTag parentTag = (XmlTag)parent;
final XmlElementDescriptor parentDescriptor = parentTag.getDescriptor();
if(parentDescriptor != null){
return parentDescriptor.getElementDescriptor(tag);
}
else{
return null;
}
}
else {
XmlElementDescriptor elementDescriptor = getElementDescriptor(tag.getLocalName(), tag.getNamespace());
if (elementDescriptor == null) {
parent = tag.getParent();
if (parent instanceof XmlTag) {
final XmlElementDescriptor descriptor = ((XmlTag)parent).getDescriptor();
if (descriptor != null) elementDescriptor = descriptor.getElementDescriptor(tag);
}
}
return elementDescriptor;
}
}
public XmlElementDescriptor[] getRootElementsDescriptors(final XmlDocument doc) {
final List<XmlElementDescriptor> result = new ArrayList<XmlElementDescriptor>();
collectElements(myFile.getDocument(), result);
return result.toArray(new XmlElementDescriptor[result.size()]);
}
private void collectElements(final XmlDocument document, final List<XmlElementDescriptor> result) {
XmlTag rootTag = document.getRootTag();
if (rootTag == null) return;
XmlTag[] tags = rootTag.getSubTags();
for (XmlTag tag : tags) {
if (equalsToSchemaName(tag, "element")) {
String name = tag.getAttributeValue("name");
if (name != null) {
final XmlElementDescriptor elementDescriptor = getElementDescriptor(name, getDefaultNamespace());
if (elementDescriptor != null) {
result.add(elementDescriptor);
}
}
} else if (equalsToSchemaName(tag, "include")) {
final String schemaLocation = tag.getAttributeValue("schemaLocation");
if (schemaLocation != null) {
final XmlFile xmlFile = XmlUtil.findXmlFile(rootTag.getContainingFile(), schemaLocation);
if (xmlFile != null) {
final XmlDocument includedDocument = xmlFile.getDocument();
if (includedDocument != null) {
collectElements(includedDocument, result);
}
}
}
}
}
}
protected static boolean equalsToSchemaName(XmlTag tag, String schemaName) {
return schemaName.equals(tag.getLocalName()) && checkSchemaNamespace(tag);
}
private static XmlTag findSpecialTag(String name, String specialName, XmlTag rootTag, XmlNSDescriptorImpl descriptor, Set<XmlTag> visited) {
XmlNSDescriptorImpl nsDescriptor = getNSDescriptorToSearchIn(rootTag, name, descriptor);
if (nsDescriptor != descriptor) {
return findSpecialTag(
XmlUtil.findLocalNameByQualifiedName(name),
specialName,
nsDescriptor.getDescriptorFile().getDocument().getRootTag(),
nsDescriptor,
visited
);
}
if (visited == null) visited = new HashSet<XmlTag>(1);
else if (visited.contains(rootTag)) return null;
visited.add(rootTag);
XmlTag[] tags = rootTag.getSubTags();
for (XmlTag tag : tags) {
if (equalsToSchemaName(tag, specialName)) {
String attribute = tag.getAttributeValue("name");
if (name.equals(attribute)
|| name.indexOf(":") >= 0 && name.substring(name.indexOf(":") + 1).equals(attribute)) {
return tag;
}
}
else if (equalsToSchemaName(tag, "include") ||
(equalsToSchemaName(tag, "import") &&
rootTag.getNamespaceByPrefix(
XmlUtil.findPrefixByQualifiedName(name)
).equals(tag.getAttributeValue("namespace"))
)
) {
final String schemaLocation = tag.getAttributeValue("schemaLocation");
if (schemaLocation != null) {
final XmlFile xmlFile = XmlUtil.findXmlFile(rootTag.getContainingFile(), schemaLocation);
if (xmlFile != null) {
final XmlDocument document = xmlFile.getDocument();
if (document != null) {
final XmlTag rTag = findSpecialTag(name, specialName, document.getRootTag(), descriptor, visited);
if (rTag != null) return rTag;
}
}
}
}
}
return null;
}
public XmlTag findGroup(String name) {
return findSpecialTag(name,"group",myFile.getDocument().getRootTag(), this, null);
}
public XmlTag findAttributeGroup(String name) {
return findSpecialTag(name,"attributeGroup",myFile.getDocument().getRootTag(),this, null);
}
private Map<String,List<XmlTag>> mySubstitutions;
public XmlElementDescriptor[] getSubstitutes(String localName, String namespace) {
List<XmlElementDescriptor> result = new ArrayList<XmlElementDescriptor>();
if (mySubstitutions ==null) {
XmlDocument document = myFile.getDocument();
mySubstitutions = new HashMap<String, List<XmlTag>>();
XmlTag rootTag = document.getRootTag();
XmlTag[] tags = rootTag.getSubTags();
for (XmlTag tag : tags) {
if (equalsToSchemaName(tag, "element")) {
final String substAttr = tag.getAttributeValue("substitutionGroup");
if (substAttr != null) {
String substLocalName = XmlUtil.findLocalNameByQualifiedName(substAttr);
List<XmlTag> list = mySubstitutions.get(substLocalName);
if (list == null) {
list = new LinkedList<XmlTag>();
mySubstitutions.put(substLocalName, list);
}
list.add(tag);
}
}
}
}
List<XmlTag> substitutions = mySubstitutions.get(localName);
if (substitutions==null) return XmlElementDescriptor.EMPTY_ARRAY;
for (XmlTag tag : substitutions) {
final String substAttr = tag.getAttributeValue("substitutionGroup");
if (substAttr != null && checkElementNameEquivalence(localName, namespace, substAttr, tag)) {
result.add(createElementDescriptor(tag));
}
}
return result.toArray(new XmlElementDescriptor[result.size()]);
}
public static String getSchemaNamespace(XmlFile file) {
return XmlUtil.findNamespacePrefixByURI(file, "http:
}
public PsiElement getDeclaration(){
return myFile.getDocument();
}
public boolean processDeclarations(PsiElement context, PsiScopeProcessor processor, PsiSubstitutor substitutor, PsiElement lastElement, PsiElement place){
return PsiScopesUtil.walkChildrenScopes(context, processor, substitutor, lastElement, place);
}
public String getName(PsiElement context){
return getName();
}
public String getName(){
return "";
}
public void init(PsiElement element){
myFile = (XmlFile) element.getContainingFile();
final XmlDocument document = myFile.getDocument();
if (document != null) {
final XmlTag rootTag = document.getRootTag();
if (rootTag != null) {
myTargetNamespace = rootTag.getAttributeValue("targetNamespace");
}
}
}
public Object[] getDependences(){
return new Object[]{myFile, };
}
static {
STD_TYPES.add("string");
STD_TYPES.add("normalizedString");
STD_TYPES.add("token");
STD_TYPES.add("byte");
STD_TYPES.add("unsignedByte");
STD_TYPES.add("base64Binary");
STD_TYPES.add("hexBinary");
STD_TYPES.add("integer");
STD_TYPES.add("positiveInteger");
STD_TYPES.add("negativeInteger");
STD_TYPES.add("nonNegativeInteger");
STD_TYPES.add("nonPositiveInteger");
STD_TYPES.add("int");
STD_TYPES.add("unsignedInt");
STD_TYPES.add("long");
STD_TYPES.add("unsignedLong");
STD_TYPES.add("short");
STD_TYPES.add("unsignedShort");
STD_TYPES.add("decimal");
STD_TYPES.add("float");
STD_TYPES.add("double");
STD_TYPES.add("boolean");
STD_TYPES.add("time");
STD_TYPES.add("dateTime");
STD_TYPES.add("duration");
STD_TYPES.add("date");
STD_TYPES.add("gMonth");
STD_TYPES.add("gYear");
STD_TYPES.add("gYearMonth");
STD_TYPES.add("gDay");
STD_TYPES.add("gMonthDay");
STD_TYPES.add("Name");
STD_TYPES.add("QName");
STD_TYPES.add("NCName");
STD_TYPES.add("anyURI");
STD_TYPES.add("language");
STD_TYPES.add("ID");
STD_TYPES.add("IDREF");
STD_TYPES.add("IDREFS");
STD_TYPES.add("ENTITY");
STD_TYPES.add("ENTITIES");
STD_TYPES.add("NOTATION");
STD_TYPES.add("NMTOKEN");
STD_TYPES.add("NMTOKENS");
}
public void validate(PsiElement context, Validator.ValidationHost host) {
ExternalDocumentValidator.doValidation(context,host);
}
protected boolean supportsStdAttributes() {
return true;
}
} |
package servlets;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dto.UserDto;
import dto.Validator;
import enumeration.UserStatus;
import enumeration.UserType;
import service.EditProfileService;
import service.HtmlService;
import service.HeaderService;
import service.InvitedUserService;
import service.LoginService;
import service.UserService;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/forgot")
public class ForgotServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String messageAlert = "";
private String outForm = "";
/**
* @see HttpServlet#HttpServlet()
*/
public ForgotServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
resetGlobals();
if (HeaderService.isTempUser(request)){
RequestDispatcher rd = getServletContext().getRequestDispatcher("/inviteduser");
rd.forward(request, response);
} else if(HeaderService.isAuthenticated(request)) {
// logged in, redirect to main
request.setAttribute("message_alert", messageAlert);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/main");
rd.forward(request, response);
} else {
outForm=drawEmailFieldset(null);
request.setAttribute("message_alert", messageAlert);
request.setAttribute("out_form", outForm);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/forgot.jsp");
rd.forward(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
resetGlobals();
if (HeaderService.isTempUser(request)){
RequestDispatcher rd = getServletContext().getRequestDispatcher("/inviteduser");
rd.forward(request, response);
} else if(HeaderService.isAuthenticated(request)) {
// logged in, redirect to main
request.setAttribute("message_alert", messageAlert);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/main");
rd.forward(request, response);
} else if(request.getParameter("getTemp") != null) {
String email=request.getParameter("username");
Validator v=UserService.selectUserByEmail(request, email);
UserDto u=(UserDto)v.getObject();
if(v.isVerified()) {
if(u.getStatus()!=UserStatus.LOCKED.getCode()){
if(u.getType()==UserType.ELECTORATE.getCode() || u.getType()==UserType.AUTHORITY.getCode()){
EditProfileService.sendTempPassword(request, u).isVerified();
} else if(u.getType()==UserType.INVITED.getCode()){
InvitedUserService.resendInvitation(request, u).isVerified();
}
}
}
outForm=drawEmailSentScreen();
request.setAttribute("message_alert",messageAlert);
request.setAttribute("out_form", outForm);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/forgot.jsp");
rd.forward(request, response);
}
}
public String drawEmailFieldset(UserDto u) {
String out = "";
if(u == null) {
u = new UserDto();
u.setEmail("");
}
out += "<form action=\"forgot\" method=\"post\" data-abide>";
out += "<fieldset>";
out += "<legend>Reset Password</legend>";
out += HtmlService.drawInputTextEmail("username", "Email", "your@email.address", u.getEmail());
out += "<input type=\"submit\" name=\"getTemp\" class=\"small radius button\" value=\"Reset Password\">";
out += "</fieldset>";
out += "</form>";
return out;
}
public String drawEmailSentScreen() {
String out = "<p>We've sent you an email with instructions on how to finish resetting your password.</p>";
return out;
}
private void resetGlobals() {
this.messageAlert = "";
this.outForm = "";
}
} |
package org.scijava.thread;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.scijava.Context;
/**
* Tests the {@link ThreadService}.
*
* @author Johannes Schindelin
*/
public class ThreadServiceTest {
private Context context;
private ThreadService threadService;
@Before
public void setUp() {
context = new Context(ThreadService.class);
threadService = context.getService(ThreadService.class);
}
@After
public void tearDown() {
context.dispose();
}
/** Tests {@link ThreadService#run(Callable)}. */
@Test
public void testRunCallable() throws InterruptedException, ExecutionException
{
final Thread result = threadService.run(new Callable<Thread>() {
@Override
public Thread call() {
return Thread.currentThread();
}
}).get();
assertNotSame(Thread.currentThread(), result);
}
/** Tests {@link ThreadService#run(Runnable)}. */
@Test
public void testRunRunnable() throws InterruptedException, ExecutionException
{
final Thread[] results = new Thread[1];
threadService.run(new Runnable() {
@Override
public void run() {
results[0] = Thread.currentThread();
}
}).get();
assertNotSame(Thread.currentThread(), results[0]);
}
/**
* Tests {@link ThreadService#invoke(Runnable)} and
* {@link ThreadService#isDispatchThread()}.
*/
@Test
public void testInvoke() throws InterruptedException,
InvocationTargetException
{
final boolean[] results = new boolean[1];
threadService.invoke(new Runnable() {
@Override
public void run() {
results[0] = threadService.isDispatchThread();
}
});
assertTrue(results[0]);
assertFalse(threadService.isDispatchThread());
}
/**
* Tests {@link ThreadService#queue(Runnable)} and
* {@link ThreadService#isDispatchThread()}.
*/
@Test
public void testQueue() throws InterruptedException {
final Object sync = new Object();
final boolean[] results = new boolean[1];
synchronized (sync) {
threadService.queue(new Runnable() {
@Override
public void run() {
results[0] = threadService.isDispatchThread();
synchronized (sync) {
sync.notifyAll();
}
}
});
sync.wait();
}
assertTrue(results[0]);
assertFalse(threadService.isDispatchThread());
}
/**
* Tests {@link ThreadService#getParent(Thread)} when called after
* {@link ThreadService#invoke(Runnable)}.
*/
@Test
public void testGetParentInvoke() throws Exception {
final AskForParentR ask = new AskForParentR(threadService);
threadService.invoke(ask);
assertSame(Thread.currentThread(), ask.parent);
}
/**
* Tests {@link ThreadService#getParent(Thread)} when called after
* {@link ThreadService#run(Callable)}.
*/
@Test
public void testGetParentRunCallable() throws Exception {
final AskForParentC ask = new AskForParentC(threadService);
final Thread parent = threadService.run(ask).get();
assertSame(Thread.currentThread(), parent);
}
/**
* Tests {@link ThreadService#getParent(Thread)} when called after
* {@link ThreadService#run(Runnable)}.
*/
@Test
public void testGetParentRunRunnable() throws Exception {
final AskForParentR ask = new AskForParentR(threadService);
threadService.run(ask).get();
assertSame(Thread.currentThread(), ask.parent);
}
private static class AskForParentR implements Runnable {
private final ThreadService threadService;
private Thread parent;
public AskForParentR(final ThreadService threadService) {
this.threadService = threadService;
}
@Override
public void run() {
parent = threadService.getParent(null);
}
}
private static class AskForParentC implements Callable<Thread> {
private final ThreadService threadService;
public AskForParentC(final ThreadService threadService) {
this.threadService = threadService;
}
@Override
public Thread call() {
return threadService.getParent(null);
}
}
} |
package ca.ualberta.lard.test;
import ca.ualberta.lard.NewCommentActivity;
import ca.ualberta.lard.model.GeoLocation;
import android.content.Intent;
import android.test.ActivityInstrumentationTestCase2;
/**
* JUnit tests for NewCommentActivity. Tests that the correct parent id is received. Also
* tests user interaction with the UI (attaching a picture, changing location, inputting
* text for the comment).
*/
public class NewCommentActivityTests extends ActivityInstrumentationTestCase2<NewCommentActivity> {
public NewCommentActivityTests() {
super(NewCommentActivity.class);
}
public void testParentIDExists() {
Intent intent = new Intent();
String value = "Test";
intent.putExtra(NewCommentActivity.PARENT_ID, value);
setActivityIntent(intent);
NewCommentActivity activity = getActivity();
assertEquals("NewCommentActivity should get the value from intent", value, activity.getPid());
}
public void testParentIDNotExists() {
Intent intent = new Intent();
setActivityIntent(intent);
NewCommentActivity activity = getActivity();
assertEquals("NewCommentActivity should get the value from intent", null, activity.getPid());
}
public void testPictureDefault() {
Intent intent = new Intent();
setActivityIntent(intent);
NewCommentActivity activity = getActivity();
assertTrue("NewCommentActivity should by default have no picture", activity.getPicture().isNull());
}
public void testGeoLocationDefault() {
Intent intent = new Intent();
setActivityIntent(intent);
NewCommentActivity activity = getActivity();
GeoLocation loc = new GeoLocation(activity);
assertEquals("NewCommentActivity should by default have a default location", loc.getLatitude(), activity.getGeoLocation().getLatitude());
assertEquals("NewCommentActivity should by default have a default location", loc.getLongitude(), activity.getGeoLocation().getLongitude());
}
} |
package me.dslztx.assist.client.redis;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class RedisClient {
private static final Logger logger = LoggerFactory.getLogger(RedisClient.class);
private Jedis jedis;
private JedisPoolProxy jedisPoolProxy;
public RedisClient(Jedis jedis, JedisPoolProxy jedisPoolProxy) {
this.jedis = jedis;
this.jedisPoolProxy = jedisPoolProxy;
}
public void returnResource() {
try {
if (jedis != null && jedisPoolProxy != null) {
jedisPoolProxy.getPool().returnResource(jedis);
}
} catch (Exception e) {
logger.error("", e);
if (jedis != null && jedisPoolProxy != null) {
jedisPoolProxy.getPool().returnBrokenResource(jedis);
}
} finally {
jedis = null;
jedisPoolProxy = null;
}
}
public Jedis getJedis() {
return jedis;
}
}
class JedisPoolProxy {
private static final Logger logger = LoggerFactory.getLogger(JedisPoolProxy.class);
private static final long BLOCKED_TIME = 10 * 1000;
String server;
JedisPool pool;
AtomicLong blockedTime = new AtomicLong(-1);
public JedisPoolProxy(String server, JedisPool pool) {
this.server = server;
this.pool = pool;
}
public boolean isBlocked() {
if (blockedTime.get() < 0) {
return false;
}
if (System.currentTimeMillis() - blockedTime.get() > BLOCKED_TIME) {
logger.info("server " + server + " recovers");
blockedTime.set(-1);
return false;
}
return true;
}
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public JedisPool getPool() {
return pool;
}
public void setPool(JedisPool pool) {
this.pool = pool;
}
public long getBlockedTime() {
return blockedTime.get();
}
public void setBlockedTime(long blockedTime) {
logger.info("server " + server + " is blocked");
this.blockedTime.set(blockedTime);
}
} |
package org.piwik.sdk;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import org.piwik.sdk.ecommerce.EcommerceItems;
import org.piwik.sdk.tools.ActivityHelper;
import org.piwik.sdk.tools.CurrencyFormatter;
import org.piwik.sdk.tools.Logy;
import java.net.URL;
public class TrackHelper {
private final TrackMe mBaseTrackMe;
private TrackHelper() {
this(null);
}
private TrackHelper(@Nullable TrackMe baseTrackMe) {
if (baseTrackMe == null) baseTrackMe = new TrackMe();
mBaseTrackMe = baseTrackMe;
}
public static TrackHelper track() {
return new TrackHelper();
}
public static TrackHelper track(@NonNull TrackMe base) {
return new TrackHelper(base);
}
static abstract class BaseEvent {
private final TrackHelper mBaseBuilder;
BaseEvent(TrackHelper baseBuilder) {
mBaseBuilder = baseBuilder;
}
TrackMe getBaseTrackMe() {
return mBaseBuilder.mBaseTrackMe;
}
@Nullable
public abstract TrackMe build();
public void with(@NonNull PiwikApplication piwikApplication) {
with(piwikApplication.getTracker());
}
public void with(@NonNull Tracker tracker) {
TrackMe trackMe = build();
if (trackMe != null) tracker.track(trackMe);
}
}
/**
* To track a screenview.
*
* @param path Example: "/user/settings/billing"
* @return an object that allows addition of further details.
*/
public Screen screen(String path) {
return new Screen(this, path);
}
/**
* Calls {@link #screen(String)} for an activity.
* Uses the activity-stack as path and activity title as names.
*
* @param activity the activity to track
*/
public Screen screen(Activity activity) {
String breadcrumbs = ActivityHelper.getBreadcrumbs(activity);
return new Screen(this, ActivityHelper.breadcrumbsToPath(breadcrumbs)).title(breadcrumbs);
}
public static class Screen extends BaseEvent {
private final String mPath;
private final CustomVariables mCustomVariables = new CustomVariables();
private String mTitle;
Screen(TrackHelper baseBuilder, String path) {
super(baseBuilder);
mPath = path;
}
/**
* The title of the action being tracked. It is possible to use slashes / to set one or several categories for this action.
*
* @param title Example: Help / Feedback will create the Action Feedback in the category Help.
* @return this object to allow chaining calls
*/
public Screen title(String title) {
mTitle = title;
return this;
}
/**
* Just like {@link Tracker#setVisitCustomVariable(int, String, String)} but only valid per screen.
* Only takes effect when setting prior to tracking the screen view.
*/
public Screen variable(int index, String name, String value) {
mCustomVariables.put(index, name, value);
return this;
}
@Nullable
@Override
public TrackMe build() {
if (mPath == null) return null;
return new TrackMe(getBaseTrackMe())
.set(QueryParams.SCREEN_SCOPE_CUSTOM_VARIABLES, mCustomVariables.toString())
.set(QueryParams.URL_PATH, mPath)
.set(QueryParams.ACTION_NAME, mTitle);
}
}
public EventBuilder event(@NonNull String category, @NonNull String action) {
return new EventBuilder(this, category, action);
}
public static class EventBuilder extends BaseEvent {
@NonNull private final String mCategory;
@NonNull private final String mAction;
private String mPath;
private String mName;
private Float mValue;
EventBuilder(TrackHelper builder, @NonNull String category, @NonNull String action) {
super(builder);
mCategory = category;
mAction = action;
}
/**
* The path under which this event occurred.
* Example: "/user/settings/billing", if you pass NULL, the last path set by #trackScreenView will be used.
*/
public EventBuilder path(String path) {
mPath = path;
return this;
}
/**
* Defines a label associated with the event.
* For example, if you have multiple Button controls on a screen, you might use the label to specify the specific View control identifier that was clicked.
*/
public EventBuilder name(String name) {
mName = name;
return this;
}
/**
* Defines a numeric value associated with the event.
* For example, if you were tracking "Buy" button clicks, you might log the number of items being purchased, or their total cost.
*/
public EventBuilder value(Float value) {
mValue = value;
return this;
}
@Nullable
@Override
public TrackMe build() {
TrackMe trackMe = new TrackMe(getBaseTrackMe())
.set(QueryParams.URL_PATH, mPath)
.set(QueryParams.EVENT_CATEGORY, mCategory)
.set(QueryParams.EVENT_ACTION, mAction)
.set(QueryParams.EVENT_NAME, mName);
if (mValue != null) trackMe.set(QueryParams.EVENT_VALUE, mValue);
return trackMe;
}
}
/**
* By default, Goals in Piwik are defined as "matching" parts of the screen path or screen title.
* In this case a conversion is logged automatically. In some situations, you may want to trigger
* a conversion manually on other types of actions, for example:
* when a user submits a form
* when a user has stayed more than a given amount of time on the page
* when a user does some interaction in your Android application
*
* @param idGoal id of goal as defined in piwik goal settings
*/
public Goal goal(int idGoal) {
return new Goal(this, idGoal);
}
public static class Goal extends BaseEvent {
private final int mIdGoal;
private Float mRevenue;
Goal(TrackHelper baseBuilder, int idGoal) {
super(baseBuilder);
mIdGoal = idGoal;
}
/**
* Tracking request will trigger a conversion for the goal of the website being tracked with this ID
*
* @param revenue a monetary value that was generated as revenue by this goal conversion.
*/
public Goal revenue(Float revenue) {
mRevenue = revenue;
return this;
}
@Nullable
@Override
public TrackMe build() {
if (mIdGoal < 0) return null;
TrackMe trackMe = new TrackMe(getBaseTrackMe()).set(QueryParams.GOAL_ID, mIdGoal);
if (mRevenue != null) trackMe.set(QueryParams.REVENUE, mRevenue);
return trackMe;
}
}
public Outlink outlink(URL url) {
return new Outlink(this, url);
}
public static class Outlink extends BaseEvent {
private final URL mURL;
Outlink(TrackHelper baseBuilder, URL url) {
super(baseBuilder);
mURL = url;
}
@Nullable
@Override
public TrackMe build() {
if (!mURL.getProtocol().equals("http") && !mURL.getProtocol().equals("https") && !mURL.getProtocol().equals("ftp")) {
return null;
}
return new TrackMe(getBaseTrackMe())
.set(QueryParams.LINK, mURL.toExternalForm())
.set(QueryParams.URL_PATH, mURL.toExternalForm());
}
}
public Download download() {
return new Download(this);
}
public static class Download {
private final TrackHelper mBaseBuilder;
private DownloadTracker.Extra mExtra = DownloadTracker.Extra.NONE;
private boolean mForced = false;
private String mVersion;
Download(TrackHelper baseBuilder) {
mBaseBuilder = baseBuilder;
}
/**
* Sets the identifier type for this download
*
* @param identifier {@link DownloadTracker.Extra#APK_CHECKSUM} or {@link DownloadTracker.Extra#NONE}
* @return this object, to chain calls.
*/
public Download identifier(DownloadTracker.Extra identifier) {
mExtra = identifier;
return this;
}
/**
* Normally a download event is only fired once per app version.
* If the download has already been tracked for this version, nothing happens.
* Calling this will force this download to be tracked.
*
* @return this object, to chain calls.
*/
public Download force() {
mForced = true;
return this;
}
/**
* To track specific app versions. Useful if the app can change without the apk being updated (e.g. hybrid apps/web apps).
*
* @param version by default {@link android.content.pm.PackageInfo#versionCode} is used.
* @return this object, to chain calls.
*/
public Download version(String version) {
mVersion = version;
return this;
}
public void with(Tracker tracker) {
final DownloadTracker downloadTracker = new DownloadTracker(tracker, mBaseBuilder.mBaseTrackMe);
if (mVersion != null) downloadTracker.setVersion(mVersion);
if (mForced) {
downloadTracker.trackNewAppDownload(mExtra);
} else {
downloadTracker.trackOnce(mExtra);
}
}
}
/**
* Tracking the impressions
*
* @param contentName The name of the content. For instance 'Ad Foo Bar'
*/
public ContentImpression impression(@NonNull String contentName) {
return new ContentImpression(this, contentName);
}
public static class ContentImpression extends BaseEvent {
private final String mContentName;
private String mContentPiece;
private String mContentTarget;
ContentImpression(TrackHelper baseBuilder, String contentName) {
super(baseBuilder);
mContentName = contentName;
}
/**
* @param contentPiece The actual content. For instance the path to an image, video, audio, any text
*/
public ContentImpression piece(String contentPiece) {
mContentPiece = contentPiece;
return this;
}
/**
* @param contentTarget The target of the content. For instance the URL of a landing page.
*/
public ContentImpression target(String contentTarget) {
mContentTarget = contentTarget;
return this;
}
@Nullable
@Override
public TrackMe build() {
if (TextUtils.isEmpty(mContentName)) return null;
return new TrackMe(getBaseTrackMe())
.set(QueryParams.CONTENT_NAME, mContentName)
.set(QueryParams.CONTENT_PIECE, mContentPiece)
.set(QueryParams.CONTENT_TARGET, mContentTarget);
}
}
/**
* Tracking the interactions</p>
* To map an interaction to an impression make sure to set the same value for contentName and contentPiece as
* the impression has.
*
* @param contentInteraction The name of the interaction with the content. For instance a 'click'
* @param contentName The name of the content. For instance 'Ad Foo Bar'
*/
public ContentInteraction interaction(@NonNull String contentName, @NonNull String contentInteraction) {
return new ContentInteraction(this, contentName, contentInteraction);
}
public static class ContentInteraction extends BaseEvent {
private final String mContentName;
private final String mInteraction;
private String mContentPiece;
private String mContentTarget;
ContentInteraction(TrackHelper baseBuilder, String contentName, String interaction) {
super(baseBuilder);
mContentName = contentName;
mInteraction = interaction;
}
/**
* @param contentPiece The actual content. For instance the path to an image, video, audio, any text
*/
public ContentInteraction piece(String contentPiece) {
mContentPiece = contentPiece;
return this;
}
/**
* @param contentTarget The target the content leading to when an interaction occurs. For instance the URL of a landing page.
*/
public ContentInteraction target(String contentTarget) {
mContentTarget = contentTarget;
return this;
}
@Nullable
@Override
public TrackMe build() {
if (TextUtils.isEmpty(mContentName) || TextUtils.isEmpty(mInteraction)) return null;
return new TrackMe(getBaseTrackMe())
.set(QueryParams.CONTENT_NAME, mContentName)
.set(QueryParams.CONTENT_PIECE, mContentPiece)
.set(QueryParams.CONTENT_TARGET, mContentTarget)
.set(QueryParams.CONTENT_INTERACTION, mInteraction);
}
}
/**
* Tracks a shopping cart. Call this javascript function every time a user is adding, updating
* or deleting a product from the cart.
*
* @param grandTotal total value of items in cart
*/
public CartUpdate cartUpdate(int grandTotal) {
return new CartUpdate(this, grandTotal);
}
public static class CartUpdate extends BaseEvent {
private final int mGrandTotal;
private EcommerceItems mEcommerceItems;
CartUpdate(TrackHelper baseBuilder, int grandTotal) {
super(baseBuilder);
mGrandTotal = grandTotal;
}
/**
* @param items Items included in the cart
*/
public CartUpdate items(EcommerceItems items) {
mEcommerceItems = items;
return this;
}
@Nullable
@Override
public TrackMe build() {
if (mEcommerceItems == null) mEcommerceItems = new EcommerceItems();
return new TrackMe(getBaseTrackMe())
.set(QueryParams.GOAL_ID, 0)
.set(QueryParams.REVENUE, CurrencyFormatter.priceString(mGrandTotal))
.set(QueryParams.ECOMMERCE_ITEMS, mEcommerceItems.toJson());
}
}
/**
* Tracks an Ecommerce order, including any ecommerce item previously added to the order. All
* monetary values should be passed as an integer number of cents (or the smallest integer unit
* for your currency)
*
* @param orderId (required) A unique string identifying the order
* @param grandTotal (required) total amount of the order, in cents
*/
public Order order(String orderId, int grandTotal) {
return new Order(this, orderId, grandTotal);
}
public static class Order extends BaseEvent {
private final String mOrderId;
private final int mGrandTotal;
private EcommerceItems mEcommerceItems;
private Integer mDiscount;
private Integer mShipping;
private Integer mTax;
private Integer mSubTotal;
Order(TrackHelper baseBuilder, String orderId, int grandTotal) {
super(baseBuilder);
mOrderId = orderId;
mGrandTotal = grandTotal;
}
/**
* @param subTotal the subTotal for the order, in cents
*/
public Order subTotal(Integer subTotal) {
mSubTotal = subTotal;
return this;
}
/**
* @param tax the tax for the order, in cents
*/
public Order tax(Integer tax) {
mTax = tax;
return this;
}
/**
* @param shipping the shipping for the order, in cents
*/
public Order shipping(Integer shipping) {
mShipping = shipping;
return this;
}
/**
* @param discount the discount for the order, in cents
*/
public Order discount(Integer discount) {
mDiscount = discount;
return this;
}
/**
* @param items the items included in the order
*/
public Order items(EcommerceItems items) {
mEcommerceItems = items;
return this;
}
@Nullable
@Override
public TrackMe build() {
if (mEcommerceItems == null) mEcommerceItems = new EcommerceItems();
return new TrackMe(getBaseTrackMe())
.set(QueryParams.GOAL_ID, 0)
.set(QueryParams.ORDER_ID, mOrderId)
.set(QueryParams.REVENUE, CurrencyFormatter.priceString(mGrandTotal))
.set(QueryParams.ECOMMERCE_ITEMS, mEcommerceItems.toJson())
.set(QueryParams.SUBTOTAL, CurrencyFormatter.priceString(mSubTotal))
.set(QueryParams.TAX, CurrencyFormatter.priceString(mTax))
.set(QueryParams.SHIPPING, CurrencyFormatter.priceString(mShipping))
.set(QueryParams.DISCOUNT, CurrencyFormatter.priceString(mDiscount));
}
}
/**
* Caught exceptions are errors in your app for which you've defined exception handling code,
* such as the occasional timeout of a network connection during a request for data.
* <p/>
* This is just a different way to define an event.
* Keep in mind Piwik is not a crash tracker, use this sparingly.
* <p/>
* For this to be useful you should ensure that proguard does not remove all classnames and line numbers.
* Also note that if this is used across different app versions and obfuscation is used, the same exception might be mapped to different obfuscated names by proguard.
* This would mean the same exception (event) is tracked as different events by Piwik.
*
* @param throwable exception instance
*/
public Exception exception(Throwable throwable) {
return new Exception(this, throwable);
}
public static class Exception extends BaseEvent {
private final Throwable mThrowable;
private String mDescription;
private boolean mIsFatal;
Exception(TrackHelper baseBuilder, Throwable throwable) {
super(baseBuilder);
mThrowable = throwable;
}
/**
* @param description exception message
*/
public Exception description(String description) {
mDescription = description;
return this;
}
/**
* @param isFatal true if it's fatal exception
*/
public Exception fatal(boolean isFatal) {
mIsFatal = isFatal;
return this;
}
@Nullable
@Override
public TrackMe build() {
String className;
try {
StackTraceElement trace = mThrowable.getStackTrace()[0];
className = trace.getClassName() + "/" + trace.getMethodName() + ":" + trace.getLineNumber();
} catch (java.lang.Exception e) {
Logy.w(Tracker.LOGGER_TAG, "Couldn't get stack info", e);
className = mThrowable.getClass().getName();
}
String actionName = "exception/" + (mIsFatal ? "fatal/" : "") + (className + "/") + mDescription;
return new TrackMe(getBaseTrackMe())
.set(QueryParams.ACTION_NAME, actionName)
.set(QueryParams.EVENT_CATEGORY, "Exception")
.set(QueryParams.EVENT_ACTION, className)
.set(QueryParams.EVENT_NAME, mDescription)
.set(QueryParams.EVENT_VALUE, mIsFatal ? 1 : 0);
}
}
public UncaughtExceptions uncaughtExceptions() {
return new UncaughtExceptions(this);
}
public static class UncaughtExceptions {
private final TrackHelper mBaseBuilder;
UncaughtExceptions(TrackHelper baseBuilder) {
mBaseBuilder = baseBuilder;
}
/**
* @param tracker the tracker that should receive the exception events.
* @return returns the new (but already active) exception handler.
*/
public Thread.UncaughtExceptionHandler with(Tracker tracker) {
if (Thread.getDefaultUncaughtExceptionHandler() instanceof PiwikExceptionHandler) {
throw new RuntimeException("Trying to wrap an existing PiwikExceptionHandler.");
}
Thread.UncaughtExceptionHandler handler = new PiwikExceptionHandler(tracker, mBaseBuilder.mBaseTrackMe);
Thread.setDefaultUncaughtExceptionHandler(handler);
return handler;
}
}
/**
* This method will bind a tracker to your application,
* causing it to automatically track Activities with {@link #screen(Activity)} within your app.
*
* @param app your app
* @return the registered callback, you need this if you wanted to unregister the callback again
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public AppTracking screens(Application app) {
return new AppTracking(this, app);
}
public static class AppTracking {
private final Application mApplication;
private final TrackHelper mBaseBuilder;
public AppTracking(TrackHelper baseBuilder, Application application) {
mBaseBuilder = baseBuilder;
mApplication = application;
}
/**
* @param tracker the tracker to use
* @return the registered callback, you need this if you wanted to unregister the callback again
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public Application.ActivityLifecycleCallbacks with(final Tracker tracker) {
final Application.ActivityLifecycleCallbacks callback = new Application.ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
TrackHelper.track(mBaseBuilder.mBaseTrackMe).screen(activity).with(tracker);
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
if (activity != null && activity.isTaskRoot()) {
tracker.dispatch();
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
};
mApplication.registerActivityLifecycleCallbacks(callback);
return callback;
}
}
} |
package org.carlspring.strongbox.cron.jobs;
import org.carlspring.strongbox.config.NugetLayoutProviderCronTasksTestConfig;
import org.carlspring.strongbox.cron.domain.CronTaskConfigurationDto;
import org.carlspring.strongbox.cron.services.CronTaskConfigurationService;
import org.carlspring.strongbox.cron.services.JobManager;
import org.carlspring.strongbox.repository.RepositoryManagementStrategyException;
import org.carlspring.strongbox.resource.ConfigurationResourceResolver;
import org.carlspring.strongbox.services.ConfigurationManagementService;
import org.carlspring.strongbox.services.RepositoryManagementService;
import org.carlspring.strongbox.services.StorageManagementService;
import org.carlspring.strongbox.storage.MutableStorage;
import org.carlspring.strongbox.storage.repository.MutableRepository;
import org.carlspring.strongbox.storage.repository.NugetRepositoryFactory;
import org.carlspring.strongbox.storage.repository.RepositoryPolicyEnum;
import javax.inject.Inject;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.parallel.Execution;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.carlspring.strongbox.util.TestFileUtils.deleteIfExists;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.parallel.ExecutionMode.CONCURRENT;
/**
* @author Kate Novik.
*/
@ContextConfiguration(classes = NugetLayoutProviderCronTasksTestConfig.class)
@ExtendWith(SpringExtension.class)
@ActiveProfiles(profiles = "test")
public class RegenerateNugetChecksumCronJobTestIT
extends BaseCronJobWithNugetIndexingTestCase
{
private static final String STORAGE1 = "storage-nuget";
private static final String STORAGE2 = "nuget-checksum-test";
private static final String REPOSITORY_RELEASES = "rnccj-releases";
private static final String REPOSITORY_ALPHA = "rnccj-alpha";
private static final File REPOSITORY_RELEASES_BASEDIR_1 = new File(ConfigurationResourceResolver.getVaultDirectory() +
"/storages/" + STORAGE1 + "/" +
REPOSITORY_RELEASES);
private static final File REPOSITORY_ALPHA_BASEDIR = new File(ConfigurationResourceResolver.getVaultDirectory() +
"/storages/" + STORAGE1 + "/" +
REPOSITORY_ALPHA);
private static final File REPOSITORY_RELEASES_BASEDIR_2 = new File(ConfigurationResourceResolver.getVaultDirectory() +
"/storages/" + STORAGE2 + "/" +
REPOSITORY_RELEASES);
@Inject
private CronTaskConfigurationService cronTaskConfigurationService;
@Inject
private ConfigurationManagementService configurationManagementService;
@Inject
private RepositoryManagementService repositoryManagementService;
@Inject
protected StorageManagementService storageManagementService;
@Inject
private JobManager jobManager;
@Inject
private NugetRepositoryFactory nugetRepositoryFactory;
@BeforeAll
public static void cleanUp()
throws Exception
{
cleanUp(getRepositoriesToClean());
}
@Override
@BeforeEach
public void init(TestInfo testInfo)
throws Exception
{
super.init(testInfo);
createStorage(STORAGE1);
createRepository(STORAGE1, REPOSITORY_RELEASES, RepositoryPolicyEnum.RELEASE.getPolicy());
//Create released nuget package in the repository rnccj-releases (storage1)
generateNugetPackage(REPOSITORY_RELEASES_BASEDIR_1.getAbsolutePath(),
"org.carlspring.strongbox.checksum-second", "1.0");
createRepository(STORAGE1, REPOSITORY_ALPHA, RepositoryPolicyEnum.SNAPSHOT.getPolicy());
//Create pre-released nuget package in the repository rnccj-alpha
generateAlphaNugetPackage(REPOSITORY_ALPHA_BASEDIR.getAbsolutePath(), "org.carlspring.strongbox.checksum-one",
"1.0.1");
createStorage(STORAGE2);
createRepository(STORAGE2, REPOSITORY_RELEASES, RepositoryPolicyEnum.RELEASE.getPolicy());
//Create released nuget package in the repository rnccj-releases (storage2)
generateNugetPackage(REPOSITORY_RELEASES_BASEDIR_2.getAbsolutePath(), "org.carlspring.strongbox.checksum-one",
"1.0");
}
@AfterEach
public void removeRepositories()
throws IOException, JAXBException
{
removeRepositories(getRepositoriesToClean());
}
public static Set<MutableRepository> getRepositoriesToClean()
{
Set<MutableRepository> repositories = new LinkedHashSet<>();
repositories.add(createRepositoryMock(STORAGE1, REPOSITORY_RELEASES));
repositories.add(createRepositoryMock(STORAGE1, REPOSITORY_ALPHA));
repositories.add(createRepositoryMock(STORAGE2, REPOSITORY_RELEASES));
return repositories;
}
public void addRegenerateCronJobConfig(String name,
String storageId,
String repositoryId,
String basePath,
boolean forceRegeneration)
throws Exception
{
CronTaskConfigurationDto cronTaskConfiguration = new CronTaskConfigurationDto();
cronTaskConfiguration.setOneTimeExecution(true);
cronTaskConfiguration.setImmediateExecution(true);
cronTaskConfiguration.setName(name);
cronTaskConfiguration.addProperty("jobClass", RegenerateChecksumCronJob.class.getName());
cronTaskConfiguration.addProperty("cronExpression", "0 11 11 11 11 ? 2100");
cronTaskConfiguration.addProperty("storageId", storageId);
cronTaskConfiguration.addProperty("repositoryId", repositoryId);
cronTaskConfiguration.addProperty("basePath", basePath);
cronTaskConfiguration.addProperty("forceRegeneration", String.valueOf(forceRegeneration));
cronTaskConfigurationService.saveConfiguration(cronTaskConfiguration);
CronTaskConfigurationDto obj = cronTaskConfigurationService.getTaskConfigurationDto(name);
assertNotNull(obj);
}
@Test
public void testRegenerateNugetPackageChecksum()
throws Exception
{
final String jobName = expectedJobName;
String artifactPath = REPOSITORY_RELEASES_BASEDIR_1 + "/org.carlspring.strongbox.checksum-second";
deleteIfExists(
new File(artifactPath, "/1.0/org.carlspring.strongbox.checksum-second.1.0.nupkg.sha512"));
deleteIfExists(new File(artifactPath, "/1.0/org.carlspring.strongbox.checksum-second.nuspec.sha512"));
assertFalse(new File(artifactPath, "/1.0/org.carlspring.strongbox.checksum-second.1.0.nupkg.sha512").exists(),
"The checksum file for artifact exist!");
List<File> resultList = new ArrayList<>();
jobManager.registerExecutionListener(jobName, (jobName1, statusExecuted) ->
{
if (!jobName1.equals(jobName) || !statusExecuted)
{
return;
}
resultList.add(new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-second.1.0.nupkg.sha512"));
resultList.add(new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-second.nuspec.sha512"));
});
addCronJobConfig(jobName, RegenerateChecksumCronJob.class, STORAGE1, REPOSITORY_RELEASES,
properties ->
{
properties.put("basePath", "org.carlspring.strongbox.checksum-second");
properties.put("forceRegeneration","false");
});
assertTrue(expectEvent(), "Failed to execute task!");
assertEquals(2, resultList.size());
resultList.forEach(f -> {
assertTrue(f.exists(),
"The checksum file doesn't exist!");
assertTrue(f.length() > 0,
"The checksum file is empty!");
});
}
@Test
public void testRegenerateNugetChecksumInRepository()
throws Exception
{
final String jobName = expectedJobName;
deleteIfExists(
new File(REPOSITORY_ALPHA_BASEDIR,
"/org.carlspring.strongbox.checksum-one/1.0.1-alpha/org.carlspring.strongbox.checksum-one.1.0.1-alpha.nupkg.sha512"));
deleteIfExists(
new File(REPOSITORY_ALPHA_BASEDIR,
"/org.carlspring.strongbox.checksum-one/1.0.1-alpha/org.carlspring.strongbox.checksum-one.nuspec.sha512"));
assertFalse(new File(REPOSITORY_ALPHA_BASEDIR,
"/org.carlspring.strongbox.checksum-one/1.0.1-alpha/org.carlspring.strongbox.checksum-one.1.0.1-alpha.nupkg.sha512").exists(),
"The checksum file for artifact exist!");
List<File> resultList = new ArrayList<>();
jobManager.registerExecutionListener(jobName, (jobName1,
statusExecuted) -> {
if (!jobName1.equals(jobName) || !statusExecuted)
{
return;
}
resultList.add(new File(REPOSITORY_ALPHA_BASEDIR,
"/org.carlspring.strongbox.checksum-one/1.0.1-alpha/org.carlspring.strongbox.checksum-one.1.0.1-alpha.nupkg.sha512"));
resultList.add(new File(REPOSITORY_ALPHA_BASEDIR,
"/org.carlspring.strongbox.checksum-one/1.0.1-alpha/org.carlspring.strongbox.checksum-one.nuspec.sha512"));
});
addCronJobConfig(jobName, RegenerateChecksumCronJob.class, STORAGE1, REPOSITORY_ALPHA,
properties -> properties.put("forceRegeneration", "false"));
assertTrue(expectEvent(), "Failed to execute task!");
assertEquals(2, resultList.size());
resultList.forEach(f -> {
assertTrue(f.exists(),
"The checksum file doesn't exist!");
assertTrue(f.length() > 0,
"The checksum file is empty!");
});
}
@Test
public void testRegenerateNugetChecksumInStorage()
throws Exception
{
final String jobName = expectedJobName;
String artifactPath = REPOSITORY_RELEASES_BASEDIR_1 + "/org.carlspring.strongbox.checksum-second";
deleteIfExists(new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-second.1.0.nupkg.sha512"));
deleteIfExists(new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-second.nuspec.sha512"));
assertFalse(new File(artifactPath, "/1.0/org.carlspring.strongbox.checksum-second.1.0.nupkg.sha512").exists(),
"The checksum file for artifact exist!");
List<File> resultList = new ArrayList<>();
jobManager.registerExecutionListener(jobName, (jobName1,
statusExecuted) -> {
if (!jobName1.equals(jobName) || !statusExecuted)
{
return;
}
resultList.add(new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-second.1.0.nupkg.sha512"));
resultList.add(new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-second.nuspec.sha512"));
});
addCronJobConfig(jobName, RegenerateChecksumCronJob.class, STORAGE1, null,
properties -> properties.put("forceRegeneration", "false"));
assertTrue(expectEvent(), "Failed to execute task!");
assertEquals(2, resultList.size());
resultList.forEach(f -> {
assertTrue(f.exists(),
"The checksum file doesn't exist!");
assertTrue(f.length() > 0,
"The checksum file is empty!");
});
}
@Test
public void testRegenerateNugetChecksumInStorages()
throws Exception
{
final String jobName = expectedJobName;
String artifactPath = REPOSITORY_RELEASES_BASEDIR_2 + "/org.carlspring.strongbox.checksum-one";
deleteIfExists(new File(artifactPath, "/1.0/org.carlspring.strongbox.checksum-one.1.0.nupkg.sha512"));
deleteIfExists(new File(artifactPath, "/1.0/org.carlspring.strongbox.checksum-one.nuspec.sha512"));
assertFalse(new File(artifactPath, "/1.0/org.carlspring.strongbox.checksum-one.1.0.nupkg.sha512").exists(),
"The checksum file for artifact exist!");
List<File> resultList = new ArrayList<>();
jobManager.registerExecutionListener(jobName, (jobName1, statusExecuted) ->
{
if (!jobName1.equals(jobName) || !statusExecuted)
{
return;
}
resultList.add(new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-one.1.0.nupkg.sha512"));
resultList.add(new File(artifactPath,
"/1.0/org.carlspring.strongbox.checksum-one.nuspec.sha512"));
});
addCronJobConfig(jobName, RegenerateChecksumCronJob.class, null, null,
properties -> properties.put("forceRegeneration","false"));
assertTrue(expectEvent(), "Failed to execute task!");
assertEquals(2, resultList.size());
resultList.forEach(f -> {
assertTrue(f.exists(),
"The checksum file doesn't exist!");
assertTrue(f.length() > 0,
"The checksum file is empty!");
});
}
private void createRepository(String storageId,
String repositoryId,
String policy)
throws IOException,
JAXBException,
RepositoryManagementStrategyException
{
MutableRepository repository = nugetRepositoryFactory.createRepository(repositoryId);
repository.setPolicy(policy);
createRepository(storageId, repository);
}
private void createRepository(String storageId, MutableRepository repository)
throws IOException,
JAXBException,
RepositoryManagementStrategyException
{
configurationManagementService.saveRepository(storageId, repository);
// Create the repository
repositoryManagementService.createRepository(storageId, repository.getId());
}
private void createStorage(String storageId)
throws IOException, JAXBException
{
createStorage(new MutableStorage(storageId));
}
private void createStorage(MutableStorage storage)
throws IOException, JAXBException
{
configurationManagementService.saveStorage(storage);
storageManagementService.createStorage(storage);
}
public static void cleanUp(Set<MutableRepository> repositoriesToClean)
throws Exception
{
if (repositoriesToClean != null)
{
for (MutableRepository repository : repositoriesToClean)
{
removeRepositoryDirectory(repository.getStorage().getId(), repository.getId());
}
}
}
private static void removeRepositoryDirectory(String storageId,
String repositoryId)
throws IOException
{
File repositoryBaseDir = new File(ConfigurationResourceResolver.getVaultDirectory(),
"/storages/" + storageId + "/" + repositoryId);
if (repositoryBaseDir.exists())
{
org.apache.commons.io.FileUtils.deleteDirectory(repositoryBaseDir);
}
}
public void removeRepositories(Set<MutableRepository> repositoriesToClean)
throws IOException, JAXBException
{
for (MutableRepository repository : repositoriesToClean)
{
configurationManagementService.removeRepository(repository.getStorage()
.getId(), repository.getId());
}
}
public static MutableRepository createRepositoryMock(String storageId,
String repositoryId)
{
// This is no the real storage, but has a matching ID.
// We're mocking it, as the configurationManager is not available at the the static methods are invoked.
MutableStorage storage = new MutableStorage(storageId);
MutableRepository repository = new MutableRepository(repositoryId);
repository.setStorage(storage);
return repository;
}
} |
package com.jbooktrader.platform.marketdepth;
import com.jbooktrader.platform.marketbook.*;
import com.jbooktrader.platform.model.*;
import com.jbooktrader.platform.report.*;
import java.util.*;
/**
* Holds history of market snapshots for a trading instrument.
*/
public class MarketDepth {
private final LinkedList<MarketDepthItem> bids, asks;
private boolean isResetting;
private double lowBalance, highBalance, lastBalance;
private double midPointPrice;
private HashSet<String> errorMessages;
private Report eventReport;
public MarketDepth() {
bids = new LinkedList<MarketDepthItem>();
asks = new LinkedList<MarketDepthItem>();
errorMessages = new HashSet<String>();
isResetting = true;
eventReport = Dispatcher.getReporter();
}
public void reset() {
isResetting = true;
bids.clear();
asks.clear();
}
/**
* Market depth is considered valid when all four of the following conditions are true:
* <p/>
* 1. The number of bid levels equals the number of ask levels and is non-zero
* 2. The bid price of level N is smaller than the bid price of level N-1 for all levels
* 3. The ask price of level N is greater than the ask price of level N-1 for all levels
* 4. The best bid price (at level 0) is smaller than the best ask price (at level 0)
*/
private void checkForValidity() {
boolean isValid = true;
// Number of bid levels must be the same as number of ask levels
int bidLevels = bids.size();
int askLevels = asks.size();
if (bidLevels != askLevels) {
isValid = false;
String errorMsg = "Number of bid levels (" + bidLevels + ") is not equal to number of ask levels (" + askLevels + ")";
if (!errorMessages.contains(errorMsg)) {
errorMessages.add(errorMsg);
eventReport.report(errorMsg);
}
}
if (bidLevels == 0) {
isValid = false;
String errorMsg = "No bids";
if (!errorMessages.contains(errorMsg)) {
errorMessages.add(errorMsg);
eventReport.report(errorMsg);
}
}
if (askLevels == 0) {
isValid = false;
String errorMsg = "No asks";
if (!errorMessages.contains(errorMsg)) {
errorMessages.add(errorMsg);
eventReport.report(errorMsg);
}
}
// The bid price of level N must be smaller than the bid price of level N-1
if (!bids.isEmpty()) {
double previousLevelBidPrice = bids.getFirst().getPrice();
for (int itemIndex = 1; itemIndex < bidLevels; itemIndex++) {
double price = bids.get(itemIndex).getPrice();
if (price >= previousLevelBidPrice) {
isValid = false;
String errorMsg = "Bid price " + price + " at level " + itemIndex + " is greater or equal to bid price " + previousLevelBidPrice + " at level " + (itemIndex - 1);
if (!errorMessages.contains(errorMsg)) {
errorMessages.add(errorMsg);
eventReport.report(errorMsg);
}
}
previousLevelBidPrice = price;
}
}
// The ask price of level N must be greater than the ask price of level N-1
if (!asks.isEmpty()) {
double previousLevelAskPrice = asks.getFirst().getPrice();
for (int itemIndex = 1; itemIndex < askLevels; itemIndex++) {
double price = asks.get(itemIndex).getPrice();
if (price <= previousLevelAskPrice) {
isValid = false;
String errorMsg = "Ask price " + price + " at level " + itemIndex + " is smaller or equal to ask price " + previousLevelAskPrice + " at level " + (itemIndex - 1);
if (!errorMessages.contains(errorMsg)) {
errorMessages.add(errorMsg);
eventReport.report(errorMsg);
}
}
previousLevelAskPrice = price;
}
}
// Best bid price must be smaller than the best ask price
if (!bids.isEmpty() && !asks.isEmpty()) {
double bestBid = bids.getFirst().getPrice();
double bestAsk = asks.getFirst().getPrice();
if (bestBid >= bestAsk) {
isValid = false;
String errorMsg = "Best bid price " + bestBid + " is greater or equal to best ask price " + bestAsk;
if (!errorMessages.contains(errorMsg)) {
errorMessages.add(errorMsg);
eventReport.report(errorMsg);
}
}
}
if (isValid && !errorMessages.isEmpty()) {
errorMessages.clear();
String errorMsg = "Errors cleared. Market depth is valid.";
eventReport.report(errorMsg);
}
}
private int getCumulativeSize(LinkedList<MarketDepthItem> items) {
int cumulativeSize = 0;
for (MarketDepthItem item : items) {
cumulativeSize += item.getSize();
}
return cumulativeSize;
}
public String getMarketDepthAsString() {
return errorMessages.isEmpty() ? (getCumulativeSize(bids) + "-" + getCumulativeSize(asks)) : "invalid";
}
synchronized public void update(int position, MarketDepthOperation operation, MarketDepthSide side, double price, int size) {
List<MarketDepthItem> items = (side == MarketDepthSide.Bid) ? bids : asks;
int levels = items.size();
switch (operation) {
case Insert:
if (position <= levels) {
items.add(position, new MarketDepthItem(size, price));
}
break;
case Update:
if (position < levels) {
MarketDepthItem item = items.get(position);
item.setSize(size);
item.setPrice(price);
}
break;
case Delete:
if (position < levels) {
items.remove(position);
}
break;
}
if (operation == MarketDepthOperation.Update) {
int cumulativeBid = getCumulativeSize(bids);
int cumulativeAsk = getCumulativeSize(asks);
double totalDepth = cumulativeBid + cumulativeAsk;
lastBalance = 100d * (cumulativeBid - cumulativeAsk) / totalDepth;
lowBalance = Math.min(lastBalance, lowBalance);
highBalance = Math.max(lastBalance, highBalance);
midPointPrice = (bids.getFirst().getPrice() + asks.getFirst().getPrice()) / 2;
isResetting = false;
}
}
synchronized public MarketSnapshot getMarketSnapshot(long time) {
if (isResetting) {
return null;
}
checkForValidity();
int balance = (int) Math.round((lowBalance + highBalance) / 2d);
MarketSnapshot marketSnapshot = new MarketSnapshot(time, balance, midPointPrice);
// reset values for the next market snapshot
highBalance = lowBalance = lastBalance;
return marketSnapshot;
}
} |
// EarthShape.java
package earthshape;
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.CheckboxMenuItem;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.Point;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.GLCapabilities;
import com.jogamp.opengl.GLEventListener;
import com.jogamp.opengl.awt.GLCanvas;
import com.jogamp.opengl.util.Animator;
import com.jogamp.opengl.util.texture.Texture;
import com.jogamp.opengl.util.texture.TextureData;
import com.jogamp.opengl.util.texture.TextureIO;
import util.FloatUtil;
import util.Vector3f;
/** This application demonstrates a procedure for inferring the shape
* of a surface (such as the Earth) based on the observed locations of
* stars from various locations at a fixed point in time. */
public class EarthShape
// For now at least, continue to use plain AWT.
extends Frame
// Listen for GL draw events.
implements GLEventListener,
// Also handle keyboard input.
KeyListener,
// And mouse input for the GL canvas.
MouseListener, MouseMotionListener
{
// AWT boilerplate.
private static final long serialVersionUID = 3903955302894393226L;
/** Compass rose texture. This is only valid between 'init' and
* 'dispose'. */
private Texture compassTexture;
private Texture earthMapTexture;
/** The main GL canvas. */
private GLCanvas glCanvas;
/** Camera position in space. */
private Vector3f cameraPosition = new Vector3f(1,1,2);
/** Azimuth angle in which the camera is looking, in degrees
* to the left of the -Z axis. It is kept in [0,360), wrapping
* as it gets to either extreme. */
private float cameraAzimuthDegrees = 0;
/** When the mouse moves one pixel horizontally, the camera
* azimuth turns by this many degrees. */
private static final float CAMERA_HORIZONTAL_SENSITIVITY = 0.5f;
/** Camera pitch angle, in degrees. In [-90,90], where +90 is
* straight up. */
private float cameraPitchDegrees = 0;
/** When the mouse moves one pixel vertically, the camera pitch
* angle changes by this many degrees. */
private static final float CAMERA_VERTICAL_SENSITIVITY = 0.5f;
/** Velocity of camera movement, in world coordinates. The magnitude
* is units per second. */
private Vector3f cameraVelocity = new Vector3f(0,0,0);
/** As the camera continues moving, it accelerates by this
* amount with each additional key press event. */
private static final float CAMERA_ACCELERATION = 4f;
/** Max amount of friction acceleration to apply to camera
* velocity, in units per second per second, when at least
* one movement key is being held. */
private static final float MOVING_CAMERA_FRICTION = 2f;
/** Max amount of friction acceleration to apply to camera
* velocity, in units per second per second, when no
* movement keys are being held. */
private static final float STATIONARY_CAMERA_FRICTION = 5f;
/** Widget to show various state variables such as camera position. */
private Label statusLabel = new Label();
/** True when we are in "first person shooter" camera control
* mode, where mouse movement looks around and the mouse is
* kept inside the canvas window. */
private boolean fpsCameraMode = false;
/** "Robot" interface object, used to move the mouse in FPS mode. */
private Robot robotObject;
/** Blank cursor, used to hide the mouse cursor. */
private Cursor blankCursor;
/** Animator object for the GL canvas. Valid between init and
* dispose. */
private Animator animator;
/** The thread that last issued a 'log' command. This is used to
* only log thread names when there is interleaving. */
private static Thread lastLoggedThread = null;
/** The value of the millisecond timer the last time physics was
* updated. */
private long lastPhysicsUpdateMillis;
/** For each possible movement direction, true if that direction's
* key is held down. */
private boolean[] moveKeys = new boolean[MoveDirection.values().length];
/** Units in 3D space coordinates per km in surface being mapped. */
private static final float SPACE_UNITS_PER_KM = 0.001f;
/** Squares of the surface we have built. */
private ArrayList<SurfaceSquare> surfaceSquares = new ArrayList<SurfaceSquare>();
/** If true, draw surfaces using the abstract compass texture.
* Otherwise, draw them using the EarthMap texture. */
private boolean drawCompasses = true;
/** Menu item to toggle 'drawCompasses'. */
private CheckboxMenuItem drawCompassesCBItem;
/** If true, draw surface normals as short line segments. */
private boolean drawSurfaceNormals = true;
/** Menu item to toggle 'drawSurfaceNormals'. */
private CheckboxMenuItem drawSurfaceNormalsCBItem;
/** If true, draw celestial North vectors on each square. */
private boolean drawCelestialNorth = false;
/** Menu item to toggle 'drawCelestialNorth'. */
private CheckboxMenuItem drawCelestialNorthCBItem;
/** Current aspect ratio: canvas width divided by canvas height
* in pixels. (Really, aspect ratio ought to reflect physical
* size ratio, but I will assume pixels are square; fortunately,
* they usually are.) */
private float aspectRatio = 1.0f;
/** Desired distance between camera and front clipping plane. */
private static final float FRONT_CLIP_DISTANCE = 0.1f;
public EarthShape()
{
super("Earth Shape");
try {
this.robotObject = new Robot();
}
catch (AWTException e) {
e.printStackTrace();
System.exit(2);
}
this.setLayout(new BorderLayout());
// Exit the app when window close button is pressed (AWT boilerplate).
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
EarthShape.this.dispose();
}
});
//this.addKeyListener(this);
this.setSize(800, 800);
this.setLocationByPlatform(true);
// Create a blank cursor so I can hide the cursor later.
{
BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
this.blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(
cursorImg, new Point(0, 0), "blank cursor");
}
this.buildEarthSurfaceFromStarData();
this.setupJOGL();
this.lastPhysicsUpdateMillis = System.currentTimeMillis();
this.glCanvas.addKeyListener(this);
this.glCanvas.addMouseListener(this);
this.glCanvas.addMouseMotionListener(this);
this.buildMenuBar();
// Status bar on bottom.
this.statusLabel = new Label();
this.setStatusLabel();
this.add(this.statusLabel, BorderLayout.SOUTH);
}
/** Initialize the JOGL library, then create a GL canvas and
* associate it with this window. */
private void setupJOGL()
{
log("creating GLCapabilities");
// This call takes about one second to complete, which is
// pretty slow...
GLCapabilities caps = new GLCapabilities(null /*profile*/);
log("caps: "+caps);
caps.setDoubleBuffered(true);
caps.setHardwareAccelerated(true);
// Make the GL canvas and specify that 'this' object will
// handle its draw-related events.
this.glCanvas = new GLCanvas(caps);
this.glCanvas.addGLEventListener(this);
// Associate the canvas with 'this' window.
this.add(this.glCanvas, BorderLayout.CENTER);
}
/** Build the menu bar and attach it to 'this'. */
private void buildMenuBar()
{
MenuBar menuBar = new MenuBar();
this.setMenuBar(menuBar);
Menu fileMenu = new Menu("File");
addMenuItem(fileMenu, "Exit", new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.log("exit menu item invoked");
EarthShape.this.dispose();
}
});
menuBar.add(fileMenu);
Menu drawMenu = new Menu("Draw");
this.drawCompassesCBItem =
addCBMenuItem(drawMenu, "Draw squares with compasses", this.drawCompasses,
new ItemListener() {
public void itemStateChanged(ItemEvent e) {
EarthShape.this.toggleDrawCompasses();
}
});
this.drawSurfaceNormalsCBItem =
addCBMenuItem(drawMenu, "Draw surface normals", this.drawSurfaceNormals,
new ItemListener() {
public void itemStateChanged(ItemEvent e) {
EarthShape.this.toggleDrawSurfaceNormals();
}
});
this.drawCelestialNorthCBItem =
addCBMenuItem(drawMenu, "Draw celestial North", this.drawCelestialNorth,
new ItemListener() {
public void itemStateChanged(ItemEvent e) {
EarthShape.this.toggleDrawCelestialNorth();
}
});
menuBar.add(drawMenu);
Menu buildMenu = new Menu("Build");
addMenuItem(buildMenu, "Build Earth using star data and no assumed shape",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.buildEarthSurfaceFromStarData();
}
});
addMenuItem(buildMenu, "Build complete Earth using assumed sphere",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.buildEarthSurfaceWithLatLong();
}
});
addMenuItem(buildMenu, "Build partial Earth using assumed sphere and random walk",
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.randomWalkEarthSurface();
}
});
menuBar.add(buildMenu);
}
/** Make a new menu item and add it to 'menu' with the given
* label and listener. */
private static void addMenuItem(Menu menu, String itemLabel,
ActionListener listener)
{
MenuItem item = new MenuItem(itemLabel);
item.addActionListener(listener);
menu.add(item);
}
private static CheckboxMenuItem addCBMenuItem(Menu menu, String itemLabel,
boolean initState, ItemListener listener)
{
CheckboxMenuItem cbItem =
new CheckboxMenuItem(itemLabel, initState);
cbItem.addItemListener(listener);
menu.add(cbItem);
return cbItem;
}
/** Print a message to the console with a timestamp. */
private static void log(String msg)
{
Thread t = Thread.currentThread();
if (t != EarthShape.lastLoggedThread) {
System.out.println(""+System.currentTimeMillis()+
" ["+t.getName()+"]"+
": "+msg);
EarthShape.lastLoggedThread = t;
}
else {
System.out.println(""+System.currentTimeMillis()+
": "+msg);
}
}
/** Initialize the GL context. */
@Override
public void init(GLAutoDrawable drawable) {
log("init");
// The tutorial I am working from uses 'GL' rather than 'GL2',
// but I find that using 'GL' leads to syntax errors since
// some of the methods I'm supposed to call are only defined
// for 'GL2'. I assume the tutorial is just out of date.
GL2 gl = drawable.getGL().getGL2();
// Load textures. We have to wait until 'init' to do this because
// it requires a GL context because the textures are loaded into
// the graphics card's memory in a device- and mode-dependent
// format.
log("loading textures");
this.compassTexture = loadTexture(gl, "textures/compass-rose.png", TextureIO.PNG);
this.earthMapTexture = loadTexture(gl, "textures/EarthMap.jpg", TextureIO.JPG);
// Set up an animator to keep redrawing. This is not started
// until we enter "FPS" mode.
this.animator = new Animator(drawable);
// Use a light blue background.
gl.glClearColor(0.8f, 0.9f, 1.0f, 0);
//gl.glClearColor(0,0,0,0);
// Enable lighting generally.
gl.glEnable(GL2.GL_LIGHTING);
// Enable light #0, which has some default properties that,
// for the moment, seem to work adequately.
gl.glEnable(GL2.GL_LIGHT0);
// Position to try to get some more differentiation among
// surfaces with different normals.
gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_POSITION,
new float[] {-0.5f, 1f, 0.5f, 0}, 0);
// Increase the ambient intensity of that light.
//gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_AMBIENT, new float[] {1,1,1,1}, 0);
// There was no need for that; the dim light was once again
// a consequence of non-unit normal vectors.
}
/** Load and return a texture of a given name and type. This exits
* the process if texture loading fails. */
private Texture loadTexture(GL2 gl, String fileName, String fileType)
{
InputStream stream = getClass().getResourceAsStream(fileName);
try {
TextureData data = TextureIO.newTextureData(
gl.getGLProfile(), stream, false /*mipmap*/, fileType);
Texture ret = TextureIO.newTexture(data);
log("loaded "+fileName+"; mem="+ret.getEstimatedMemorySize()+
", coords="+ret.getImageTexCoords());
return ret;
}
catch (IOException e) {
// For now at least, failure to load a texture is fatal.
e.printStackTrace();
System.exit(2);
return null;
}
finally {
try {
stream.close();
}
catch (IOException e) {}
}
}
/** Release allocated resources associated with the GL context. */
@Override
public void dispose(GLAutoDrawable drawable) {
log("dispose");
GL2 gl = drawable.getGL().getGL2();
this.compassTexture.destroy(gl);
this.compassTexture = null;
this.earthMapTexture.destroy(gl);
this.earthMapTexture = null;
this.animator.remove(drawable);
this.animator.stop();
this.animator = null;
}
/** Draw one frame to the screen. */
@Override
public void display(GLAutoDrawable drawable) {
//log("display");
// First, update object locations per physics rules.
this.updatePhysics();
GL2 gl = drawable.getGL().getGL2();
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
// Specify camera projection.
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glLoadIdentity();
// Note: The combination of near clipping plane and the
// left/right/top/bottom values defines the field of view.
// If you move the clipping plane nearer the camera without
// adjusting the edges, the FOV becomes larger!
gl.glFrustum(-FRONT_CLIP_DISTANCE * this.aspectRatio, // left
FRONT_CLIP_DISTANCE * this.aspectRatio, // right
-FRONT_CLIP_DISTANCE, // bottom
FRONT_CLIP_DISTANCE, // top
FRONT_CLIP_DISTANCE, // front clip
300); // back clip
// Rotate and position camera. Effectively, these
// transformations happen in the reverse order they are
// written here; first we translate, then yaw, then
// finally pitch.
gl.glRotatef(-this.cameraPitchDegrees, +1, 0, 0);
gl.glRotatef(-this.cameraAzimuthDegrees, 0, +1, 0);
{
Vector3f c = this.cameraPosition;
gl.glTranslatef(-c.x(), -c.y(), -c.z());
}
// Enable depth test for hidden surface removal.
gl.glEnable(GL.GL_DEPTH_TEST);
// Enable automatic normal vector normalization so
// I can freely scale my geometry without worrying about
// denormalizing the normal vectors and messing up
// the lighting calculations.
gl.glEnable(GL2.GL_NORMALIZE);
// Future matrix manipulations are for the model.
gl.glMatrixMode(GL2.GL_MODELVIEW);
// Use thicker lines so they will show up better if/when I
// make a screenshot recording.
gl.glLineWidth(2);
// Make axis normals point toward +Y since my light is
// above the scene.
gl.glNormal3f(0,1,0);
// The axes are not textured.
gl.glDisable(GL.GL_TEXTURE_2D);
// X axis.
{
gl.glBegin(GL.GL_LINES);
glMaterialColor3f(gl, 1,0,0); // Red
// Draw from origin to points at infinity.
gl.glVertex4f(0,0,0,1);
gl.glVertex4f(-1,0,0,0);
gl.glVertex4f(0,0,0,1);
gl.glVertex4f(+1,0,0,0);
for (int i=-100; i < 100; i++) {
if (i == 0) { continue; }
float size = (i%10==0? 0.5f : 0.1f);
gl.glVertex3f(i, size, 0);
gl.glVertex3f(i, -size, 0);
gl.glVertex3f(i, 0, size);
gl.glVertex3f(i, 0, -size);
}
gl.glEnd();
// Draw a "+X" at the positive end for reference.
gl.glPushMatrix();
gl.glTranslatef(100, 10, 0);
gl.glScalef(10, 10, 10);
gl.glRotatef(-90, 0, 1, 0);
gl.glTranslatef(-1, 0, 0);
drawPlus(gl);
gl.glTranslatef(1, 0, 0);
drawX(gl);
gl.glPopMatrix();
}
// Y axis.
{
gl.glBegin(GL.GL_LINES);
glMaterialColor3f(gl, 0,0.5f,0); // Dark green
gl.glVertex4f(0,0,0,1);
gl.glVertex4f(0,-1,0,0);
gl.glVertex4f(0,0,0,1);
gl.glVertex4f(0,+1,0,0);
for (int i=-100; i < 100; i++) {
if (i == 0) { continue; }
float size = (i%10==0? 0.5f : 0.1f);
gl.glVertex3f(size, i, 0);
gl.glVertex3f(-size, i, 0);
gl.glVertex3f(0, i, size);
gl.glVertex3f(0, i, -size);
}
gl.glEnd();
// Draw a "+Y" at the positive end for reference.
gl.glPushMatrix();
gl.glTranslatef(0, 100, 10);
gl.glScalef(10, 10, 10);
gl.glRotatef(90, 1, 0, 0);
gl.glTranslatef(-1, 0, 0);
drawPlus(gl);
gl.glTranslatef(1, 0, 0);
drawY(gl);
gl.glPopMatrix();
}
// Z axis.
{
gl.glBegin(GL.GL_LINES);
glMaterialColor3f(gl, 0,0,1); // Dark blue
gl.glVertex4f(0,0,0,1);
gl.glVertex4f(0,0,-1,0);
gl.glVertex4f(0,0,0,1);
gl.glVertex4f(0,0,+1,0);
for (int i=-100; i < 100; i++) {
if (i == 0) { continue; }
float size = (i%10==0? 0.5f : 0.1f);
gl.glVertex3f(0, size, i);
gl.glVertex3f(0, -size, i);
gl.glVertex3f(size, 0, i);
gl.glVertex3f(-size, 0, i);
}
gl.glEnd();
// Draw a "+Z" at the positive end for reference.
gl.glPushMatrix();
gl.glTranslatef(0, 10, 100);
gl.glScalef(10, 10, 10);
gl.glRotatef(180, 0, 1, 0);
gl.glTranslatef(-1, 0, 0);
drawPlus(gl);
gl.glTranslatef(1, 0, 0);
drawZ(gl);
gl.glPopMatrix();
}
this.drawEarthSurface(gl);
gl.glFlush();
}
/** Set the next vertex's color using glMaterial. My intent is this
* is sort of a replacement for glColor when using lighting. */
private static void glMaterialColor3f(GL2 gl, float r, float g, float b)
{
gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL2.GL_AMBIENT_AND_DIFFUSE,
new float[] { r,g,b,1 }, 0);
}
/** Draw a rectangle with the compass texture. */
private void drawCompassRect(
GL2 gl,
Vector3f nw,
Vector3f sw,
Vector3f ne,
Vector3f se)
{
gl.glEnable(GL.GL_TEXTURE_2D);
this.compassTexture.bind(gl);
gl.glBegin(GL.GL_TRIANGLE_STRIP);
glMaterialColor3f(gl, 1, 1, 1);
// Normal vector, based on just three vertices (since these
// are supposed to be flat anyway).
Vector3f normal = (se.minus(sw)).cross(nw.minus(sw));
gl.glNormal3f(normal.x(), normal.y(), normal.z());
// NW corner.
gl.glTexCoord2f(0,1);
gl.glVertex3fv(nw.getArray(), 0);
// SW corner.
gl.glTexCoord2f(0,0);
gl.glVertex3fv(sw.getArray(), 0);
// NE corner.
gl.glTexCoord2f(1,1);
gl.glVertex3fv(ne.getArray(), 0);
// SE corner.
gl.glTexCoord2f(1,0);
gl.glVertex3fv(se.getArray(), 0);
gl.glEnd();
}
/** Draw a square with the earth map texture. */
private void drawEarthMapRect(
GL2 gl,
Vector3f nw,
Vector3f sw,
Vector3f ne,
Vector3f se,
float centerLatitude,
float centerLongitude,
float sizeKm)
{
// Calculate the latitudes of the North and South edges, assuming
// 111km per degree. (222 is because I'm dividing in half in order
// to offset in both directions.)
float northLatitude = centerLatitude + (sizeKm / 222);
float southLatitude = centerLatitude - (sizeKm / 222);
// Calculate longitudes of the corners, assuming
// 111km * cos(latitude) per degree.
float neLongitude = (float)(centerLongitude + (sizeKm / (222 * FloatUtil.cosDegf(northLatitude))));
float nwLongitude = (float)(centerLongitude - (sizeKm / (222 * FloatUtil.cosDegf(northLatitude))));
float seLongitude = (float)(centerLongitude + (sizeKm / (222 * FloatUtil.cosDegf(southLatitude))));
float swLongitude = (float)(centerLongitude - (sizeKm / (222 * FloatUtil.cosDegf(southLatitude))));
gl.glEnable(GL.GL_TEXTURE_2D);
this.earthMapTexture.bind(gl);
gl.glBegin(GL.GL_TRIANGLE_STRIP);
glMaterialColor3f(gl, 1, 1, 1);
// Normal vector, based on just three vertices (since these
// are supposed to be flat anyway).
Vector3f normal = (se.minus(sw)).cross(nw.minus(sw));
gl.glNormal3f(normal.x(), normal.y(), normal.z());
// NW corner.
gl.glTexCoord2f(long2tex(nwLongitude), lat2tex(northLatitude));
gl.glVertex3fv(nw.getArray(), 0);
// SW corner.
gl.glTexCoord2f(long2tex(swLongitude), lat2tex(southLatitude));
gl.glVertex3fv(sw.getArray(), 0);
// NE corner.
gl.glTexCoord2f(long2tex(neLongitude), lat2tex(northLatitude));
gl.glVertex3fv(ne.getArray(), 0);
// SE corner.
gl.glTexCoord2f(long2tex(seLongitude), lat2tex(southLatitude));
gl.glVertex3fv(se.getArray(), 0);
gl.glEnd();
}
/** Convert a latitude to a 'v' texture coordinate for the Earth map. */
private float lat2tex(float latitude)
{
// -90 maps to the bottom (0), +90 maps to the top (1).
return (float)((latitude + 90) / 180);
}
/** Convert a longitude to a 'u' texture coordinate for the Earth map. */
private float long2tex(float longitude)
{
// -180 maps to the left (0), +180 maps to the right (1).
return (float)((longitude + 180) / 360);
}
/** Build a portion of the Earth's surface. Adds squares to
* 'surfaceSquares'. This works by iterating over latitude
* and longitude pairs and assuming a spherical Earth. */
private void buildEarthSurfaceWithLatLong()
{
log("building Earth");
this.surfaceSquares.clear();
// Size of squares to build, in km.
float sizeKm = 1000;
// Start with an arbitrary square centered at the origin
// the 3D space, and at SF, CA in the real world.
float startLatitude = 38; // 38N
float startLongitude = -122; // 122W
SurfaceSquare startSquare = new SurfaceSquare(
new Vector3f(0,0,0), // center
new Vector3f(0,0,-1), // north
new Vector3f(0,1,0),
sizeKm,
startLatitude,
startLongitude,
new Vector3f(0,0,0));
this.addSurfaceSquare(startSquare);
// Outer loop 1: Walk North as far as we can.
SurfaceSquare outer = startSquare;
for (float latitude = startLatitude;
latitude < 90;
latitude += 9)
{
// Go North another step.
outer = this.addAdjacentSquare(outer, latitude, startLongitude);
// Inner loop: Walk East until we get back to
// the same longitude.
float longitude = startLongitude;
float prevLongitude = longitude;
SurfaceSquare inner = outer;
while (true) {
inner = this.addAdjacentSquare(inner, latitude, longitude);
if (prevLongitude < outer.longitude &&
outer.longitude <= longitude) {
break;
}
prevLongitude = longitude;
longitude = FloatUtil.modulus2(longitude+9, -180, 180);
}
}
// Outer loop 2: Walk South as far as we can.
outer = startSquare;
for (float latitude = startLatitude - 9;
latitude > -90;
latitude -= 9)
{
// Go North another step.
outer = this.addAdjacentSquare(outer, latitude, startLongitude);
// Inner loop: Walk East until we get back to
// the same longitude.
float longitude = startLongitude;
float prevLongitude = longitude;
SurfaceSquare inner = outer;
while (true) {
inner = this.addAdjacentSquare(inner, latitude, longitude);
if (prevLongitude < outer.longitude &&
outer.longitude <= longitude) {
break;
}
prevLongitude = longitude;
longitude = FloatUtil.modulus2(longitude+9, -180, 180);
}
}
this.redrawCanvas();
log("finished building Earth; nsquares="+this.surfaceSquares.size());
}
/** Build the surface by walking randomly from a starting location. */
private void randomWalkEarthSurface()
{
log("building Earth by random walk");
this.surfaceSquares.clear();
// Size of squares to build, in km.
float sizeKm = 1000;
// Start with an arbitrary square centered at the origin
// the 3D space, and at SF, CA in the real world.
float startLatitude = 38; // 38N
float startLongitude = -122; // 122W
SurfaceSquare startSquare = new SurfaceSquare(
new Vector3f(0,0,0), // center
new Vector3f(0,0,-1), // north
new Vector3f(0,1,0),
sizeKm,
startLatitude,
startLongitude,
new Vector3f(0,0,0));
this.addSurfaceSquare(startSquare);
SurfaceSquare square = startSquare;
for (int i=0; i < 1000; i++) {
// Select a random change in latitude and longitude
// of about 10 degrees.
float deltaLatitude = (float)(Math.random() * 12 - 6);
float deltaLongitude = (float)(Math.random() * 12 - 6);
// Walk in that direction, keeping latitude and longitude
// within their usual ranges. Also stay away from the poles
// since the rounding errors cause problems there.
square = this.addAdjacentSquare(square,
FloatUtil.clamp(square.latitude + deltaLatitude, -80, 80),
FloatUtil.modulus2(square.longitude + deltaLongitude, -180, 180));
}
this.redrawCanvas();
log("finished building Earth; nsquares="+this.surfaceSquares.size());
}
/** Given square 'old', add an adjacent square at the given
* latitude and longitude. The relative orientation of the
* new square will determined using the latitude and longitude,
* at this stage as a proxy for star observation data. The size
* will be the same as the old square.
* This works best when the squares are nearby since this
* procedure assumes the surface is locally flat. */
private SurfaceSquare addAdjacentSquare(
SurfaceSquare old,
float newLatitude,
float newLongitude)
{
// Calculate local East for 'old'.
Vector3f oldEast = old.north.cross(old.up).normalize();
// Calculate celestial North for 'old', which is given by
// the latitude plus geographic North.
Vector3f celestialNorth =
old.north.rotate(old.latitude, oldEast);
// Get lat/long deltas.
float deltaLatitude = newLatitude - old.latitude;
float deltaLongitude = FloatUtil.modulus2(
newLongitude - old.longitude, -180, 180);
// If we didn't move, just return the old square.
if (deltaLongitude == 0 && deltaLatitude == 0) {
return old;
}
// What we want now is to first rotate Northward
// around local East to account for change in latitude, then
// Eastward around celestial North for change in longitude.
Vector3f firstRotation = oldEast.times(-deltaLatitude);
Vector3f secondRotation = celestialNorth.times(deltaLongitude);
// But then we want to express the composition of those as a
// single rotation vector in order to call the general routine.
Vector3f combined = Vector3f.composeRotations(firstRotation, secondRotation);
// Now call into the general procedure for adding a square
// given the proper relative orientation rotation.
return addRotatedAdjacentSquare(old, newLatitude, newLongitude, combined);
}
/** Build a surface using star data rather than any presumed
* size and shape. */
private void buildEarthSurfaceFromStarData()
{
log("building Earth using star data");
this.surfaceSquares.clear();
// Begin by grabbing the hardcoded star data.
StarData[] starData = StarData.getHardcodedData();
StarCatalog[] starCatalog = StarCatalog.makeCatalog();
// Size of squares to build, in km.
float sizeKm = 1000;
SurfaceSquare firstSquare = null;
// Work through the data in order, assuming that observations
// for a given location are contiguous, and that the data appears
// in a good walk order.
float curLatitude = 0;
float curLongitude = 0;
SurfaceSquare curSquare = null;
for (StarData sd : starData) {
// Skip forward to next location.
if (curSquare != null && sd.latitude == curLatitude && sd.longitude == curLongitude) {
continue;
}
log("buildEarth: building lat="+sd.latitude+" long="+sd.longitude);
if (curSquare == null) {
// First square will be placed at the 3D origin with
// its North pointed along the -Z axis.
curSquare = new SurfaceSquare(
new Vector3f(0,0,0), // center
new Vector3f(0,0,-1), // north
new Vector3f(0,1,0),
sizeKm,
sd.latitude,
sd.longitude,
new Vector3f(0,0,0));
this.addSurfaceSquare(curSquare);
firstSquare = curSquare;
}
else {
// Calculate a rotation vector that will best align
// the current square's star observations with the
// next square's.
Vector3f rot = calcRequiredRotation(curSquare, starData,
starCatalog, sd.latitude, sd.longitude);
if (rot == null) {
log("buildEarth: could not place next square!");
break;
}
// Make the new square from the old and the computed
// change in orientation.
curSquare =
addRotatedAdjacentSquare(curSquare, sd.latitude, sd.longitude, rot);
}
this.addMatchingData(curSquare, starData);
curLatitude = sd.latitude;
curLongitude = sd.longitude;
}
// Go one step North from first square;
{
curSquare = firstSquare;
float newLatitude = 38 + 9;
float newLongitude = -122;
log("buildEarth: building lat="+newLatitude+" long="+newLongitude);
Vector3f rot = calcRequiredRotation(curSquare, starData,
starCatalog, newLatitude, newLongitude);
if (rot == null) {
log("buildEarth: could not place next square!");
}
curSquare =
addRotatedAdjacentSquare(curSquare, newLatitude, newLongitude, rot);
this.addMatchingData(curSquare, starData);
curLatitude = newLatitude;
curLongitude = newLongitude;
}
// From here, keep exploring, relying on the synthetic catalog.
this.buildLatitudeStrip(curSquare, +9, starData, starCatalog);
this.buildLatitudeStrip(curSquare, -9, starData, starCatalog);
this.buildLongitudeStrip(curSquare, +9, starData, starCatalog);
this.buildLongitudeStrip(curSquare, -9, starData, starCatalog);
this.redrawCanvas();
log("buildEarth: finished using star data");
}
/** Build squares by going North or South from a starting square
* until we add 20 or we can't add any more. At each spot, also
* build latitude strips in both directions. */
private void buildLongitudeStrip(SurfaceSquare startSquare,
float deltaLatitude,
StarData[] starData,
StarCatalog[] starCatalog)
{
float curLatitude = startSquare.latitude;
float curLongitude = startSquare.longitude;
SurfaceSquare curSquare = startSquare;
while (true) {
float newLatitude = curLatitude + deltaLatitude;
if (!( -90 < newLatitude && newLatitude < 90 )) {
// Do not go past the poles.
break;
}
float newLongitude = curLongitude;
log("buildEarth: building lat="+newLatitude+" long="+newLongitude);
Vector3f rot = calcRequiredRotation(curSquare, starData,
starCatalog, newLatitude, newLongitude);
if (rot == null) {
log("buildEarth: could not place next square!");
break;
}
curSquare =
addRotatedAdjacentSquare(curSquare, newLatitude, newLongitude, rot);
this.addMatchingData(curSquare, starData);
curLatitude = newLatitude;
curLongitude = newLongitude;
// Also build strips in each direction.
this.buildLatitudeStrip(curSquare, +9, starData, starCatalog);
this.buildLatitudeStrip(curSquare, -9, starData, starCatalog);
}
}
/** Build squares by going East or West from a starting square
* until we add 20 or we can't add any more. */
private void buildLatitudeStrip(SurfaceSquare startSquare,
float deltaLongitude,
StarData[] starData,
StarCatalog[] starCatalog)
{
float curLatitude = startSquare.latitude;
float curLongitude = startSquare.longitude;
SurfaceSquare curSquare = startSquare;
for (int i=0; i < 20; i++) {
float newLatitude = curLatitude;
float newLongitude = FloatUtil.modulus2(curLongitude + deltaLongitude, -180, 180);
log("buildEarth: building lat="+newLatitude+" long="+newLongitude);
Vector3f rot = calcRequiredRotation(curSquare, starData,
starCatalog, newLatitude, newLongitude);
if (rot == null) {
log("buildEarth: could not place next square!");
break;
}
curSquare =
addRotatedAdjacentSquare(curSquare, newLatitude, newLongitude, rot);
this.addMatchingData(curSquare, starData);
curLatitude = newLatitude;
curLongitude = newLongitude;
}
}
/** Cause the GL canvas to redraw. */
private void redrawCanvas()
{
// I want to be able to liberally call this, including before
// things are fully initialized, so check for null.
if (this.glCanvas != null) {
this.glCanvas.display();
}
}
/** Add a square adjacent to 'old', positioned at the given latitude
* and longitude, with orientation changed by 'rotation'. */
private SurfaceSquare addRotatedAdjacentSquare(
SurfaceSquare old,
float newLatitude,
float newLongitude,
Vector3f rotation)
{
// Calculate local East for 'old'.
Vector3f oldEast = old.north.cross(old.up).normalize();
// Calculate the angle along the spherical Earth subtended
// by the arc from 'old' to the new coordinates.
float arcAngleDegrees = FloatUtil.sphericalSeparationAngle(
old.longitude, old.latitude,
newLongitude, newLatitude);
// Calculate the distance along the surface that separates
// these points by using the fact that there are 111 km per
// degree of arc.
float distanceKm = (float)(111.0 * arcAngleDegrees);
// Get lat/long deltas.
float deltaLatitude = newLatitude - old.latitude;
float deltaLongitude = FloatUtil.modulus2(
newLongitude - old.longitude, -180, 180);
// If we didn't move, just return the old square.
if (deltaLongitude == 0 && deltaLatitude == 0) {
return old;
}
// Compute the new orientation vectors by rotating
// the old ones by the given amount.
Vector3f newNorth = old.north.rotateAA(rotation);
Vector3f newUp = old.up.rotateAA(rotation);
Vector3f newEast = newNorth.cross(newUp).normalize();
// Calculate the average compass heading, in degrees North
// of East, used to go from the old
// location to the new. This is rather crude because it
// doesn't properly account for the fact that longitude
// lines get closer together near the poles.
float headingDegrees = FloatUtil.radiansToDegreesf(
(float)Math.atan2(deltaLatitude, deltaLongitude));
// For both old and new, calculate a unit vector for the
// travel direction. Then average them to approximate the
// average travel direction.
Vector3f oldTravel = oldEast.rotate(headingDegrees, old.up);
Vector3f newTravel = newEast.rotate(headingDegrees, newUp);
Vector3f avgTravel = oldTravel.plus(newTravel).normalize();
// Calculate the new square's center as 'distance' units
// along 'avgTravel'.
Vector3f newCenter = old.center.plus(
avgTravel.times(distanceKm * SPACE_UNITS_PER_KM));
// Make the new square and add it to the list.
SurfaceSquare ret = new SurfaceSquare(
newCenter, newNorth, newUp,
old.sizeKm,
newLatitude, // did not change
newLongitude,
Vector3f.composeRotations(old.rotationFromNominal, rotation));
this.addSurfaceSquare(ret);
return ret;
}
/** Add to 'square.starData' all entries of 'starData' that have
* the same latitude and longitude. */
private void addMatchingData(SurfaceSquare square, StarData[] starData)
{
for (StarData sd : starData) {
if (square.latitude == sd.latitude &&
square.longitude == sd.longitude)
{
square.starData.add(sd);
}
}
}
/** Compare star data for 'startSquare' and for the given new
* latitude and longitude. Return a rotation vector that will
* transform the orientation of 'startSquare' to match the
* best surface for a new square at the new location. The
* vector's length is the amount of rotation in degrees.
*
* Returns null if there are not enough stars in common. */
private Vector3f calcRequiredRotation(
SurfaceSquare startSquare,
StarData[] starData,
StarCatalog[] starCatalog,
float newLatitude,
float newLongitude)
{
// Set of stars visible at the start and end squares and
// above 20 degrees above the horizon.
HashMap<String, Vector3f> startStars =
getVisibleStars(starData, starCatalog, startSquare.latitude, startSquare.longitude);
HashMap<String, Vector3f> endStars =
getVisibleStars(starData, starCatalog, newLatitude, newLongitude);
// Current best rotation and average difference.
Vector3f currentRotation = new Vector3f(0,0,0);
// Iteratively refine the current rotation by computing the
// average correction rotation and applying it until that
// correction drops below a certain threshold.
for (int iterationCount = 0; iterationCount < 1000; iterationCount++) {
// Accumulate the vector sum of all the rotation difference
// vectors as well as the max length.
Vector3f diffSum = new Vector3f(0,0,0);
float maxDiffLength = 0;
int diffCount = 0;
for (HashMap.Entry<String, Vector3f> e : startStars.entrySet()) {
String starName = e.getKey();
Vector3f startVector = e.getValue();
Vector3f endVector = endStars.get(starName);
if (endVector == null) {
continue;
}
// Both vectors must first be rotated the way the start
// surface was rotated since its creation so that when
// we compute the final required rotation, it can be
// applied to the start surface in its existing orientation,
// not the norminal orientation that the star vectors have
// before I do this.
startVector = startVector.rotateAA(startSquare.rotationFromNominal);
endVector = endVector.rotateAA(startSquare.rotationFromNominal);
// Calculate a difference rotation vector from the
// rotated end vector to the start vector. Rotating
// the end star in one direction is like rotating
// the start terrain in the opposite direction.
Vector3f rot = endVector.rotateAA(currentRotation)
.rotationToBecome(startVector);
// Accumulate it.
diffSum = diffSum.plus(rot);
maxDiffLength = (float)Math.max(maxDiffLength, rot.length());
diffCount++;
}
if (diffCount < 2) {
log("reqRot: not enough stars");
return null;
}
// Calculate the average correction rotation.
Vector3f avgDiff = diffSum.times(1.0f / diffCount);
// If the correction angle is small enough, stop. For any set
// of observations, we should be able to drive the average
// difference arbitrarily close to zero (this is like finding
// the centroid, except in spherical rather than flat space).
// The real question is whether the *maximum* difference is
// large enough to indicate that the data is inconsistent.
if (avgDiff.length() < 0.001) {
log("reqRot finished: iters="+iterationCount+
" avgDiffLen="+avgDiff.length()+
" maxDiffLength="+maxDiffLength+
" diffCount="+diffCount);
if (maxDiffLength > 0.2) {
// For the data I am working with, I estimate it is
// accurate to within 0.2 degrees. Consequently,
// there should not be a max difference that large.
log("reqRot: WARNING: maxDiffLength greater than 0.2");
}
return currentRotation;
}
// Otherwise, apply it to the current rotation and
// iterate again.
currentRotation = currentRotation.plus(avgDiff);
}
log("reqRot: hit iteration limit!");
return currentRotation;
}
/** For every star in 'starData' that matches 'latitude' and
* 'longitude', and has an elevation of at least 20 degrees,
* add it to a map from star name to azEl vector. */
private HashMap<String, Vector3f> getVisibleStars(
StarData[] starData,
StarCatalog[] starCatalog,
float latitude,
float longitude)
{
HashMap<String, Vector3f> ret = new HashMap<String, Vector3f>();
// First use any manual data I have.
for (StarData sd : starData) {
if (sd.latitude == latitude &&
sd.longitude == longitude &&
sd.elevation >= 20)
{
ret.put(sd.name,
azimuthElevationToVector(sd.azimuth, sd.elevation));
}
}
// Then use the synthetic data.
for (StarCatalog sc : starCatalog) {
if (ret.containsKey(sc.name)) {
continue;
}
// Synthesize an observation.
StarData sd = sc.makeObservation(1488772800.0 /*2017-03-05 20:00 -08:00*/,
latitude, longitude);
if (sd.elevation >= 20) {
ret.put(sd.name,
azimuthElevationToVector(sd.azimuth, sd.elevation));
}
}
return ret;
}
/** Convert a pair of azimuth and elevation, in degrees, to a unit
* vector that points in the same direction, in a coordinate system
* where 0 degrees azimuth is -Z, East is +X, and up is +Y. */
private Vector3f azimuthElevationToVector(float azimuth, float elevation)
{
// Start by pointing a vector at 0 degrees azimuth (North).
Vector3f v = new Vector3f(0, 0, -1);
// Now rotate it up to align with elevation.
v = v.rotate(elevation, new Vector3f(1, 0, 0));
// Now rotate it East to align with azimuth.
v = v.rotate(-azimuth, new Vector3f(0, 1, 0));
return v;
}
/** Add a square to 'surfaceSquares'. */
private void addSurfaceSquare(SurfaceSquare s)
{
this.surfaceSquares.add(s);
log("added square: "+s);
}
/** Draw what is in 'surfaceSquares'. */
private void drawEarthSurface(GL2 gl)
{
for (SurfaceSquare s : this.surfaceSquares) {
this.drawSquare(gl, s);
}
}
/** Draw one surface square. */
private void drawSquare(GL2 gl, SurfaceSquare s)
{
Vector3f east = s.north.cross(s.up);
// Size of the square in 3D coordinates.
float squareSize = s.sizeKm * SPACE_UNITS_PER_KM;
// Scale north and east by half of desired square size.
Vector3f n = s.north.normalize().times(squareSize/2);
Vector3f e = east.normalize().times(squareSize/2);
Vector3f nw = s.center.plus(n).minus(e);
Vector3f sw = s.center.minus(n).minus(e);
Vector3f ne = s.center.plus(n).plus(e);
Vector3f se = s.center.minus(n).plus(e);
if (this.drawCompasses) {
this.drawCompassRect(gl, nw, sw, ne, se);
}
else {
this.drawEarthMapRect(gl, nw, sw, ne, se, s.latitude, s.longitude, s.sizeKm);
}
// Also draw a surface normal.
if (this.drawSurfaceNormals) {
gl.glDisable(GL.GL_TEXTURE_2D);
gl.glBegin(GL.GL_LINES);
glMaterialColor3f(gl, 0.5f, 0.5f, 0); // Dark yellow
gl.glNormal3f(0,1,0);
gl.glVertex3fv(s.center.getArray(), 0);
gl.glVertex3fv(s.center.plus(s.up).getArray(), 0);
gl.glEnd();
}
// Draw a line to celestial North.
if (this.drawCelestialNorth) {
gl.glDisable(GL.GL_TEXTURE_2D);
gl.glBegin(GL.GL_LINES);
glMaterialColor3f(gl, 1, 0, 0); // Red
gl.glNormal3f(0,1,0);
gl.glVertex3fv(s.center.getArray(), 0);
Vector3f celestialNorth = s.north.rotate(s.latitude, east);
gl.glVertex3fv(s.center.plus(celestialNorth.times(5)).getArray(), 0);
gl.glEnd();
}
}
/** Draw a 2D "+" in the [0,1] box. */
private void drawPlus(GL2 gl)
{
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(.2f, .5f);
gl.glVertex2f(.8f, .5f);
gl.glVertex2f(.5f, .2f);
gl.glVertex2f(.5f, .8f);
gl.glEnd();
}
/** Draw a 2D "X" in the [0,1] box. */
private void drawX(GL2 gl)
{
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(0f, 0f);
gl.glVertex2f(1f, 1f);
gl.glVertex2f(0f, 1f);
gl.glVertex2f(1f, 0f);
gl.glEnd();
}
/** Draw a 2D "Y" in the [0,1] box. */
private void drawY(GL2 gl)
{
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(.5f, 0f);
gl.glVertex2f(.5f, .5f);
gl.glVertex2f(.5f, .5f);
gl.glVertex2f(0f, 1f);
gl.glVertex2f(.5f, .5f);
gl.glVertex2f(1f, 1f);
gl.glEnd();
}
/** Draw a 2D "Z" in the [0,1] box. */
private void drawZ(GL2 gl)
{
gl.glBegin(GL.GL_LINE_STRIP);
gl.glVertex2f(0f, 1f);
gl.glVertex2f(1f, 1f);
gl.glVertex2f(0f, 0f);
gl.glVertex2f(1f, 0f);
gl.glEnd();
}
/** Called when the window is resized. The superclass does
* basic resize handling, namely adjusting the viewport to
* fill the canvas, so we do not need to do anything more. */
@Override
public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
//log("reshape");
// Just keep track of the aspect ratio. During display, we will
// adjust the camera view in a corresponding way.
this.aspectRatio = (float)width / (float)height;
}
/** Update state variables to reflect passage of time. */
private void updatePhysics()
{
// Everything that happens should be scaled according to how
// much real time has elapsed since the last physics update
// so that the motion appears smooth even when the frames per
// second varies.
long newMillis = System.currentTimeMillis();
float elapsedSeconds = (newMillis - this.lastPhysicsUpdateMillis) / 1000.0f;
// Update camera velocity based on move keys.
boolean moving = false;
for (MoveDirection md : MoveDirection.values()) {
if (this.moveKeys[md.ordinal()]) {
moving = true;
// Rotate the direction of 'md' according to the
// current camera azimuth.
Vector3f rd = md.direction.rotate(this.cameraAzimuthDegrees,
new Vector3f(0, +1, 0));
// Scale it per camera acceleration and elapsed time.
Vector3f srd = rd.times(CAMERA_ACCELERATION * elapsedSeconds);
// Apply that to the camera velocity.
this.cameraVelocity = this.cameraVelocity.plus(srd);
}
}
// Update camera position.
if (!this.cameraVelocity.isZero()){
// Move camera.
this.cameraPosition =
this.cameraPosition.plus(this.cameraVelocity.times(elapsedSeconds));
// Apply friction to the velocity.
Vector3f v = this.cameraVelocity;
float speed = (float)v.length();
float maxFrictionAccel = moving?
MOVING_CAMERA_FRICTION : STATIONARY_CAMERA_FRICTION;
maxFrictionAccel *= elapsedSeconds;
// Remove up to maxFrictionAccel speed.
if (speed < maxFrictionAccel) {
this.cameraVelocity = new Vector3f(0,0,0);
}
else {
this.cameraVelocity =
v.minus(v.normalize().times(maxFrictionAccel));
}
}
this.setStatusLabel();
this.lastPhysicsUpdateMillis = newMillis;
}
public static void main(String[] args)
{
(new EarthShape()).setVisible(true);
}
/** Map from KeyEvent key code to corresponding movement
* direction, or null if it does not correspond. */
private static MoveDirection keyCodeToMoveDirection(int code)
{
switch (code) {
case KeyEvent.VK_A: return MoveDirection.MD_LEFT;
case KeyEvent.VK_D: return MoveDirection.MD_RIGHT;
case KeyEvent.VK_SPACE: return MoveDirection.MD_UP;
case KeyEvent.VK_Z: return MoveDirection.MD_DOWN;
case KeyEvent.VK_W: return MoveDirection.MD_FORWARD;
case KeyEvent.VK_S: return MoveDirection.MD_BACKWARD;
default: return null;
}
}
@Override
public void keyPressed(KeyEvent ev) {
//log("key pressed: "+ev);
MoveDirection md = EarthShape.keyCodeToMoveDirection(ev.getKeyCode());
if (md != null) {
this.moveKeys[md.ordinal()] = true;
}
switch (ev.getKeyCode()) {
case KeyEvent.VK_C:
this.toggleDrawCompasses();
break;
case KeyEvent.VK_L:
this.buildEarthSurfaceWithLatLong();
break;
case KeyEvent.VK_R:
this.randomWalkEarthSurface();
break;
case KeyEvent.VK_T:
this.buildEarthSurfaceFromStarData();
break;
default:
break;
}
}
/** Toggle the 'drawCompasses' flag, then update state and redraw. */
private void toggleDrawCompasses()
{
log("toggleDrawCompasses");
this.drawCompasses = !this.drawCompasses;
this.setStatusLabel();
this.redrawCanvas();
}
/** Toggle the 'drawSurfaceNormals' flag. */
private void toggleDrawSurfaceNormals()
{
this.drawSurfaceNormals = !this.drawSurfaceNormals;
this.setStatusLabel();
this.redrawCanvas();
}
/** Toggle the 'drawCelestialNorth' flag. */
private void toggleDrawCelestialNorth()
{
this.drawCelestialNorth = !this.drawCelestialNorth;
this.setStatusLabel();
this.redrawCanvas();
}
/** Set the status label text to reflect other state variables.
* This also updates the state of stateful menu items. */
private void setStatusLabel()
{
StringBuilder sb = new StringBuilder();
sb.append("camera="+this.cameraPosition);
sb.append(", az="+this.cameraAzimuthDegrees);
sb.append(", pch="+this.cameraPitchDegrees);
sb.append(", tex="+(this.drawCompasses? "compass" : "earth"));
if (this.fpsCameraMode) {
sb.append(", FPS mode (click to exit)");
}
this.statusLabel.setText(sb.toString());
this.drawCompassesCBItem.setState(this.drawCompasses);
this.drawSurfaceNormalsCBItem.setState(this.drawSurfaceNormals);
this.drawCelestialNorthCBItem.setState(this.drawCelestialNorth);
}
@Override
public void keyReleased(KeyEvent ev) {
MoveDirection md = EarthShape.keyCodeToMoveDirection(ev.getKeyCode());
if (md != null) {
this.moveKeys[md.ordinal()] = false;
}
}
@Override
public void keyTyped(KeyEvent ev) {}
@Override
public void mouseClicked(MouseEvent ev) {}
@Override
public void mouseEntered(MouseEvent ev) {}
@Override
public void mouseExited(MouseEvent ev) {}
@Override
public void mousePressed(MouseEvent ev) {
log("mouse pressed: ev="+ev);
if (ev.getButton() == MouseEvent.BUTTON1) {
this.fpsCameraMode = !this.fpsCameraMode;
this.setStatusLabel();
if (this.fpsCameraMode) {
// When transition into FPS mode, move the mouse
// to the center and hide it.
this.centerMouse(ev);
ev.getComponent().setCursor(this.blankCursor);
// Only run the animator thread in FPS mode.
this.animator.start();
}
else {
// Un-hide the mouse cursor.
ev.getComponent().setCursor(null);
// And stop the animator.
this.animator.stop();
// Also kill any latent camera motion.
this.cameraVelocity = new Vector3f(0,0,0);
}
}
}
/** Move the mouse to the center of the component where the given
* event originated, and also return that center point in screen
* coordinates. */
private Point centerMouse(MouseEvent ev)
{
// Calculate the screen coordinates of the center of the
// clicked component.
Point absComponentLoc = ev.getComponent().getLocationOnScreen();
Dimension comDim = ev.getComponent().getSize();
int cx = absComponentLoc.x + comDim.width/2;
int cy = absComponentLoc.y + comDim.height/2;
// Move the mouse to the center of the clicked component.
robotObject.mouseMove(cx, cy);
return new Point(cx, cy);
}
@Override
public void mouseReleased(MouseEvent ev) {}
@Override
public void mouseDragged(MouseEvent ev) {}
@Override
public void mouseMoved(MouseEvent ev) {
//log("mouse moved: ev="+ev);
if (this.fpsCameraMode) {
// Get the screen coordinate where mouse is now.
Point mouseAbsLoc = ev.getLocationOnScreen();
// Move the mouse to the center of the clicked component,
// and get that location.
Point c = this.centerMouse(ev);
// Calculate delta.
int dx = mouseAbsLoc.x - c.x;
int dy = mouseAbsLoc.y - c.y;
// The act of re-centering the mouse causes an extra
// mouse movement event to fire with a zero delta.
// Discard it as a minor optimization.
if (dx == 0 && dy == 0) {
return;
}
//log("FPS: dx="+dx+", dy="+dy);
// Rotate the camera based on mouse movement.
float newAz = this.cameraAzimuthDegrees - dx * CAMERA_HORIZONTAL_SENSITIVITY;
// Normalize the azimuth to [0,360).
this.cameraAzimuthDegrees = FloatUtil.modulus(newAz, 360);
// Rotate the pitch.
float newPitch = this.cameraPitchDegrees + dy * CAMERA_VERTICAL_SENSITIVITY;
this.cameraPitchDegrees = FloatUtil.clamp(newPitch, -90, 90);
this.setStatusLabel();
}
}
} |
package seedu.address.logic;
import com.google.common.eventbus.Subscribe;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import seedu.address.commons.core.Config;
import seedu.address.commons.core.EventsCenter;
import seedu.address.logic.commands.*;
import seedu.address.commons.events.ui.JumpToListRequestEvent;
import seedu.address.commons.events.ui.ShowHelpRequestEvent;
import seedu.address.commons.events.model.TaskManagerChangedEvent;
import seedu.address.model.Model;
import seedu.address.model.ModelManager;
import seedu.address.model.ReadOnlyTaskManager;
import seedu.address.model.TaskManager;
import seedu.address.model.person.*;
import seedu.address.model.tag.Tag;
import seedu.address.model.tag.UniqueTagList;
import seedu.address.storage.StorageManager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static seedu.address.commons.core.Messages.*;
public class LogicManagerTest {
@Rule
public TemporaryFolder saveFolder = new TemporaryFolder();
private Model model;
private Logic logic;
private Config config;
//These are for checking the correctness of the events raised
private ReadOnlyTaskManager latestSavedTaskManager;
private boolean helpShown;
private int targetedJumpIndex;
@Subscribe
private void handleLocalModelChangedEvent(TaskManagerChangedEvent abce) {
latestSavedTaskManager = new TaskManager(abce.data);
}
@Subscribe
private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) {
helpShown = true;
}
@Subscribe
private void handleJumpToListRequestEvent(JumpToListRequestEvent je) {
targetedJumpIndex = je.targetIndex;
}
@Before
public void setup() {
model = new ModelManager();
String tempTaskManagerFile = saveFolder.getRoot().getPath() + "TempTaskManager.xml";
String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json";
logic = new LogicManager(model, new StorageManager(tempTaskManagerFile, tempPreferencesFile), new Config());
EventsCenter.getInstance().registerHandler(this);
latestSavedTaskManager = new TaskManager(model.getTaskManager()); // last saved assumed to be up to date before.
helpShown = false;
targetedJumpIndex = -1; // non yet
}
@After
public void teardown() {
EventsCenter.clearSubscribers();
}
@Test
public void execute_invalid() throws Exception {
String invalidCommand = " ";
assertCommandBehavior(invalidCommand,
String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
/**
* Executes the command and confirms that the result message is correct.
* Both the 'task manager' and the 'last shown list' are expected to be empty.
* @see #assertCommandBehavior(String, String, ReadOnlyTaskManager, List)
*/
private void assertCommandBehavior(String inputCommand, String expectedMessage) throws Exception {
assertCommandBehavior(inputCommand, expectedMessage, new TaskManager(), Collections.emptyList());
}
/**
* Executes the command and confirms that the result message is correct and
* also confirms that the following three parts of the LogicManager object's state are as expected:<br>
* - the internal task manager data are same as those in the {@code expectedTaskManager} <br>
* - the backing list shown by UI matches the {@code shownList} <br>
* - {@code expectedTaskManager} was saved to the storage file. <br>
*/
private void assertCommandBehavior(String inputCommand, String expectedMessage,
ReadOnlyTaskManager expectedTaskManager,
List<? extends ReadOnlyTask> expectedShownList) throws Exception {
//Execute the command
CommandResult result = logic.execute(inputCommand);
//Confirm the ui display elements should contain the right data
assertEquals(expectedMessage, result.feedbackToUser);
assertEquals(expectedShownList, model.getFilteredTaskList());
//Confirm the state of data (saved and in-memory) is as expected
assertEquals(expectedTaskManager, model.getTaskManager());
assertEquals(expectedTaskManager, latestSavedTaskManager);
}
@Test
public void execute_unknownCommandWord() throws Exception {
String unknownCommand = "uicfhmowqewca";
assertCommandBehavior(unknownCommand, MESSAGE_UNKNOWN_COMMAND);
}
@Test
public void execute_help() throws Exception {
assertCommandBehavior("help", HelpCommand.SHOWING_HELP_MESSAGE);
assertTrue(helpShown);
}
@Test
public void execute_exit() throws Exception {
assertCommandBehavior("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT);
}
@Test
public void execute_clear() throws Exception {
TestDataHelper helper = new TestDataHelper();
model.addTask(helper.generateTask(1));
model.addTask(helper.generateTask(2));
model.addTask(helper.generateTask(3));
assertCommandBehavior("clear", ClearCommand.MESSAGE_SUCCESS, new TaskManager(), Collections.emptyList());
}
@Test
public void execute_add_invalidArgsFormat() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE);
assertCommandBehavior(
"add #me", expectedMessage);
assertCommandBehavior(
"add t/10-20 ", expectedMessage);
}
@Test
public void execute_add_invalidTaskData() throws Exception {
//assertCommandBehavior(
//"add []\\[;] d/20-10-2016 t/13:00 #one", Content.MESSAGE_CONTENT_CONSTRAINTS);
assertCommandBehavior(
"add Valid Content d/notvaliddate t/14:00 #two", TaskDate.MESSAGE_DATE_CONSTRAINTS);
assertCommandBehavior(
"add Valid Content d/20-10-2016 t/notvalidtime #three", TaskTime.MESSAGE_TIME_CONSTRAINTS);
assertCommandBehavior(
"add Valid Content d/20-10-2016 t/13:00 #[][]", Tag.MESSAGE_TAG_CONSTRAINTS);
}
@Test
public void execute_add_successful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.homework();
TaskManager expectedTM = new TaskManager();
expectedTM.addTask(toBeAdded);
// execute command and verify result
assertCommandBehavior(helper.generateAddCommand(toBeAdded),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded),
expectedTM,
expectedTM.getTaskList());
}
@Test
public void execute_addDuplicate_notAllowed() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.homework();
TaskManager expectedTM = new TaskManager();
expectedTM.addTask(toBeAdded);
// setup starting state
model.addTask(toBeAdded); // task already in internal task manager
// execute command and verify result
assertCommandBehavior(
helper.generateAddCommand(toBeAdded),
AddCommand.MESSAGE_DUPLICATE_TASK,
expectedTM,
expectedTM.getTaskList());
}
@Test
public void execute_list_showsAllTasks() throws Exception {
// prepare expectations
TestDataHelper helper = new TestDataHelper();
TaskManager expectedTM = helper.generateTaskManager(2);
List<? extends ReadOnlyTask> expectedList = expectedTM.getTaskList();
// prepare task manager state
helper.addToModel(model, 2);
assertCommandBehavior("list",
ListCommand.MESSAGE_SUCCESS,
expectedTM,
expectedList);
}
/**
* Confirms the 'invalid argument index number behaviour' for the given command
* targeting a single task in the shown list, using visible index.
* @param commandWord to test assuming it targets a single task in the last shown list based on visible index.
*/
private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception {
assertCommandBehavior(commandWord , expectedMessage); //index missing
assertCommandBehavior(commandWord + " +1", expectedMessage); //index should be unsigned
assertCommandBehavior(commandWord + " -1", expectedMessage); //index should be unsigned
assertCommandBehavior(commandWord + " 0", expectedMessage); //index cannot be 0
assertCommandBehavior(commandWord + " not_a_number", expectedMessage);
}
/**
* Confirms the 'invalid argument index number behaviour' for the given command
* targeting a single task in the shown list, using visible index.
* @param commandWord to test assuming it targets a single task in the last shown list based on visible index.
*/
private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception {
String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX;
TestDataHelper helper = new TestDataHelper();
List<Task> taskList = helper.generateTaskList(2);
// set TB state to 2 tasks
model.resetData(new TaskManager());
for (Task p : taskList) {
model.addTask(p);
}
assertCommandBehavior(commandWord + " 3", expectedMessage, model.getTaskManager(), taskList);
}
@Test
public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage);
}
@Test
public void execute_selectIndexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("select");
}
@Test
public void execute_select_jumpsToCorrectTask() throws Exception {
TestDataHelper helper = new TestDataHelper();
List<Task> threeTasks = helper.generateTaskList(3);
TaskManager expectedTM = helper.generateTaskManager(threeTasks);
helper.addToModel(model, threeTasks);
assertCommandBehavior("select 2",
String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2),
expectedTM,
expectedTM.getTaskList());
assertEquals(1, targetedJumpIndex);
assertEquals(model.getFilteredTaskList().get(1), threeTasks.get(1));
}
@Test
public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage);
}
@Test
public void execute_deleteIndexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("delete");
}
@Test
public void execute_delete_removesCorrectTask() throws Exception {
TestDataHelper helper = new TestDataHelper();
List<Task> threeTasks = helper.generateTaskList(3);
TaskManager expectedTM = helper.generateTaskManager(threeTasks);
expectedTM.removeTask(threeTasks.get(1));
helper.addToModel(model, threeTasks);
assertCommandBehavior("delete 2",
String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, threeTasks.get(1)),
expectedTM,
expectedTM.getTaskList());
}
@Test
public void execute_find_invalidArgsFormat() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE);
assertCommandBehavior("find ", expectedMessage);
}
@Test
public void execute_find_onlyMatchesFullWordsInNames() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task tTarget1 = helper.generateTaskWithName("bla bla KEY bla");
Task tTarget2 = helper.generateTaskWithName("bla KEY bla bceofeia");
Task t1 = helper.generateTaskWithName("KE Y");
Task t2 = helper.generateTaskWithName("KEYKEYKEY sduauo");
List<Task> fourTasks = helper.generateTaskList(t1, tTarget1, t2, tTarget2);
TaskManager expectedTM = helper.generateTaskManager(fourTasks);
List<Task> expectedList = helper.generateTaskList(tTarget1, tTarget2);
helper.addToModel(model, fourTasks);
assertCommandBehavior("find KEY",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedTM,
expectedList);
}
@Test
public void execute_find_isNotCaseSensitive() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task t1 = helper.generateTaskWithName("bla bla KEY bla");
Task t2 = helper.generateTaskWithName("bla KEY bla bceofeia");
Task t3 = helper.generateTaskWithName("key key");
Task t4 = helper.generateTaskWithName("KEy sduauo");
List<Task> fourTasks = helper.generateTaskList(t3, t1, t4, t2);
TaskManager expectedTM = helper.generateTaskManager(fourTasks);
List<Task> expectedList = fourTasks;
helper.addToModel(model, fourTasks);
assertCommandBehavior("find KEY",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedTM,
expectedList);
}
@Test
public void execute_find_matchesIfAnyKeywordPresent() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task tTarget1 = helper.generateTaskWithName("bla bla KEY bla");
Task tTarget2 = helper.generateTaskWithName("bla rAnDoM bla bceofeia");
Task tTarget3 = helper.generateTaskWithName("key key");
Task t1 = helper.generateTaskWithName("sduauo");
List<Task> fourTasks = helper.generateTaskList(tTarget1, t1, tTarget2, tTarget3);
TaskManager expectedTM = helper.generateTaskManager(fourTasks);
List<Task> expectedList = helper.generateTaskList(tTarget1, tTarget2, tTarget3);
helper.addToModel(model, fourTasks);
assertCommandBehavior("find key rAnDoM",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedTM,
expectedList);
}
/**
* A utility class to generate test data.
*/
class TestDataHelper{
Task homework() throws Exception {
Content content = new Content("Do Homework");
TaskDate taskdate = new TaskDate("21-02-2016");
TaskTime tasktime = new TaskTime("13:00");
Tag tag1 = new Tag("tag1");
Tag tag2 = new Tag("tag2");
UniqueTagList tags = new UniqueTagList(tag1, tag2);
return new Task(content, taskdate, tasktime, tags);
}
/**
* Generates a valid person using the given seed.
* Running this function with the same parameter values guarantees the returned person will have the same state.
* Each unique seed will generate a unique Person object.
*
* @param seed used to generate the person data field values
*/
Task generateTask(int seed) throws Exception {
return new Task(
new Content("Content " + seed),
new TaskDate("1" + Math.abs(seed) + "-0" + Math.abs(seed) + "-2016"),
new TaskTime("1" + Math.abs(seed) + ":0" + Math.abs(seed)),
new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1)))
);
}
/** Generates the correct add command based on the task given */
String generateAddCommand(Task t) {
StringBuffer cmd = new StringBuffer();
cmd.append("add ");
cmd.append(t.getContent().value);
cmd.append(" d/").append(t.getDate().dateString);
cmd.append(" t/").append(t.getTime().timeString);
UniqueTagList tags = t.getTags();
for(Tag tg: tags){
cmd.append(" #").append(tg.tagName);
}
return cmd.toString();
}
/**
* Generates an TaskManager with auto-generated tasks.
*/
TaskManager generateTaskManager(int numGenerated) throws Exception{
TaskManager taskManager = new TaskManager();
addToTaskManager(taskManager, numGenerated);
return taskManager;
}
/**
* Generates an TaskManager based on the list of Tasks given.
*/
TaskManager generateTaskManager(List<Task> tasks) throws Exception{
TaskManager taskManager = new TaskManager();
addToTaskManager(taskManager, tasks);
return taskManager;
}
/**
* Adds auto-generated Task objects to the given TaskManager
* @param taskManager The TaskManager to which the Tasks will be added
*/
void addToTaskManager(TaskManager taskManager, int numGenerated) throws Exception{
addToTaskManager(taskManager, generateTaskList(numGenerated));
}
/**
* Adds the given list of Tasks to the given TaskManager
*/
void addToTaskManager(TaskManager taskManager, List<Task> tasksToAdd) throws Exception{
for(Task p: tasksToAdd){
taskManager.addTask(p);
}
}
/**
* Adds auto-generated Task objects to the given model
* @param model The model to which the Tasks will be added
*/
void addToModel(Model model, int numGenerated) throws Exception{
addToModel(model, generateTaskList(numGenerated));
}
/**
* Adds the given list of Tasks to the given model
*/
void addToModel(Model model, List<Task> tasksToAdd) throws Exception{
for(Task p: tasksToAdd){
model.addTask(p);
}
}
/**
* Generates a list of Tasks based on the flags.
*/
List<Task> generateTaskList(int numGenerated) throws Exception{
List<Task> tasks = new ArrayList<>();
for(int i = 1; i <= numGenerated; i++){
tasks.add(generateTask(i));
}
return tasks;
}
List<Task> generateTaskList(Task... tasks) {
return Arrays.asList(tasks);
}
/**
* Generates a Task object with given name. Other fields will have some dummy values.
*/
Task generateTaskWithName(String name) throws Exception {
return new Task(
new Content(name),
new TaskDate("13-02-2016"),
new TaskTime("13:00"),
new UniqueTagList(new Tag("tag"))
);
}
}
} |
package net.chocolapod.lwjgfont.packager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Packager {
private static final byte[] buff = new byte [1024 * 1024];
private String resourceDir = "";
private String targetDir = "";
public void process(String distPath) throws IOException {
ZipOutputStream out = null;
try {
out = new ZipOutputStream(new FileOutputStream(distPath));
packageFile(targetDir, targetDir + File.separator, out);
packageFile(resourceDir, resourceDir + File.separator, out);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private void packageFile(String filePath, String filePathMask, ZipOutputStream out) throws IOException {
File file = new File(filePath);
if (file.isDirectory()) {
for (File child: file.listFiles()) {
packageFile(child.getPath(), filePathMask, out);
}
} else {
FileInputStream in = null;
int length;
String dstPath = file.getPath();
if (dstPath.startsWith(filePathMask)) {
dstPath = dstPath.substring(filePathMask.length());
}
// Windows \
// Jar /
if (File.separatorChar == '\\') {
dstPath = dstPath.replaceAll("\\\\", "/");
}
try {
in = new FileInputStream(file.getPath());
out.putNextEntry(new ZipEntry(dstPath));
while (0 < (length = in.read(buff))) {
out.write(buff, 0, length);
}
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public void setResourceDir(String resourceDir) {
this.resourceDir = resourceDir;
}
public void setTargetDir(String targetDir) {
this.targetDir = targetDir;
}
} |
package me.alex.jobs.listener;
import me.alex.jobs.Jobs;
import me.alex.jobs.config.JobsConfiguration;
import me.alex.jobs.config.container.Job;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Wolf;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageByProjectileEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityListener;
/**
* Plugin that monitors when things get killed by you and then pays you
*
* @author Alex
*
*/
public class JobsKillPaymentListener extends EntityListener{
private Jobs plugin;
public JobsKillPaymentListener(Jobs plugin) {
this.plugin = plugin;
}
/**
* Function that gets called whenever an entity gets damaged
*
* Must make sure that the entity is getting damaged by another entity first
* and that this damager is either a player or a player's wolf.
*
* Then it checks to see if the entity is actually dead and if it is to pay the killer
*/
public void onEntityDamage(EntityDamageEvent event){
// if event is not cancelled and entity isn't already dead.
if(!event.isCancelled() && !event.getEntity().isDead()){
Player damager;
LivingEntity victim;
if(event instanceof EntityDamageByProjectileEvent){
EntityDamageByProjectileEvent damageEvent = (EntityDamageByProjectileEvent)event;
if(damageEvent.getDamager() instanceof Player){
damager = (Player) damageEvent.getDamager();
}
else{
// hasn't been killed by a player shooting an arrow/snowball
return;
}
}
else if (event instanceof EntityDamageByEntityEvent){
EntityDamageByEntityEvent damageEvent = (EntityDamageByEntityEvent) event;
if(damageEvent.getDamager() instanceof Player){
damager = (Player) damageEvent.getDamager();
}
else if (damageEvent.getDamager() instanceof Wolf){
// wolf has an owner
if(((Wolf)damageEvent.getDamager()).getOwner() != null &&
((Wolf)damageEvent.getDamager()).getOwner() instanceof Player){
damager = (Player)((Wolf)damageEvent.getDamager()).getOwner();
}
else {
// wild wolf, don't care
return;
}
}
else {
// don't care
return;
}
}
else {
// don't care
return;
}
if(event.getEntity() instanceof LivingEntity){
victim = (LivingEntity)event.getEntity();
}
else{
// not interested
return;
}
if(victim.getHealth() <= 0){
// for all intensive purposes dead.
return;
}
if((JobsConfiguration.getInstance().getPermissions() == null || !JobsConfiguration.getInstance().getPermissions().isEnabled())
|| JobsConfiguration.getInstance().getPermissions().getHandler().has(damager, "jobs.world." + damager.getWorld().getName())){
// if victim would die
if(victim.getHealth() - event.getDamage() > 0){
// not dealth lethal damage
return;
}
// if near mob spawners.
if (nearMobSpawner(damager) || nearMobSpawner(victim)){
// near mob spawner, no payment or experience
return;
}
// pay
plugin.getPlayerJobInfo(damager).killed(victim.getClass().toString().replace("class ", "").trim());
// pay for jobs
if(victim instanceof Player){
for(Job temp: plugin.getPlayerJobInfo((Player)victim).getJobs()){
plugin.getPlayerJobInfo(damager).killed((victim.getClass().toString().replace("class ", "")+":"+temp.getName()).trim());
}
}
}
}
}
/**
* Function to check whether an entity is near a mob spawner
* @param entity - the entity to be checked
* @return true - near a mob spawner
* @return false - not near a mob spawner
*/
private boolean nearMobSpawner(LivingEntity entity){
int x = entity.getLocation().getBlockX();
int y = entity.getLocation().getBlockY();
int z = entity.getLocation().getBlockZ();
for(int a=0; a< 10; ++a){
for(int b=0; b< 10; ++b){
for(int c=0; c< 10; ++c){
if((entity.getWorld().getBlockAt(x-a,y-b,z-c).getTypeId() == 52)||
(entity.getWorld().getBlockAt(x+a,y+b,z+c).getTypeId() == 52)){
return true;
}
}
}
}
return false;
}
} |
package seedu.manager.logic;
import com.google.common.eventbus.Subscribe;
import seedu.manager.commons.core.CommandWord.Commands;
import seedu.manager.commons.core.EventsCenter;
import seedu.manager.commons.core.Messages;
import seedu.manager.commons.events.model.TaskManagerChangedEvent;
import seedu.manager.commons.events.ui.JumpToTagListRequestEvent;
import seedu.manager.commons.events.ui.JumpToTaskListRequestEvent;
import seedu.manager.commons.events.ui.ShowHelpRequestEvent;
import seedu.manager.commons.exceptions.IllegalValueException;
import seedu.manager.logic.Logic;
import seedu.manager.logic.LogicManager;
import seedu.manager.logic.commands.*;
import seedu.manager.logic.commands.SortCommand.SortComparators;
import seedu.manager.logic.parser.ExtensionParser;
import seedu.manager.model.TaskManager;
import seedu.manager.model.Model;
import seedu.manager.model.ModelManager;
import seedu.manager.model.ReadOnlyTaskManager;
import seedu.manager.model.task.*;
import seedu.manager.model.task.Task.TaskProperties;
import seedu.manager.storage.StorageManager;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static seedu.manager.commons.core.Messages.*;
public class LogicManagerTest {
@Rule
public TemporaryFolder saveFolder = new TemporaryFolder();
private Model model;
private Logic logic;
//These are for checking the correctness of the events raised
private ReadOnlyTaskManager latestSavedTaskManager;
private boolean helpShown;
private int targetedTaskJumpIndex;
private int targetedTagJumpIndex;
@Subscribe
private void handleLocalModelChangedEvent(TaskManagerChangedEvent abce) {
latestSavedTaskManager = new TaskManager(abce.data);
}
@Subscribe
private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) {
helpShown = true;
}
@Subscribe
private void handleJumpToTaskListRequestEvent(JumpToTaskListRequestEvent je) {
targetedTaskJumpIndex = je.getTargetIndex();
}
@Subscribe
private void handleJumpToTagListRequestEvent(JumpToTagListRequestEvent je) {
targetedTagJumpIndex = je.getTargetIndex();
}
@Before
public void setup() {
model = new ModelManager();
String tempTaskManagerFile = saveFolder.getRoot().getPath() + "TempTaskManager.xml";
String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json";
logic = new LogicManager(model, new StorageManager(tempTaskManagerFile, tempPreferencesFile));
EventsCenter.getInstance().registerHandler(this);
latestSavedTaskManager = new TaskManager(model.getTaskManager()); // last saved assumed to be up to date before.
targetedTagJumpIndex = -1;
targetedTaskJumpIndex = -1;
helpShown = false;
}
@After
public void teardown() {
EventsCenter.clearSubscribers();
}
@Test
public void execute_invalid() throws Exception {
String invalidCommand = " ";
assertCommandBehavior(invalidCommand,
String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
/**
* Executes the command and confirms that the result message is correct.
* Both the 'task manager' and the 'last shown list' are expected to be empty.
* @see #assertCommandBehavior(String, String, ReadOnlyTaskManager, List)
*/
private void assertCommandBehavior(String inputCommand, String expectedMessage) throws Exception {
assertCommandBehavior(inputCommand, expectedMessage, new TaskManager(), Collections.emptyList());
}
/**
* Executes the command and confirms that the result message is correct and
* also confirms that the following three parts of the LogicManager object's state are as expected:<br>
* - the internal task manager data are same as those in the {@code expectedTaskManager} <br>
* - the backing list shown by UI matches the {@code shownList} <br>
* - {@code expectedTaskManager} was saved to the storage file. <br>
*/
private void assertCommandBehavior(String inputCommand, String expectedMessage,
ReadOnlyTaskManager expectedTaskManager,
List<? extends ReadOnlyTask> expectedShownList) throws Exception {
//Execute the command
CommandResult result = logic.execute(inputCommand);
//Confirm the ui display elements should contain the right data
assertEquals(expectedMessage, result.feedbackToUser);
assertEquals(expectedShownList, model.getSortedFilteredTaskList());
//Confirm the state of data (saved and in-memory) is as expected
assertEquals(expectedTaskManager, model.getTaskManager());
assertEquals(expectedTaskManager, latestSavedTaskManager);
}
@Test
public void execute_unknownCommandWord() throws Exception {
String unknownCommand = "uicfhmowqewca";
assertCommandBehavior(unknownCommand, MESSAGE_UNKNOWN_COMMAND);
}
// @@author A0147924X
@Test
public void execute_helpExtraArgs_errorMessageShown() throws Exception {
assertCommandBehavior("help abc abc", HelpCommand.MESSAGE_WRONG_NUM_ARGS);
}
@Test
public void execute_helpForNonexistentCommand_errorMessageShown() throws Exception {
assertCommandBehavior("help abc", HelpCommand.MESSAGE_WRONG_HELP_COMMAND);
}
@Test
public void execute_helpNoArgs_successful() throws Exception {
assertCommandBehavior("help", HelpCommand.SHOWING_HELP_MESSAGE);
assertTrue(helpShown);
}
@Test
public void execute_helpForCommand_successful() throws Exception {
assertCommandBehavior("help add", AddCommand.MESSAGE_USAGE + "\nAlias: add");
assertCommandBehavior("help priority", HelpCommand.MESSAGE_PRIORITY_USAGE + "\nAlias: priority");
}
// @@author
@Test
public void execute_exit_successful() throws Exception {
assertCommandBehavior("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT);
}
@Test
public void execute_clear_successful() throws Exception {
TestDataHelper helper = new TestDataHelper();
model.addTask(helper.generateTask(1));
model.addTask(helper.generateTask(2));
model.addTask(helper.generateTask(3));
assertCommandBehavior("clear", ClearCommand.MESSAGE_SUCCESS, new TaskManager(), Collections.emptyList());
}
// @@author A0147924X
@Test
public void execute_sort_successful() throws Exception {
TestDataHelper helper = new TestDataHelper();
model.addTask(helper.generateTask(1));
model.addTask(helper.generateTask(2));
model.addTask(helper.generateTask(3));
TaskManager expectedTM = new TaskManager();
expectedTM.addTask(helper.generateTask(1));
expectedTM.addTask(helper.generateTask(2));
expectedTM.addTask(helper.generateTask(3));
List<ReadOnlyTask> expectedList = new ArrayList<>(expectedTM.getTaskList());
SortComparators comparator = SortComparators.PRIORITY;
expectedList.sort((t1, t2) -> t1.comparePriority(t2));
assertCommandBehavior(
String.format("sortby %1$s", comparator.getValue()),
String.format(SortCommand.MESSAGE_SUCCESS, comparator.getValue()),
expectedTM,
expectedList);
comparator = SortComparators.TIME;
expectedList.sort((t1, t2) -> t1.compareTime(t2));
assertCommandBehavior(
String.format("sortby %1$s", comparator.getValue()),
String.format(SortCommand.MESSAGE_SUCCESS, comparator.getValue()),
expectedTM,
expectedList);
}
@Test
public void execute_add_invalidTaskData() throws Exception {
assertCommandBehavior(
"add Dinner with Lancelot venue Acceptable Venue priority wrong", Priority.MESSAGE_PRIORITY_CONSTRAINTS);
assertCommandBehavior(
"add venue No Description priority low", AddCommand.MESSAGE_USAGE);
}
@Test
public void execute_addOnlyDesc_successful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.guinevere();
TaskManager expectedTM = new TaskManager();
expectedTM.addTask(toBeAdded);
// execute command and verify result
assertCommandBehavior(helper.generateAddCommand(toBeAdded),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded),
expectedTM,
expectedTM.getTaskList());
}
@Test
public void execute_addDescContainsKeyword_successful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.morgana();
TaskManager expectedTM = new TaskManager();
expectedTM.addTask(toBeAdded);
assertCommandBehavior(helper.generateAddCommand(toBeAdded),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded),
expectedTM,
expectedTM.getTaskList());
assertEquals(0, targetedTaskJumpIndex);
}
@Test
public void execute_addContainsEscapedKeyword_successful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.challenge();
TaskManager expectedTM = new TaskManager();
expectedTM.addTask(toBeAdded);
assertCommandBehavior(
"add Come 'at' me venue Battlefield priority high",
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded),
expectedTM,
expectedTM.getTaskList());
assertEquals(0, targetedTaskJumpIndex);
toBeAdded = helper.canoodle();
expectedTM.addTask(toBeAdded);
assertCommandBehavior(
"add Secret rendezvous venue 'by' the wall",
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded),
expectedTM,
expectedTM.getTaskList());
assertEquals(1, targetedTaskJumpIndex);
}
@Test
public void execute_add_successful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.lancelot();
TaskManager expectedTM = new TaskManager();
expectedTM.addTask(toBeAdded);
// execute command and verify result
assertCommandBehavior(helper.generateAddCommand(toBeAdded),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded.getAsPrettyText()),
expectedTM,
expectedTM.getTaskList());
assertEquals(0, targetedTaskJumpIndex);
toBeAdded = helper.guinevere();
expectedTM.addTask(toBeAdded);
assertCommandBehavior(helper.generateAddCommand(toBeAdded),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded.getAsPrettyText()),
expectedTM,
expectedTM.getTaskList());
assertEquals(1, targetedTaskJumpIndex);
}
@Test
public void execute_addDuplicate_notAllowed() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.guinevere();
TaskManager expectedTM = new TaskManager();
expectedTM.addTask(toBeAdded);
// setup starting state
model.addTask(toBeAdded); // task already in internal task manager
// execute command and verify result
assertCommandBehavior(
helper.generateAddCommand(toBeAdded),
AddCommand.MESSAGE_DUPLICATE_TASK,
expectedTM,
expectedTM.getTaskList());
}
@Test
public void execute_addAfterSorting_successful() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.guinevere();
helper.addToModel(model, 3);
TaskManager expectedTM = new TaskManager();
helper.addToTaskManager(expectedTM, 3);
expectedTM.addTask(toBeAdded);
List<ReadOnlyTask> expectedList = new ArrayList<>(expectedTM.getTaskList());
expectedList.sort((t1, t2) -> t1.comparePriority(t2));
logic.execute("sortby priority");
assertCommandBehavior(
helper.generateAddCommand(toBeAdded),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded.getAsPrettyText()),
expectedTM,
expectedList);
assertEquals(expectedList.indexOf(toBeAdded), targetedTaskJumpIndex);
}
@Test
public void execute_editInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("edit", expectedMessage);
}
@Test
public void execute_editIndexInvalid_errorMessageShown() throws Exception {
String expectedMessage = Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX;
assertCommandBehavior("edit 52 Dinner with Arthur", expectedMessage);
assertCommandBehavior("edit 10 Dinner with Arthur", expectedMessage);
}
@Test
public void execute_editInvalidFromToFormat_errorMessage() throws Exception {
String expectedMessage = ExtensionParser.EXTENSION_FROM_TO_INVALID_FORMAT;
assertCommandBehavior("edit 1 from 7:30-8:30", expectedMessage);
assertCommandBehavior("edit 1 from 7:30", expectedMessage);
}
@Test
public void execute_editDuplicateParams_errorMessage() throws Exception {
TestDataHelper helper = new TestDataHelper();
TaskManager expectedTM = new TaskManager();
Task toBeEdited = helper.guinevere();
model.addTask(toBeEdited);
expectedTM.addTask(toBeEdited);
String editCommand = "edit 1 Picnic with Guinevere";
assertCommandBehavior(
editCommand,
String.format(EditCommand.MESSAGE_DUPLICATE_PARAMS, toBeEdited),
expectedTM,
expectedTM.getTaskList()
);
}
@Test
public void execute_edit_successful() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task toBeEdited = helper.lancelot();
Task newTask = editTaskWithProperty(toBeEdited, TaskProperties.DESC, "Dinner with Guinevere");
model.addTask(toBeEdited);
model.addTask(helper.morgana());
TaskManager expectedTM = new TaskManager();
expectedTM.addTask(helper.morgana());
expectedTM.addTask(newTask);
String editCommand = "edit 1 Dinner with Guinevere";
assertCommandBehavior(
editCommand,
String.format(EditCommand.MESSAGE_SUCCESS, newTask.getAsPrettyText()),
expectedTM,
expectedTM.getTaskList()
);
assertEquals(1, targetedTaskJumpIndex);
Task newTask1 = editTaskWithProperty(newTask, TaskProperties.DESC, "Dinner with Lancelot");
newTask1 = editTaskWithProperty(newTask1, TaskProperties.VENUE, "Avalon");
expectedTM.removeTask(newTask);
expectedTM.addTask(newTask1);
String editCommand1 = "edit 2 Dinner with Lancelot venue Avalon";
assertCommandBehavior(
editCommand1,
String.format(EditCommand.MESSAGE_SUCCESS, newTask1.getAsPrettyText()),
expectedTM,
expectedTM.getTaskList()
);
assertEquals(1, targetedTaskJumpIndex);
Task newTask2 = editTaskWithProperty(newTask1, TaskProperties.STARTTIME, "7:30pm");
newTask2 = editTaskWithProperty(newTask2, TaskProperties.ENDTIME, "8:50pm");
newTask2 = editTaskWithProperty(newTask2, TaskProperties.PRIORITY, "low");
expectedTM.removeTask(newTask1);
expectedTM.addTask(newTask2);
String editCommand2 = "edit 2 from 7:30pm to 8:50pm priority low";
assertCommandBehavior(
editCommand2,
String.format(EditCommand.MESSAGE_SUCCESS, newTask2.getAsPrettyText()),
expectedTM,
expectedTM.getTaskList()
);
assertEquals(1, targetedTaskJumpIndex);
}
private Task editTaskWithProperty(Task taskToEdit, TaskProperties property, String value)
throws IllegalValueException {
HashMap<TaskProperties, Optional<String>> newProps =
taskToEdit.getPropertiesAsStrings();
newProps.put(property, Optional.of(value));
return new Task(newProps);
}
@Test
public void execute_editAfterSorting_successful() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task toBeEdited = helper.lancelot();
model.addTask(helper.generateTask(2));
model.addTask(helper.generateTask(3));
model.addTask(toBeEdited);
logic.execute("sortby priority");
TaskManager expectedTM = new TaskManager();
expectedTM.addTask(helper.generateTask(2));
expectedTM.addTask(helper.generateTask(3));
HashMap<TaskProperties, Optional<String>> newProps =
toBeEdited.getPropertiesAsStrings();
newProps.put(TaskProperties.DESC, Optional.of("Dinner with Guinevere"));
Task newTask = new Task(newProps);
expectedTM.addTask(newTask);
String editCommand = "edit 2 Dinner with Guinevere";
List<ReadOnlyTask> expectedList = new ArrayList<>(expectedTM.getTaskList());
expectedList.sort((t1, t2) -> t1.comparePriority(t2));
assertCommandBehavior(
editCommand,
String.format(EditCommand.MESSAGE_SUCCESS, newTask.getAsPrettyText()),
expectedTM,
expectedList
);
assertEquals(expectedList.indexOf(newTask), targetedTaskJumpIndex);
}
@Test
public void execute_doneInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DoneCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("done", expectedMessage);
}
@Test
public void execute_doneIndexInvalid_errorMessageShown() throws Exception {
String expectedMessage = Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX;
assertCommandBehavior("done 52", expectedMessage);
assertCommandBehavior("done 10", expectedMessage);
}
@Test
public void execute_done_successful() throws Exception {
TestDataHelper helper = new TestDataHelper();
List<Task> threeTasks = helper.generateTaskList(3);
helper.addToModel(model, threeTasks);
TaskManager expectedTM = helper.generateTaskManager(threeTasks);
Task doneTask = editTaskWithProperty(threeTasks.get(1), TaskProperties.DONE, "Yes");
expectedTM.removeTask(threeTasks.get(1));
expectedTM.addTask(doneTask);
String doneCommand = "done 2";
// execute command and verify result
assertCommandBehavior(doneCommand,
String.format(DoneCommand.MESSAGE_SUCCESS, doneTask),
expectedTM,
expectedTM.getTaskList());
assertEquals(2, targetedTaskJumpIndex);
}
// @@author
@Test
public void execute_list_showsAllTasks() throws Exception {
// prepare expectations
TestDataHelper helper = new TestDataHelper();
TaskManager expectedTM = helper.generateTaskManager(2);
List<? extends ReadOnlyTask> expectedList = expectedTM.getTaskList();
// prepare task manager state
helper.addToModel(model, 2);
assertCommandBehavior("list",
ListCommand.MESSAGE_SUCCESS,
expectedTM,
expectedList);
}
/**
* Confirms the 'invalid argument index number behaviour' for the given command
* targeting a single task in the shown list, using visible index.
* @param commandWord to test assuming it targets a single task in the last shown list based on visible index.
*/
private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception {
assertCommandBehavior(commandWord , expectedMessage); //index missing
assertCommandBehavior(commandWord + " +1", expectedMessage); //index should be unsigned
assertCommandBehavior(commandWord + " -1", expectedMessage); //index should be unsigned
assertCommandBehavior(commandWord + " 0", expectedMessage); //index cannot be 0
assertCommandBehavior(commandWord + " not_a_number", expectedMessage);
}
/**
* Confirms the 'invalid argument index number behaviour' for the given command
* targeting a single task in the shown list, using visible index.
* @param commandWord to test assuming it targets a single task in the last shown list based on visible index.
*/
private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception {
String expectedMessage = MESSAGE_INVALID_PERSON_DISPLAYED_INDEX;
TestDataHelper helper = new TestDataHelper();
List<Task> taskList = helper.generateTaskList(2);
// set TM state to 2 tasks
model.resetData(new TaskManager());
for (Task p : taskList) {
model.addTask(p);
}
assertCommandBehavior(commandWord + " 3", expectedMessage, model.getTaskManager(), taskList);
}
@Test
public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage);
}
@Test
public void execute_deleteIndexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("delete");
}
@Test
public void execute_deleteIndexInvalid_errorMessageShown() throws Exception {
String expectedMessage = Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX;
assertCommandBehavior("delete 52", expectedMessage);
assertCommandBehavior("delete 10", expectedMessage);
}
@Test
public void execute_delete_removesCorrectTask() throws Exception {
TestDataHelper helper = new TestDataHelper();
List<Task> threeTasks = helper.generateTaskList(3);
TaskManager expectedTM = helper.generateTaskManager(threeTasks);
expectedTM.removeTask(threeTasks.get(1));
helper.addToModel(model, threeTasks);
assertCommandBehavior("delete 2",
String.format(DeleteCommand.MESSAGE_SUCCESS, threeTasks.get(1).getAsPrettyText()),
expectedTM,
expectedTM.getTaskList());
}
// @@author A0148003U
@Test
public void execute_undo_successful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeUndone = helper.lancelot();
// execute command and verify result
logic.execute(helper.generateAddCommand(toBeUndone));
assertCommandBehavior("undo",String.format(AddCommand.UNDO_SUCCESS, toBeUndone));
}
@Test
public void execute_find_invalidArgsFormat() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE);
assertCommandBehavior("find ", expectedMessage);
}
@Test
public void execute_find_onlyMatchesFullWordsInDescs() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task pTarget1 = helper.generateTaskWithDesc("bla bla KEY bla");
Task pTarget2 = helper.generateTaskWithDesc("bla KEY bla bceofeia");
Task p1 = helper.generateTaskWithDesc("KE Y");
Task p2 = helper.generateTaskWithDesc("KEYKEYKEY sduauo");
List<Task> fourTasks = helper.generateTaskList(p1, pTarget1, p2, pTarget2);
TaskManager expectedTM = helper.generateTaskManager(fourTasks);
List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2);
helper.addToModel(model, fourTasks);
assertCommandBehavior("find KEY",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedTM,
expectedList);
}
@Test
public void execute_find_isNotCaseSensitive() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task p1 = helper.generateTaskWithDesc("bla bla KEY bla");
Task p2 = helper.generateTaskWithDesc("bla KEY bla bceofeia");
Task p3 = helper.generateTaskWithDesc("key key");
Task p4 = helper.generateTaskWithDesc("KEy sduauo");
List<Task> fourTasks = helper.generateTaskList(p3, p1, p4, p2);
TaskManager expectedTM = helper.generateTaskManager(fourTasks);
List<Task> expectedList = fourTasks;
helper.addToModel(model, fourTasks);
assertCommandBehavior("find KEY",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedTM,
expectedList);
}
@Test
public void execute_find_matchesIfAnyKeywordPresent() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task pTarget1 = helper.generateTaskWithDesc("bla bla KEY bla");
Task pTarget2 = helper.generateTaskWithDesc("bla rAnDoM bla bceofeia");
Task pTarget3 = helper.generateTaskWithDesc("key key");
Task p1 = helper.generateTaskWithDesc("sduauo");
List<Task> fourTasks = helper.generateTaskList(pTarget1, p1, pTarget2, pTarget3);
TaskManager expectedTM = helper.generateTaskManager(fourTasks);
List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2, pTarget3);
helper.addToModel(model, fourTasks);
assertCommandBehavior("find key rAnDoM",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedTM,
expectedList);
}
// @@author A0147924X
@Test
public void execute_findThenSort_successful() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task t1 = helper.generateTaskWithDescAndPriority("bla bla bla bla", "high");
Task t2 = helper.generateTaskWithDescAndPriority("bla KEY bla bceofeia", "med");
Task t3 = helper.generateTaskWithDescAndPriority("key key", "low");
Task t4 = helper.generateTaskWithDescAndPriority("KEy sduauo", "");
List<Task> fourTasks = helper.generateTaskList(t3, t1, t4, t2);
TaskManager expectedTM = helper.generateTaskManager(fourTasks);
helper.addToModel(model, fourTasks);
List<Task> expectedList = helper.generateTaskList(t3, t4, t2);
SortComparators comparator = SortComparators.PRIORITY;
assertCommandBehavior("find KEY",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedTM,
expectedList);
expectedList.sort((task1, task2) -> task1.comparePriority(task2));
assertCommandBehavior(
String.format("sortby %1$s", comparator.getValue()),
String.format(SortCommand.MESSAGE_SUCCESS, comparator.getValue()),
expectedTM,
expectedList);
}
//@@author A0139621H
@Test
public void execute_findVenue_successful() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task p1 = helper.generateTaskWithVenue("Arts");
Task p2 = helper.generateTaskWithVenue("Biz");
Task p3 = helper.generateTaskWithVenue("Com");
Task p4 = helper.generateTaskWithVenue("");
List<Task> fourTasks = helper.generateTaskList(p3, p1, p4, p2);
TaskManager expectedTM = helper.generateTaskManager(fourTasks);
helper.addToModel(model, fourTasks);
List<Task> expectedList = helper.generateTaskList(p3);
assertCommandBehavior("find venue Com",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedTM,
expectedList);
}
@Test
public void execute_find_noTasksListed() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task p1 = helper.generateTaskWithVenue("Engin");
Task p2 = helper.generateTaskWithPriority("high");
Task p3 = helper.generateTaskWithEndTime("6pm");
Task p4 = helper.generateTaskWithStartTime("8am");
List<Task> fourTasks = helper.generateTaskList(p3, p1, p4, p2);
TaskManager expectedTM = helper.generateTaskManager(fourTasks);
helper.addToModel(model, fourTasks);
List<Task> expectedList = helper.generateTaskList();
assertCommandBehavior("find venue Com",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedTM,
expectedList);
}
@Test
public void execute_find_invalidExtension() throws Exception {
assertCommandBehavior("find priority abc", Priority.MESSAGE_PRIORITY_CONSTRAINTS);
}
// @@author A0147924X
@Test
public void execute_findTag_successful() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task p1 = helper.generateTaskWithTagAndDesc("Kill Mordred", "Violent");
Task p2 = helper.guinevere();
Task p3 = helper.lancelot();
Task p4 = helper.morgana();
Task p5 = helper.generateTaskWithTagAndDesc("Elope with Guinevere", "Home-wrecking");
List<Task> fiveTasks = helper.generateTaskList(p5, p3, p1, p4, p2);
TaskManager expectedTM = helper.generateTaskManager(fiveTasks);
helper.addToModel(model, fiveTasks);
model.addTag(new Tag("Home-wrecking"));
model.addTag(new Tag("Violent"));
List<Task> expectedList = helper.generateTaskList(p1);
assertCommandBehavior("find tag Violent",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedTM,
expectedList);
assertEquals(1, targetedTagJumpIndex);
}
//@@author A0139621H
@Test
public void execute_findStartTime_successful() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task p1 = helper.generateTaskWithStartTime("2.30pm");
Task p2 = helper.generateTaskWithStartTime("11.30am");
Task p3 = helper.generateTaskWithStartTime("12.45pm");
Task p4 = helper.generateTaskWithStartTime("8am");
List<Task> fourTasks = helper.generateTaskList(p3, p1, p4, p2);
TaskManager expectedTM = helper.generateTaskManager(fourTasks);
helper.addToModel(model, fourTasks);
List<Task> expectedList = helper.generateTaskList(p1);
assertCommandBehavior("find at 2pm",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedTM,
expectedList);
}
@Test
public void execute_findEndTime_successful() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task p1 = helper.generateTaskWithEndTime("3.30pm");
Task p2 = helper.generateTaskWithEndTime("10.30am");
Task p3 = helper.generateTaskWithEndTime("1.45pm");
Task p4 = helper.generateTaskWithEndTime("8pm");
List<Task> fourTasks = helper.generateTaskList(p2, p3, p1, p4);
TaskManager expectedTM = helper.generateTaskManager(fourTasks);
helper.addToModel(model, fourTasks);
List<Task> expectedList = helper.generateTaskList(p2, p3, p1);
assertCommandBehavior("find by 4pm",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedTM,
expectedList);
}
@Test
public void execute_findStartAndEndTime_successful() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task p1 = helper.generateTaskWithStartAndEndTime("5.15pm", "6.15pm");
Task p2 = helper.generateTaskWithStartAndEndTime("7.30am", "10.45am");
Task p3 = helper.generateTaskWithStartAndEndTime("1.55pm", "3pm");
Task p4 = helper.generateTaskWithStartAndEndTime("9.30pm", "10.45pm");
List<Task> fourTasks = helper.generateTaskList(p2, p1, p4, p3);
TaskManager expectedTM = helper.generateTaskManager(fourTasks);
helper.addToModel(model, fourTasks);
List<Task> expectedList = helper.generateTaskList(p4);
assertCommandBehavior("find from 9pm to 11pm",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedTM,
expectedList);
}
@Test
public void execute_findDescAndVenue_successful() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task p1 = helper.generateTaskWithDescAndVenue("girl", "uptown");
Task p2 = helper.generateTaskWithDescAndVenue("my love", "an empty street");
Task p3 = helper.generateTaskWithDescAndVenue("funk", "uptown");
Task p4 = helper.generateTaskWithDescAndVenue("Road trip", "Genting Highlands");
List<Task> fourTasks = helper.generateTaskList(p2, p4, p1, p3);
TaskManager expectedTM = helper.generateTaskManager(fourTasks);
helper.addToModel(model, fourTasks);
List<Task> expectedList = helper.generateTaskList(p4);
assertCommandBehavior("find Road venue Genting",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedTM,
expectedList);
}
@Test
public void execute_findVenueThenDesc_successful() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task p1 = helper.generateTaskWithDescAndVenue("girl", "uptown");
Task p2 = helper.generateTaskWithDescAndVenue("my love", "an empty street");
Task p3 = helper.generateTaskWithDescAndVenue("funk", "uptown");
Task p4 = helper.generateTaskWithDescAndVenue("Road trip", "Genting Highlands");
List<Task> fourTasks = helper.generateTaskList(p2, p4, p1, p3);
TaskManager expectedTM = helper.generateTaskManager(fourTasks);
helper.addToModel(model, fourTasks);
List<Task> expectedList = helper.generateTaskList(p1, p3);
assertCommandBehavior("find venue uptown",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedTM,
expectedList);
}
@Test
public void execute_findPriority_successful() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task p1 = helper.generateTaskWithPriority("low");
Task p2 = helper.generateTaskWithPriority("med");
Task p3 = helper.generateTaskWithPriority("high");
Task p4 = helper.generateTaskWithPriority("");
List<Task> fourTasks = helper.generateTaskList(p1, p2, p3, p4);
TaskManager expectedTM = helper.generateTaskManager(fourTasks);
helper.addToModel(model, fourTasks);
List<Task> expectedList = helper.generateTaskList(p3);
assertCommandBehavior("find priority high",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedTM,
expectedList);
}
// @@author A0147924X
@Test
public void execute_alias_wrongNumberOfArgs() throws Exception {
assertCommandBehavior("alias", AliasCommand.MESSAGE_WRONG_NUM_ARGS);
assertCommandBehavior("alias add", AliasCommand.MESSAGE_WRONG_NUM_ARGS);
assertCommandBehavior("alias add + -", AliasCommand.MESSAGE_WRONG_NUM_ARGS);
}
@Test
public void execute_alias_doesNotExist() throws Exception {
assertCommandBehavior("alias - +", AliasCommand.MESSAGE_NO_MATCH);
}
@Test
public void execute_alias_alreadyTaken() throws Exception {
assertCommandBehavior("alias add +", String.format(AliasCommand.MESSAGE_SUCCESS, "add", "+"));
assertCommandBehavior("alias edit +", String.format(AliasCommand.MESSAGE_ALIAS_TAKEN, Commands.ADD));
}
@Test
public void execute_alias_successful() throws Exception {
assertCommandBehavior("alias add +", String.format(AliasCommand.MESSAGE_SUCCESS, "add", "+"));
assertCommandBehavior("help add", AddCommand.MESSAGE_USAGE + "\nAlias: +");
TestDataHelper helper = new TestDataHelper();
TaskManager expectedTM = new TaskManager();
Task toBeAdded = helper.lancelot();
expectedTM.addTask(toBeAdded);
// execute command and verify result
assertCommandBehavior(helper.generateAddCommandWithAlias(toBeAdded, "+"),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded.getAsPrettyText()),
expectedTM,
expectedTM.getTaskList());
assertEquals(0, targetedTaskJumpIndex);
assertCommandBehavior("alias delete -",
String.format(AliasCommand.MESSAGE_SUCCESS, "delete", "-"),
expectedTM,
expectedTM.getTaskList());
expectedTM.removeTask(toBeAdded);
assertCommandBehavior("- 1",
String.format(DeleteCommand.MESSAGE_SUCCESS, toBeAdded.getAsPrettyText()),
expectedTM,
expectedTM.getTaskList());
assertCommandBehavior("alias priority p",
String.format(AliasCommand.MESSAGE_SUCCESS, "priority", "p"),
expectedTM,
expectedTM.getTaskList());
toBeAdded = helper.morgana();
expectedTM.addTask(toBeAdded);
assertCommandBehavior(helper.generateAddCommandWithAlias(toBeAdded, "+").replace("priority", "p"),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded.getAsPrettyText()),
expectedTM,
expectedTM.getTaskList());
assertEquals(0, targetedTaskJumpIndex);
// cleanup
logic.execute("alias + add");
logic.execute("alias - delete");
logic.execute("alias p priority");
}
/**
* A utility class to generate test data.
*/
class TestDataHelper{
Task guinevere() throws Exception {
return new Task("Picnic with Guinevere", "", "", "", "", "", "");
}
Task lancelot() throws Exception {
return new Task("Joust with Lancelot", "Avalon", "med", "7:30", "8:30", "", "");
}
Task morgana() throws Exception {
return new Task("Flatten Morgana", "Camelot", "high", "", "", "", "");
}
Task challenge() throws Exception {
return new Task("Come at me", "Battlefield", "high", "", "", "", "");
}
Task canoodle() throws Exception {
return new Task("Secret rendezvous", "by the wall", "", "", "", "", "");
}
/**
* Generates a valid task using the given seed.
* Running this function with the same parameter values guarantees the returned task will have the same state.
* Each unique seed will generate a unique Task object.
*
* @param seed used to generate the task data field values
*/
Task generateTask(int seed) throws Exception {
return new Task(
"Task " + seed,
"" + Math.abs(seed),
new String[] {"low", "med", "high"}[seed % 3],
(Math.abs(seed) % 12 + 1) + ":00",
(Math.abs(seed) % 12 + 1) + ":00",
"",
""
);
}
/**
* Generated the add command given a task and alias for the add command
* @param task Task for which the add command will be generated
* @param alias Alias of the add command
* @return The generated add command
*/
String generateAddCommandWithAlias(Task task, String alias) {
StringBuffer cmd = new StringBuffer();
cmd.append(alias + " ");
cmd.append(task.getDesc().get().toString());
if (task.getVenue().isPresent()) {
cmd.append(" venue ").append(task.getVenue().get().toString());
}
if (task.getPriority().isPresent()) {
cmd.append(" priority ").append(task.getPriority().get().toString());
}
if (task.getStartTime().isPresent()) {
cmd.append(" from ").append(task.getStartTime().get().toString());
}
if (task.getEndTime().isPresent()) {
cmd.append(" to ").append(task.getEndTime().get().toString());
}
if (task.getTag().isPresent()) {
cmd.append(" tag ").append(task.getTag().get().toString());
}
return cmd.toString();
}
/**
* Generates the add command given a task (assumes alias is add)"
* @param task The task for which add command will be generated
* @return The generated add command
*/
String generateAddCommand(Task task) {
return generateAddCommandWithAlias(task, "add");
}
// @@author
/**
* Generates a TaskManager with auto-generated tasks.
*/
TaskManager generateTaskManager(int numGenerated) throws Exception{
TaskManager taskManager = new TaskManager();
addToTaskManager(taskManager, numGenerated);
return taskManager;
}
/**
* Generates an TaskManager based on the list of Tasks given.
*/
TaskManager generateTaskManager(List<Task> tasks) throws Exception{
TaskManager taskManager = new TaskManager();
addToTaskManager(taskManager, tasks);
return taskManager;
}
/**
* Adds auto-generated Task objects to the given TaskManager
* @param taskManager The TaskManager to which the Tasks will be added
*/
void addToTaskManager(TaskManager taskManager, int numGenerated) throws Exception{
addToTaskManager(taskManager, generateTaskList(numGenerated));
}
/**
* Adds the given list of Tasks to the given TaskManager
*/
void addToTaskManager(TaskManager taskManager, List<Task> tasksToAdd) throws Exception{
for(Task p: tasksToAdd){
taskManager.addTask(p);
}
}
/**
* Adds auto-generated Task objects to the given model
* @param model The model to which the Tasks will be added
*/
void addToModel(Model model, int numGenerated) throws Exception{
addToModel(model, generateTaskList(numGenerated));
}
/**
* Adds the given list of Tasks to the given model
*/
void addToModel(Model model, List<Task> tasksToAdd) throws Exception{
for(Task p: tasksToAdd){
model.addTask(p);
}
}
/**
* Generates a list of Tasks based on the flags.
*/
List<Task> generateTaskList(int numGenerated) throws Exception{
List<Task> tasks = new ArrayList<>();
for(int i = 1; i <= numGenerated; i++){
tasks.add(generateTask(i));
}
return tasks;
}
List<Task> generateTaskList(Task... tasks) {
return Arrays.asList(tasks);
}
//@@author A0139621H
/**
* Generates a Task object with given desc. Other fields will have some dummy values.
* @param desc Description for the task
* @return Task with the given parameters
* @throws Exception
*/
Task generateTaskWithDesc(String desc) throws Exception {
return new Task(
desc,
"Some Venue",
"low",
"7:30pm",
"8:30pm",
"",
""
);
}
/**
* Generates a Task object with given venue. Other fields will have some dummy values.
* @param venue Venue for the task
* @return Task with the given parameters
* @throws Exception
*/
Task generateTaskWithVenue(String venue) throws Exception {
return new Task(
"boo",
venue,
"med",
"10pm",
"11pm",
"",
""
);
}
/**
* Generates a Task object with given priority. Other fields will have some dummy values.
* @param priority Priority for the task
* @return Task with the given parameters
* @throws Exception
*/
Task generateTaskWithPriority(String priority) throws Exception {
return new Task(
"hello it's me",
"somewhere over the rainbow",
priority,
"10am",
"12pm",
"",
""
);
}
/**
* Generates a Task object with given start time. Other fields will have some dummy values.
* @param startTime Start time for the task
* @return Task with the given parameters
* @throws Exception
*/
Task generateTaskWithStartTime(String startTime) throws Exception {
return new Task(
"hello",
"from the other side",
"high",
startTime,
"3pm",
"",
""
);
}
/**
* Generates a Task object with given end time. Other fields will have some dummy values.
* @param endTime End time for the task
* @return Task with the given parameters
* @throws Exception
*/
Task generateTaskWithEndTime(String endTime) throws Exception {
return new Task(
"don't let me down",
"chainsmokers",
"low",
"9am",
endTime,
"",
""
);
}
/**
* Generates a Task object with given start and end time. Other fields will have some dummy values.
* @param startTime Start time for the task
* @param endTime End time for the task
* @return Task with the given parameters
* @throws Exception
*/
Task generateTaskWithStartAndEndTime(String startTime, String endTime) throws Exception {
return new Task(
"falling down",
"london bridge",
"high",
startTime,
endTime,
"",
""
);
}
/**
* Generates a Task object with given desc and venue. Other fields will have some dummy values.
* @param desc Description for the task
* @param venue Venue for the task
* @return Task with the given parameters
* @throws Exception
*/
Task generateTaskWithDescAndVenue(String desc, String venue) throws Exception {
return new Task(
desc,
venue,
"med",
"4.30am",
"7am",
"",
""
);
}
// @@author A0147924X
/**
* Generates a Task object with given desc and tag. Other fields will have some dummy values.
* @param desc Description for the task
* @param tag Tag for the task
* @return Task with the given parameters
* @throws Exception
*/
Task generateTaskWithTagAndDesc(String desc, String tag) throws Exception {
return new Task(
desc,
"Camelot",
"med",
"4.30am",
"7am",
"",
tag
);
}
/**
* Generates a Task object with given tag. Other fields will have some dummy values.
* @param desc Description for the task
* @param priority Priority for the task
* @return Task with the given parameters
* @throws Exception
*/
Task generateTaskWithDescAndPriority(String desc, String priority) throws Exception {
return new Task(
desc,
"Camelot",
priority,
"4.30am",
"7am",
"",
""
);
}
}
} |
package ljdp.minechem.api.core;
import static ljdp.minechem.api.core.EnumElement.*;
import java.util.ArrayList;
import java.util.Random;
// Na2OLi2O(SiO2)2(B2O3)3H2O
// MOLECULE IDS MUST BE CONTINIOUS OTHERWISE THE ARRAY WILL BE MISALIGNED.
public enum EnumMolecule {
cellulose(0, "Cellulose", new Element(C, 6), new Element(H, 10), new Element(O, 5)),
water(1, "Water", new Element(H, 2), new Element(O)),
carbonDioxide(2, "Carbon Dioxide", new Element(C), new Element(O, 2)),
nitrogenDioxide(3, "Nitrogen Dioxide", new Element(N), new Element(O, 2)),
toluene(4, "Toluene", new Element(C, 7), new Element(H, 8)),
potassiumNitrate(5, "Potassium Nitrate", new Element(K), new Element(N), new Element(O, 3)),
tnt(6, "Trinitrotoluene", new Element(C, 6), new Element(H, 2), new Molecule(nitrogenDioxide, 3), new Molecule(toluene)),
siliconDioxide(7, "Silicon Dioxide", new Element(Si), new Element(O, 2)),
calcite(8, "Calcite", new Element(Ca), new Element(C), new Element(O, 3)),
pyrite(9, "Pyrite", new Element(Fe), new Element(S, 2)),
nepheline(10, "Nepheline", new Element(Al), new Element(Si), new Element(O, 4)),
sulfate(11, "Sulfate (ion)", new Element(S), new Element(O, 4)),
noselite(12, "Noselite", new Element(Na, 8), new Molecule(nepheline, 6), new Molecule(sulfate)),
sodalite(13, "Sodalite", new Element(Na, 8), new Molecule(nepheline, 6), new Element(Cl, 2)),
nitrate(14, "Nitrate (ion)", new Element(N), new Element(O, 3)),
carbonate(15, "Carbonate (ion)", new Element(C), new Element(O, 3)),
cyanide(16, "Potassium Cyanide", new Element(K), new Element(C), new Element(N)),
phosphate(17, "Phosphate (ion)", new Element(P), new Element(O, 4)),
acetate(18, "Acetate (ion)", new Element(C, 2), new Element(H, 3), new Element(O, 2)),
chromate(19, "Chromate (ion)", new Element(Cr), new Element(O, 4)),
hydroxide(20, "Hydroxide (ion)", new Element(O), new Element(H)),
ammonium(21, "Ammonium (ion)", new Element(N), new Element(H, 4)),
hydronium(22, "Hydronium (ion)", new Element(H, 3), new Element(O)),
peroxide(23, "Hydrogen Peroxide", new Element(H, 2), new Element(O, 2)),
calciumOxide(24, "Calcium Oxide", new Element(Ca), new Element(O)),
calciumCarbonate(25, "Calcium Carbonate", new Element(Ca), new Molecule(carbonate)),
magnesiumCarbonate(26, "Magnesium Carbonate", new Element(Mg), new Molecule(carbonate)),
lazurite(27, "Lazurite", new Element(Na, 8), new Molecule(nepheline), new Molecule(sulfate)),
isoprene(28, "Isoprene", new Element(C, 5), new Element(H, 8)),
butene(29, "Butene", new Element(C, 4), new Element(H, 8)),
polyisobutylene(30, "Polyisobutylene Rubber", new Molecule(butene, 16), new Molecule(isoprene)),
malicAcid(31, "Malic Acid", new Element(C, 4), new Element(H, 6), new Element(O, 5)),
vinylChloride(32, "Vinyl Chloride Monomer", new Element(C, 2), new Element(H, 3), new Element(Cl)),
polyvinylChloride(33, "Polyvinyl Chloride", new Molecule(vinylChloride, 64)),
methamphetamine(34, "Methamphetamine", new Element(C, 10), new Element(H, 15), new Element(N)),
psilocybin(35, "Psilocybin", new Element(C, 12), new Element(H, 17), new Element(N, 2), new Element(O, 4), new Element(P)),
iron3oxide(36, "Iron (III) Oxide", new Element(Fe, 2), new Element(O, 3)),
strontiumNitrate(37, "Strontium Nitrate", new Element(Sr), new Molecule(nitrate, 2)),
magnetite(38, "Magnetite", new Element(Fe, 3), new Element(O, 4)),
magnesiumOxide(39, "Magnesium Oxide", new Element(Mg), new Element(O)),
cucurbitacin(40, "Cucurbitacin", new Element(C, 30), new Element(H, 42), new Element(O, 7)),
asparticAcid(41, "Aspartic Acid", new Element(C, 4), new Element(H, 7), new Element(N), new Element(O, 4)),
hydroxylapatite(42, "Hydroxylapatite", new Element(Ca, 5), new Molecule(phosphate, 3), new Element(O), new Element(H)),
alinine(43, "Alinine (amino acid)", new Element(C, 3), new Element(H, 7), new Element(N), new Element(O, 2)),
glycine(44, "Glycine (amino acid)", new Element(C, 2), new Element(H, 5), new Element(N), new Element(O, 2)),
serine(45, "Serine (amino acid)", new Element(C, 3), new Element(H, 7), new Molecule(nitrate)),
mescaline(46, "Mescaline", new Element(C, 11), new Element(H, 17), new Molecule(nitrate)),
methyl(47, "Methyl (ion)", new Element(C), new Element(H, 3)),
methylene(48, "Methylene (ion)", new Element(C), new Element(H, 2)),
cyanoacrylate(49, "Cyanoacrylate", new Molecule(methyl), new Molecule(methylene), new Element(C, 3), new Element(N), new Element(H), new Element(O, 2)),
polycyanoacrylate(50, "Poly-cyanoacrylate", new Molecule(cyanoacrylate, 3)),
redPigment(51, "Cobalt(II) nitrate", new Element(Co), new Molecule(nitrate, 2)),
orangePigment(52, "Potassium Dichromate", new Element(K, 2), new Element(Cr, 2), new Element(O, 7)),
yellowPigment(53, "Potassium Chromate", new Element(Cr), new Element(K, 2), new Element(O, 4)),
limePigment(54, "Nickel(II) Chloride", new Element(Ni), new Element(Cl, 2)),
lightbluePigment(55, "Copper(II) Sulfate", new Element(Cu), new Molecule(sulfate)),
purplePigment(56, "Potassium Permanganate", new Element(K), new Element(Mn), new Element(O, 4)),
greenPigment(57, "Zinc Green", new Element(Co), new Element(Zn), new Element(O, 2)),
blackPigment(58, "Carbon Black", new Element(C), new Element(H, 2), new Element(O)),
whitePigment(59, "Titanium Dioxide", new Element(Ti), new Element(O, 2)),
metasilicate(60, "Metasilicate", new Element(Si), new Element(O, 3)),
beryl(61, "Beryl", new Element(Be, 3), new Element(Al, 2), new Molecule(metasilicate, 6)),
ethanol(62, "Ethyl Alchohol", new Element(C, 2), new Element(H, 6), new Element(O)),
amphetamine(63, "Aphetamine", new Element(C, 9), new Element(H, 13), new Element(N)),
theobromine(64, "Theobromine", new Element(C, 7), new Element(H, 8), new Element(N, 4), new Element(O, 2)),
starch(65, "Starch", new Molecule(cellulose, 2), new Molecule(cellulose, 1)),
sucrose(66, "Sucrose", new Element(C, 12), new Element(H, 22), new Element(O, 11)),
muscarine(67, "Muscarine", new Element(C, 9), new Element(H, 20), new Element(N), new Element(O, 2)),
aluminiumOxide(68, "Aluminium Oxide", new Element(Al, 2), new Element(O, 3)),
fullrene(69, "Carbon Nanotubes", new Element(C, 64), new Element(C, 64), new Element(C, 64), new Element(C, 64)),
keratin(70, "Keratin", new Element(C, 2), new Molecule(water), new Element(N)),
penicillin(71, "Penicillin", new Element(C, 16), new Element(H, 18), new Element(N, 2), new Element(O, 4), new Element(S)),
testosterone(72, "Testosterone", new Element(C, 19), new Element(H, 28), new Element(O, 2)),
kaolinite(73, "Kaolinite", new Element(Al, 2), new Element(Si, 2), new Element(O, 5), new Molecule(hydroxide, 4)),
fingolimod(74, "Fingolimod", new Element(C, 19), new Element(H, 33), new Molecule(nitrogenDioxide)), // LJDP, You ment to say fingolimod not myrocin.
arginine(75, "Arginine (amino acid)", new Element(C, 6), new Element(H, 14), new Element(N, 4), new Element(O, 2)),
shikimicAcid(76, "Shikimic Acid", new Element(C, 7), new Element(H, 10), new Element(O, 5)),
sulfuricAcid(77, "Sulfuric Acid", new Element(H, 2), new Element(S), new Element(O, 4)),
glyphosate(78, "Glyphosate", new Element(C, 3), new Element(H, 8), new Element(N), new Element(O, 5), new Element(P)),
quinine(79, "Quinine", new Element(C, 20), new Element(H, 24), new Element(N, 2), new Element(O, 2)),
ddt(80, "DDT", new Element(C, 14), new Element(H, 9), new Element(Cl, 5)),
dota(81, "DOTA", new Element(C, 16), new Element(H, 28), new Element(N, 4), new Element(O, 8)),
poison(82, "T-2 Mycotoxin", new Element(C, 24), new Element(H, 34), new Element(O, 9)),
salt(83, "Salt", new Element(Na, 1), new Element(Cl, 1)),
nhthree(84, "Ammonia", new Element(N, 1), new Element(H, 3)),
nod(85, "Nodularin", new Element(C, 41), new Element(H, 60), new Element(N, 8), new Element(O, 10)),
ttx(86, "TTX (Tetrodotoxin)", new Element(C, 11), new Element(H, 11), new Element(N, 3), new Element(O, 8)),
afroman(87, "THC", new Element(C, 21), new Element(H, 30), new Element(O, 2)),
mt(88, "Methylcyclopentadienyl Manganese Tricarbonyl", new Element(C, 9), new Element(H, 7), new Element(Mn, 1), new Element(O, 3)), // Level 1
buli(89, "Tert-Butyllithium", new Element(Li, 1), new Element(C, 4), new Element(H, 9)), // Level 2
plat(90, "Chloroplatinic acid", new Element(H, 2), new Element(Pt, 1), new Element(Cl, 6)), // Level 3
phosgene(91, "Phosgene", new Element(C, 1), new Element(O, 1), new Element(Cl, 2)),
aalc(92, "Allyl alcohol", new Element(C, 3), new Element(H, 6), new Element(O, 1)),
hist(93, "Diphenhydramine", new Element(C, 17), new Element(H, 21), new Element(N), new Element(O)),
pal2(94, "Batrachotoxin", new Element(C, 31), new Element(H, 42), new Element(N, 2), new Element(O, 6)),
ret(95, "Retinol", new Element(C, 20), new Element(H, 30), new Element(O)),
stevenk(96, "Xylitol", new Element(C, 5), new Element(H, 12), new Element(O, 5)),
weedex(97, "Aminocyclopyrachlor", new Element(C,8), new Element(H,8), new Element(Cl), new Element(N,3), new Element(O,2)),
public static EnumMolecule[] molecules = values();
private final String descriptiveName;
private final ArrayList<Chemical> components;
private int id;
public float red;
public float green;
public float blue;
public float red2;
public float green2;
public float blue2;
EnumMolecule(int id, String descriptiveName, Chemical... chemicals) {
this.id = id;
this.components = new ArrayList<Chemical>();
this.descriptiveName = descriptiveName;
for (Chemical chemical : chemicals) {
this.components.add(chemical);
}
Random random = new Random(id);
this.red = random.nextFloat();
this.green = random.nextFloat();
this.blue = random.nextFloat();
this.red2 = random.nextFloat();
this.green2 = random.nextFloat();
this.blue2 = random.nextFloat();
}
public static EnumMolecule getById(int id) {
for (EnumMolecule molecule : molecules) {
if (molecule.id == id)
return molecule;
}
return null;
}
public int id() {
return this.id;
}
public String descriptiveName() {
return this.descriptiveName;
}
public ArrayList<Chemical> components() {
return this.components;
}
} |
package gov.nih.nci.calab.ui.submit;
/**
* This class uploads a report file and assigns visibility
*
* @author pansu
*/
/* CVS $Id: SubmitProtocolAction.java,v 1.8 2007-05-31 13:08:45 chenhang Exp $ */
import gov.nih.nci.calab.dto.common.ProtocolFileBean;
import gov.nih.nci.calab.dto.common.ProtocolBean;
import gov.nih.nci.calab.service.submit.SubmitProtocolService;
import gov.nih.nci.calab.service.search.SearchProtocolService;
import gov.nih.nci.calab.service.util.CaNanoLabConstants;
import gov.nih.nci.calab.service.util.StringUtils;
import gov.nih.nci.calab.ui.core.AbstractDispatchAction;
import gov.nih.nci.calab.ui.core.InitSessionSetup;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.upload.FormFile;
import org.apache.struts.util.LabelValueBean;
import org.apache.struts.validator.DynaValidatorForm;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
public class SubmitProtocolAction extends AbstractDispatchAction {
public ActionForward submit(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = null;
ActionMessages msgs = new ActionMessages();
DynaValidatorForm theForm = (DynaValidatorForm) form;
String protocolName = (String)theForm.get("protocolId");
String protocolType = (String)theForm.get("protocolType");
ProtocolFileBean fileBean = (ProtocolFileBean) theForm.get("file");
//String version = fileBean.getId();
ProtocolBean pBean = new ProtocolBean();
pBean.setId(protocolName);
pBean.setType(protocolType);
FormFile uploadedFile = (FormFile) theForm.get("uploadedFile");
fileBean.setProtocolBean(pBean);
SubmitProtocolService service = new SubmitProtocolService();
service.createProtocol(fileBean, uploadedFile);
if (fileBean.getVisibilityGroups().length == 0) {
fileBean
.setVisibilityGroups(CaNanoLabConstants.VISIBLE_GROUPS);
}
request.getSession().removeAttribute("AllProtocolTypeNames");
request.getSession().removeAttribute("AllProtocolTypeIds");
request.getSession().removeAttribute("protocolNames");
request.getSession().removeAttribute("AllProtocolNameVersions");
request.getSession().removeAttribute("AllProtocolNameFileIds");
request.getSession().removeAttribute("protocolVersions");
ActionMessage msg1 = new ActionMessage("message.submitProtocol.secure",
StringUtils.join(fileBean.getVisibilityGroups(), ", "));
ActionMessage msg2 = new ActionMessage("message.submitProtocol.file",
uploadedFile.getFileName());
msgs.add("message", msg1);
msgs.add("message", msg2);
saveMessages(request, msgs);
//request.getSession().setAttribute("newReportCreated", "true");
forward = mapping.findForward("success");
return forward;
}
public ActionForward getFileData(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = null;
DynaValidatorForm theForm = (DynaValidatorForm) form;
ProtocolFileBean fileBean = (ProtocolFileBean) theForm.get("file");
String fileId = fileBean.getId();
SearchProtocolService service = new SearchProtocolService();
ProtocolFileBean anotherBean = service.getProtocolFileBean(fileId);
fileBean.setDescription(anotherBean.getDescription());
fileBean.setName(anotherBean.getName());
fileBean.setTitle(anotherBean.getTitle());
fileBean.setVersion(anotherBean.getVersion());
fileBean.setVisibilityGroups(anotherBean.getVisibilityGroups());
request.setAttribute("filename", anotherBean.getName());
updateAfterFileDataRetrieval(request, theForm);
forward = mapping.findForward("resetProtocolPage");
return forward;
}
public ActionForward setup(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
InitSessionSetup.getInstance().clearWorkflowSession(session);
InitSessionSetup.getInstance().clearSearchSession(session);
InitSessionSetup.getInstance().clearInventorySession(session);
InitSessionSetup.getInstance().setApplicationOwner(session);
InitSessionSetup.getInstance().setProtocolSubmitPage(session);
InitSessionSetup.getInstance().setAllVisibilityGroups(session);
ActionForward forward = mapping.findForward("setup");
return forward;
}
public ActionForward setupUpdate(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
InitSessionSetup.getInstance().clearSearchSession(session);
InitSessionSetup.getInstance().setAllVisibilityGroups(session);
DynaValidatorForm theForm = (DynaValidatorForm) form;
String fileId = request.getParameter("fileId");
if (fileId == null)
fileId = (String)request.getAttribute("fileId");
SearchProtocolService service = new SearchProtocolService();
ProtocolFileBean fileBean=service.getWholeProtocolFileBean(fileId);
theForm.set("file", fileBean);
theForm.set("protocolName", fileBean.getProtocolBean().getName());
theForm.set("protocolType", fileBean.getProtocolBean().getType());
request.setAttribute("filename", fileBean.getName());
return mapping.findForward("setup");
}
public ActionForward setupView(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
return setupUpdate(mapping, form, request, response);
}
public ActionForward update(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionMessages msgs = new ActionMessages();
DynaValidatorForm theForm = (DynaValidatorForm) form;
ProtocolFileBean fileBean = (ProtocolFileBean) theForm.get("file");
//FormFile uploadedFile = (FormFile) theForm.get("uploadedFile");
SubmitProtocolService service = new SubmitProtocolService();
try{
service.updateProtocol(fileBean, null);
if (fileBean.getVisibilityGroups().length == 0) {
fileBean
.setVisibilityGroups(CaNanoLabConstants.VISIBLE_GROUPS);
}
}catch (Exception e){
ActionMessage msg = new ActionMessage("error.updateProtocol", e.getMessage());
msgs.add("message", msg);
saveMessages(request, msgs);
request.setAttribute("fileId", fileBean.getId());
return setupUpdate(mapping, form, request, response);
}
ActionMessage msg = new ActionMessage("message.updateProtocol", fileBean
.getTitle());
msgs.add("message", msg);
saveMessages(request, msgs);
//request.getSession().setAttribute("newProtocolCreated", "true");
return mapping.findForward("success");
}
public ActionForward reSetup(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
updateEditableDropDownList(request, theForm);
return mapping.findForward("setup");
}
public boolean loginRequired() {
return true;
}
private void updateEditableDropDownList(HttpServletRequest request,
DynaValidatorForm theForm) {
HttpSession session = request.getSession();
// update sample source drop-down list to include the new entry
String protocolType = (String) theForm.get("protocolType");
SortedSet<String> protocolTypes = (SortedSet) session.getAttribute("protocolTypes");
String protocolName = (String) theForm.get("protocolId");
ProtocolFileBean fileBean = (ProtocolFileBean) theForm.get("file");
String fileId = fileBean.getId();
//Update protocolType list first.
//If user entered a brand new protocol type, then added to the protocol type list
boolean isNewType = false;
if (protocolType != null && protocolType.length()>0
&& !protocolTypes.contains(protocolType)) {
protocolTypes.add(protocolType);
isNewType = true;
}
//otherwise don't do anything
//Update protocol name list.
boolean isNewName = false;
Map<String, List<String>> typeNamesMap = (Map)session.getAttribute("AllProtocolTypeNames");
Map<String, List<String>> typeIdsMap = (Map)session.getAttribute("AllProtocolTypeIds");
if (protocolName != null && protocolName.length()>0 ){
//if it's a new protocol type, we need to add this protocol name to the above two maps
if (isNewType){
List<String> newNameList = new ArrayList<String>();
List<String> newIdList = new ArrayList<String>();
newNameList.add(protocolName);
newIdList.add(protocolName);
typeNamesMap.put(protocolType, newNameList);
typeIdsMap.put(protocolType, newIdList);
//always a new name
isNewName = true;
}
//if an old type. if this is a new name then added to the list
else{
List<String> newNameList = typeNamesMap.get(protocolType);
List<String> newIdList = typeIdsMap.get(protocolType);
//A new name
if (newNameList == null)
isNewName = true;
else if (newNameList!= null && !newIdList.contains(protocolName)){
newNameList.add(protocolName);
newIdList.add(protocolName);
isNewName = true;
}
}
}
//Else don't do anything.
//Now set the name dropdown box
SortedSet<ProtocolBean> protocols = new TreeSet<ProtocolBean>();
if (protocolType != null && protocolType.length()>0){
List<String> protocolNames = typeNamesMap.get(protocolType);
List<String> protocolIds = typeIdsMap.get(protocolType);
if (protocolNames != null && !protocolNames.isEmpty()){
int i = 0;
for (String id : protocolIds){
ProtocolBean pb = new ProtocolBean();
pb.setId(id);
pb.setName(protocolNames.get(i));
protocols.add(pb);
i++;
}
}
//A protocol type with no protocol created
else if (protocolName != null && protocolName.length()>0){
ProtocolBean pb = new ProtocolBean();
pb.setId(protocolName);
pb.setName(protocolName);
protocols.add(pb);
}
}
else{
if (protocolName != null && protocolName.length()>0 ){
ProtocolBean pb = new ProtocolBean();
pb.setId(protocolName);
pb.setName(protocolName);
protocols.add(pb);
}
}
session.setAttribute("protocolNames", protocols);
//Now deal with the version dropdown box
boolean isNewVersion = false;
Map<String, List<String>> nameVersionsMap = (Map)session.getAttribute("AllProtocolNameVersions");
Map<String, List<String>> nameIdsMap = (Map)session.getAttribute("AllProtocolNameFileIds");
if (fileId != null && fileId.length()>0 ){
//if it's a new protocol name, we need to add this protocol
//version to the above two maps
if (isNewName){
List<String> newVersionList = new ArrayList<String>();
List<String> newVersionIdList = new ArrayList<String>();
newVersionList.add(fileId);
newVersionIdList.add(fileId);
nameVersionsMap.put(protocolName, newVersionList);
nameIdsMap.put(protocolName, newVersionIdList);
}
//if an old name. if this is a new version then added to the list
else{
//must check the name field is not empty
if (protocolName != null && protocolName.length()>0){
List<String> newVersionList = nameVersionsMap.get(protocolName);
List<String> newVersionIdList = nameIdsMap.get(protocolName);
if (newVersionIdList!= null && !newVersionIdList.contains(fileId)){
newVersionList.add(fileId);
newVersionIdList.add(fileId);
}
}
//else then there is no correlation, but we still add it to the
//dropdown box.
else {
isNewVersion = true;
}
}
}
//Let build version dropdown box
SortedSet<LabelValueBean> myProtocolFiles = new TreeSet<LabelValueBean>();
if (isNewVersion){
LabelValueBean pfb = new LabelValueBean(fileId, fileId);
myProtocolFiles.add(pfb);
}
else if (protocolName != null && protocolName.length()>0){
List<String> fileVersions = nameVersionsMap.get(protocolName);
List<String> fileIds = nameIdsMap.get(protocolName);
if (fileVersions != null && !fileVersions.isEmpty()){
int i = 0;
for (String version : fileVersions){
LabelValueBean pfb = new LabelValueBean(version, fileIds.get(i));
//pfb.setVersion(version);
//pfb.setId(fileIds.get(i));
myProtocolFiles.add(pfb);
i++;
}
}
}
session.setAttribute("protocolVersions", myProtocolFiles);
}
private void updateAfterFileDataRetrieval(HttpServletRequest request,
DynaValidatorForm theForm) {
HttpSession session = request.getSession();
// update sample source drop-down list to include the new entry
String protocolType = (String) theForm.get("protocolType");
//List<String> protocolTypes = (List) session.getAttribute("protocolTypes");
String protocolId = (String) theForm.get("protocolId");
Map<String, List<String>> typeNamesMap = (Map)session.getAttribute("AllProtocolTypeNames");
Map<String, List<String>> typeIdsMap = (Map)session.getAttribute("AllProtocolTypeIds");
//Set protocol name dropdown box
List<String> protocolNames = typeNamesMap.get(protocolType);
List<String> protocolIds = typeIdsMap.get(protocolType);
int i = 0;
SortedSet<ProtocolBean> protocols = new TreeSet<ProtocolBean>();
for (String id : protocolIds){
ProtocolBean pb = new ProtocolBean();
pb.setId(id);
pb.setName(protocolNames.get(i));
protocols.add(pb);
i++;
}
session.setAttribute("protocolNames", protocols);
// Now set protocol version dropdown box
Map<String, List<String>> nameVersionsMap = (Map)session.getAttribute("AllProtocolNameVersions");
Map<String, List<String>> nameIdsMap = (Map)session.getAttribute("AllProtocolNameFileIds");
List<String> fileVersions = nameVersionsMap.get(protocolId);
List<String> fileIds = nameIdsMap.get(protocolId);
i = 0;
SortedSet<LabelValueBean> myProtocolFiles = new TreeSet<LabelValueBean>();
for (String version : fileVersions){
LabelValueBean pfb = new LabelValueBean(version, fileIds.get(i));
//pfb.setVersion(version);
//pfb.setId(fileIds.get(i));
myProtocolFiles.add(pfb);
i++;
}
session.setAttribute("protocolVersions", myProtocolFiles);
}
} |
package acr.browser.lightning;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.*;
import android.content.res.Configuration;
import android.content.res.Resources.Theme;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Browser;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.*;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.DecelerateInterpolator;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.*;
import android.webkit.WebChromeClient.CustomViewCallback;
import android.webkit.WebView.HitTestResult;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.OnEditorActionListener;
import info.guardianproject.onionkit.ui.OrbotHelper;
import info.guardianproject.onionkit.web.WebkitProxy;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
public class BrowserActivity extends Activity implements BrowserController {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private RelativeLayout mDrawer;
private LinearLayout mDrawerRight;
private ListView mDrawerListRight;
private RelativeLayout mNewTab;
private ActionBarDrawerToggle mDrawerToggle;
private List<LightningView> mWebViews = new ArrayList<LightningView>();
private List<Integer> mIdList = new ArrayList<Integer>();
private LightningView mCurrentView;
private int mIdGenerator;
private LightningViewAdapter mTitleAdapter;
private List<HistoryItem> mBookmarkList;
private BookmarkViewAdapter mBookmarkAdapter;
private AutoCompleteTextView mSearch;
private ClickHandler mClickHandler;
private ProgressBar mProgressBar;
private boolean mSystemBrowser = false;
private ValueCallback<Uri> mUploadMessage;
private View mCustomView;
private int mOriginalOrientation;
private int mActionBarSize;
private ActionBar mActionBar;
private boolean mFullScreen;
private FrameLayout mBrowserFrame;
private FullscreenHolder mFullscreenContainer;
private CustomViewCallback mCustomViewCallback;
private final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
private Bitmap mDefaultVideoPoster;
private View mVideoProgressView;
private DatabaseHandler mHistoryHandler;
private SQLiteDatabase mHistoryDatabase;
private SharedPreferences mPreferences;
private SharedPreferences.Editor mEditPrefs;
private Context mContext;
private Bitmap mWebpageBitmap;
private String mSearchText;
private Activity mActivity;
private final int API = android.os.Build.VERSION.SDK_INT;
private Drawable mDeleteIcon;
private Drawable mRefreshIcon;
private Drawable mCopyIcon;
private Drawable mIcon;
private int mActionBarSizeDp;
private int mNumberIconColor;
private String mHomepage;
private boolean mIsNewIntent = false;
private VideoView mVideoView;
private static SearchAdapter mSearchAdapter;
private static LayoutParams mMatchParent = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initialize();
}
@SuppressWarnings("deprecation")
private synchronized void initialize() {
setContentView(R.layout.activity_main);
TypedValue typedValue = new TypedValue();
Theme theme = getTheme();
theme.resolveAttribute(R.attr.numberColor, typedValue, true);
mNumberIconColor = typedValue.data;
mPreferences = getSharedPreferences(PreferenceConstants.PREFERENCES, 0);
mEditPrefs = mPreferences.edit();
mContext = this;
if (mIdList != null) {
mIdList.clear();
} else {
mIdList = new ArrayList<Integer>();
}
if (mWebViews != null) {
mWebViews.clear();
} else {
mWebViews = new ArrayList<LightningView>();
}
mActivity = this;
mClickHandler = new ClickHandler(this);
mBrowserFrame = (FrameLayout) findViewById(R.id.content_frame);
mProgressBar = (ProgressBar) findViewById(R.id.activity_bar);
mProgressBar.setVisibility(View.GONE);
mNewTab = (RelativeLayout) findViewById(R.id.new_tab_button);
mDrawer = (RelativeLayout) findViewById(R.id.drawer);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setDivider(null);
mDrawerList.setDividerHeight(0);
mDrawerRight = (LinearLayout) findViewById(R.id.right_drawer);
mDrawerListRight = (ListView) findViewById(R.id.right_drawer_list);
mDrawerListRight.setDivider(null);
mDrawerListRight.setDividerHeight(0);
setNavigationDrawerWidth();
mWebpageBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_webpage);
mActionBar = getActionBar();
final TypedArray styledAttributes = mContext.getTheme().obtainStyledAttributes(
new int[] { android.R.attr.actionBarSize });
mActionBarSize = (int) styledAttributes.getDimension(0, 0);
if (pixelsToDp(mActionBarSize) < 48) {
mActionBarSize = getDp(48);
}
mActionBarSizeDp = pixelsToDp(mActionBarSize);
styledAttributes.recycle();
mHomepage = mPreferences.getString(PreferenceConstants.HOMEPAGE, Constants.HOMEPAGE);
mTitleAdapter = new LightningViewAdapter(this, R.layout.tab_list_item, mWebViews);
mDrawerList.setAdapter(mTitleAdapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerList.setOnItemLongClickListener(new DrawerItemLongClickListener());
mBookmarkList = getBookmarks();
mBookmarkAdapter = new BookmarkViewAdapter(this, R.layout.bookmark_list_item, mBookmarkList);
mDrawerListRight.setAdapter(mBookmarkAdapter);
mDrawerListRight.setOnItemClickListener(new BookmarkItemClickListener());
mDrawerListRight.setOnItemLongClickListener(new BookmarkItemLongClickListener());
if (mHistoryHandler == null) {
mHistoryHandler = new DatabaseHandler(this);
} else if (!mHistoryHandler.isOpen()) {
mHistoryHandler = new DatabaseHandler(this);
}
mHistoryDatabase = mHistoryHandler.getReadableDatabase();
// set display options of the ActionBar
mActionBar.setDisplayShowTitleEnabled(false);
mActionBar.setDisplayShowCustomEnabled(true);
mActionBar.setDisplayShowHomeEnabled(true);
mActionBar.setDisplayHomeAsUpEnabled(true);
mActionBar.setCustomView(R.layout.search);
RelativeLayout back = (RelativeLayout) findViewById(R.id.action_back);
RelativeLayout forward = (RelativeLayout) findViewById(R.id.action_forward);
if (back != null) {
back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mCurrentView != null) {
if (mCurrentView.canGoBack()) {
mCurrentView.goBack();
} else {
deleteTab(mDrawerList.getCheckedItemPosition());
}
}
}
});
}
if (forward != null) {
forward.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mCurrentView != null) {
if (mCurrentView.canGoForward()) {
mCurrentView.goForward();
}
}
}
});
}
// create the search EditText in the ActionBar
mSearch = (AutoCompleteTextView) mActionBar.getCustomView().findViewById(R.id.search);
mDeleteIcon = getResources().getDrawable(R.drawable.ic_action_delete);
mDeleteIcon.setBounds(0, 0, Utils.convertToDensityPixels(mContext, 24),
Utils.convertToDensityPixels(mContext, 24));
mRefreshIcon = getResources().getDrawable(R.drawable.ic_action_refresh);
mRefreshIcon.setBounds(0, 0, Utils.convertToDensityPixels(mContext, 24),
Utils.convertToDensityPixels(mContext, 24));
mCopyIcon = getResources().getDrawable(R.drawable.ic_action_copy);
mCopyIcon.setBounds(0, 0, Utils.convertToDensityPixels(mContext, 24),
Utils.convertToDensityPixels(mContext, 24));
mIcon = mRefreshIcon;
mSearch.setCompoundDrawables(null, null, mRefreshIcon, null);
mSearch.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
switch (arg1) {
case KeyEvent.KEYCODE_ENTER:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mSearch.getWindowToken(), 0);
searchTheWeb(mSearch.getText().toString());
if (mCurrentView != null) {
mCurrentView.requestFocus();
}
return true;
default:
break;
}
return false;
}
});
mSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus && mCurrentView != null) {
if (mCurrentView != null) {
if (mCurrentView.getProgress() < 100) {
setIsLoading();
} else {
setIsFinishedLoading();
}
}
updateUrl(mCurrentView.getUrl());
} else if (hasFocus) {
mIcon = mCopyIcon;
mSearch.setCompoundDrawables(null, null, mCopyIcon, null);
}
}
});
mSearch.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView arg0, int actionId, KeyEvent arg2) {
// hide the keyboard and search the web when the enter key
// button is pressed
if (actionId == EditorInfo.IME_ACTION_GO || actionId == EditorInfo.IME_ACTION_DONE
|| actionId == EditorInfo.IME_ACTION_NEXT
|| actionId == EditorInfo.IME_ACTION_SEND
|| actionId == EditorInfo.IME_ACTION_SEARCH
|| (arg2.getAction() == KeyEvent.KEYCODE_ENTER)) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mSearch.getWindowToken(), 0);
searchTheWeb(mSearch.getText().toString());
if (mCurrentView != null) {
mCurrentView.requestFocus();
}
return true;
}
return false;
}
});
mSearch.setOnTouchListener(new OnTouchListener() {
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View v, MotionEvent event) {
if (mSearch.getCompoundDrawables()[2] != null) {
boolean tappedX = event.getX() > (mSearch.getWidth()
- mSearch.getPaddingRight() - mIcon.getIntrinsicWidth());
if (tappedX) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (mSearch.hasFocus()) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", mSearch.getText()
.toString());
clipboard.setPrimaryClip(clip);
Utils.showToast(
mContext,
mContext.getResources().getString(
R.string.message_text_copied));
} else {
refreshOrStop();
}
}
return true;
}
}
return false;
}
});
mSystemBrowser = getSystemBrowser();
Thread initialize = new Thread(new Runnable() {
@Override
public void run() {
initializeSearchSuggestions(mSearch);
}
});
initialize.run();
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
@Override
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
if (view.equals(mDrawer)) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, mDrawerRight);
} else if (view.equals(mDrawerRight)) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, mDrawer);
}
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (drawerView.equals(mDrawer)) {
mDrawerLayout.closeDrawer(mDrawerRight);
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED,
mDrawerRight);
} else if (drawerView.equals(mDrawerRight)) {
mDrawerLayout.closeDrawer(mDrawer);
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, mDrawer);
}
}
};
mNewTab.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
newTab(null, true);
}
});
mNewTab.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
String url = mPreferences.getString(PreferenceConstants.SAVE_URL, null);
if (url != null) {
newTab(url, true);
Toast.makeText(mContext, R.string.deleted_tab, Toast.LENGTH_SHORT).show();
}
mEditPrefs.putString(PreferenceConstants.SAVE_URL, null).apply();
return true;
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_right_shadow, GravityCompat.END);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
initializePreferences();
initializeTabs();
if (API < 19) {
WebIconDatabase.getInstance().open(getDir("icons", MODE_PRIVATE).getPath());
}
checkForTor();
}
/*
* If Orbot/Tor is installed, prompt the user if they want to enable
* proxying for this session
*/
public boolean checkForTor() {
boolean useProxy = mPreferences.getBoolean(PreferenceConstants.USE_PROXY, false);
OrbotHelper oh = new OrbotHelper(this);
if (oh.isOrbotInstalled()
&& !mPreferences.getBoolean(PreferenceConstants.INITIAL_CHECK_FOR_TOR, false)) {
mEditPrefs.putBoolean(PreferenceConstants.INITIAL_CHECK_FOR_TOR, true);
mEditPrefs.apply();
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
mPreferences.edit().putBoolean(PreferenceConstants.USE_PROXY, true)
.apply();
initializeTor();
break;
case DialogInterface.BUTTON_NEGATIVE:
mPreferences.edit().putBoolean(PreferenceConstants.USE_PROXY, false)
.apply();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.use_tor_prompt)
.setPositiveButton(R.string.yes, dialogClickListener)
.setNegativeButton(R.string.no, dialogClickListener).show();
return true;
} else if (oh.isOrbotInstalled() & useProxy == true) {
initializeTor();
return true;
} else {
mEditPrefs.putBoolean(PreferenceConstants.USE_PROXY, false);
mEditPrefs.apply();
return false;
}
}
/*
* Initialize WebKit Proxying for Tor
*/
public void initializeTor() {
OrbotHelper oh = new OrbotHelper(this);
if (!oh.isOrbotRunning()) {
oh.requestOrbotStart(this);
}
try {
String host = mPreferences.getString(PreferenceConstants.USE_PROXY_HOST, "localhost");
int port = mPreferences.getInt(PreferenceConstants.USE_PROXY_PORT, 8118);
WebkitProxy.setProxy("acr.browser.lightning.BrowserApp", getApplicationContext(), host,
port);
} catch (Exception e) {
Log.d(Constants.TAG, "error enabling web proxying", e);
}
}
public void setNavigationDrawerWidth() {
int width = getResources().getDisplayMetrics().widthPixels * 3 / 4;
int maxWidth = Utils.convertToDensityPixels(mContext, 300);
if (width > maxWidth) {
DrawerLayout.LayoutParams params = (android.support.v4.widget.DrawerLayout.LayoutParams) mDrawer
.getLayoutParams();
params.width = maxWidth;
mDrawer.setLayoutParams(params);
DrawerLayout.LayoutParams paramsRight = (android.support.v4.widget.DrawerLayout.LayoutParams) mDrawerRight
.getLayoutParams();
paramsRight.width = maxWidth;
mDrawerRight.setLayoutParams(paramsRight);
} else {
DrawerLayout.LayoutParams params = (android.support.v4.widget.DrawerLayout.LayoutParams) mDrawer
.getLayoutParams();
params.width = width;
mDrawer.setLayoutParams(params);
DrawerLayout.LayoutParams paramsRight = (android.support.v4.widget.DrawerLayout.LayoutParams) mDrawerRight
.getLayoutParams();
paramsRight.width = width;
mDrawerRight.setLayoutParams(paramsRight);
}
}
/*
* Override this class
*/
public synchronized void initializeTabs() {
}
public void restoreOrNewTab() {
mIdGenerator = 0;
String url = null;
if (getIntent() != null) {
url = getIntent().getDataString();
if (url != null) {
if (url.startsWith(Constants.FILE)) {
Utils.showToast(this, getResources().getString(R.string.message_blocked_local));
url = null;
}
}
}
if (mPreferences.getBoolean(PreferenceConstants.RESTORE_LOST_TABS, true)) {
String mem = mPreferences.getString(PreferenceConstants.URL_MEMORY, "");
mEditPrefs.putString(PreferenceConstants.URL_MEMORY, "");
String[] array = Utils.getArray(mem);
int count = 0;
for (int n = 0; n < array.length; n++) {
if (array[n].length() > 0) {
newTab(array[n], true);
count++;
}
}
if (url != null) {
newTab(url, true);
} else if (count == 0) {
newTab(null, true);
}
} else {
newTab(url, true);
}
}
public void initializePreferences() {
if (mPreferences == null) {
mPreferences = getSharedPreferences(PreferenceConstants.PREFERENCES, 0);
}
mFullScreen = mPreferences.getBoolean(PreferenceConstants.FULL_SCREEN, false);
if (mPreferences.getBoolean(PreferenceConstants.HIDE_STATUS_BAR, false)) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
switch (mPreferences.getInt(PreferenceConstants.SEARCH, 1)) {
case 0:
mSearchText = mPreferences.getString(PreferenceConstants.SEARCH_URL,
Constants.GOOGLE_SEARCH);
if (!mSearchText.startsWith(Constants.HTTP)
&& !mSearchText.startsWith(Constants.HTTPS)) {
mSearchText = Constants.GOOGLE_SEARCH;
}
break;
case 1:
mSearchText = Constants.GOOGLE_SEARCH;
break;
case 2:
mSearchText = Constants.ANDROID_SEARCH;
break;
case 3:
mSearchText = Constants.BING_SEARCH;
break;
case 4:
mSearchText = Constants.YAHOO_SEARCH;
break;
case 5:
mSearchText = Constants.STARTPAGE_SEARCH;
break;
case 6:
mSearchText = Constants.STARTPAGE_MOBILE_SEARCH;
break;
case 7:
mSearchText = Constants.DUCK_SEARCH;
break;
case 8:
mSearchText = Constants.DUCK_LITE_SEARCH;
break;
case 9:
mSearchText = Constants.BAIDU_SEARCH;
break;
case 10:
mSearchText = Constants.YANDEX_SEARCH;
break;
}
updateCookiePreference();
if (mPreferences.getBoolean(PreferenceConstants.USE_PROXY, false)) {
initializeTor();
} else {
try {
WebkitProxy.resetProxy("acr.browser.lightning.BrowserApp", getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
}
}
/*
* Override this if class overrides BrowserActivity
*/
public void updateCookiePreference() {
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
if (mSearch.hasFocus()) {
searchTheWeb(mSearch.getText().toString());
}
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
if (mDrawerLayout.isDrawerOpen(mDrawerRight)) {
mDrawerLayout.closeDrawer(mDrawerRight);
mDrawerLayout.openDrawer(mDrawer);
} else if (mDrawerLayout.isDrawerOpen(mDrawer)) {
mDrawerLayout.closeDrawer(mDrawer);
}
mDrawerToggle.syncState();
return true;
}
// Handle action buttons
switch (item.getItemId()) {
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(mDrawerRight)) {
mDrawerLayout.closeDrawer(mDrawerRight);
}
mDrawerToggle.syncState();
return true;
case R.id.action_back:
if (mCurrentView != null) {
if (mCurrentView.canGoBack()) {
mCurrentView.goBack();
}
}
return true;
case R.id.action_forward:
if (mCurrentView != null) {
if (mCurrentView.canGoForward()) {
mCurrentView.goForward();
}
}
return true;
case R.id.action_new_tab:
newTab(null, true);
return true;
case R.id.action_incognito:
startActivity(new Intent(this, IncognitoActivity.class));
return true;
case R.id.action_share:
if (!mCurrentView.getUrl().startsWith(Constants.FILE)) {
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
mCurrentView.getTitle());
String shareMessage = mCurrentView.getUrl();
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareMessage);
startActivity(Intent.createChooser(shareIntent,
getResources().getString(R.string.dialog_title_share)));
}
return true;
case R.id.action_bookmarks:
openBookmarks();
return true;
case R.id.action_copy:
if (mCurrentView != null) {
if (!mCurrentView.getUrl().startsWith(Constants.FILE)) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", mCurrentView.getUrl()
.toString());
clipboard.setPrimaryClip(clip);
Utils.showToast(mContext,
mContext.getResources().getString(R.string.message_link_copied));
}
}
return true;
case R.id.action_settings:
startActivity(new Intent(this, SettingsActivity.class));
return true;
case R.id.action_history:
openHistory();
return true;
case R.id.action_add_bookmark:
if (!mCurrentView.getUrl().startsWith(Constants.FILE)) {
addBookmark(this, mCurrentView.getTitle(), mCurrentView.getUrl());
}
return true;
case R.id.action_find:
findInPage();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* refreshes the underlying list of the Bookmark adapter since the bookmark
* adapter doesn't always change when notifyDataChanged gets called.
*/
private void notifyBookmarkDataSetChanged() {
mBookmarkAdapter.clear();
mBookmarkAdapter.addAll(mBookmarkList);
mBookmarkAdapter.notifyDataSetChanged();
}
/**
* method that shows a dialog asking what string the user wishes to search
* for. It highlights the text entered.
*/
private void findInPage() {
final AlertDialog.Builder finder = new AlertDialog.Builder(mActivity);
finder.setTitle(getResources().getString(R.string.action_find));
final EditText getHome = new EditText(this);
getHome.setHint(getResources().getString(R.string.search_hint));
finder.setView(getHome);
finder.setPositiveButton(getResources().getString(R.string.search_hint),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String text = getHome.getText().toString();
if (mCurrentView != null) {
mCurrentView.find(text);
}
}
});
finder.show();
}
/**
* The click listener for ListView in the navigation drawer
*/
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mIsNewIntent = false;
selectItem(position);
}
}
/**
* long click listener for Navigation Drawer
*/
private class DrawerItemLongClickListener implements ListView.OnItemLongClickListener {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
deleteTab(position);
return false;
}
}
private class BookmarkItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (mCurrentView != null) {
mCurrentView.loadUrl(mBookmarkList.get(position).getUrl());
}
// keep any jank from happening when the drawer is closed after the
// URL starts to load
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mDrawerLayout.closeDrawer(mDrawerRight);
}
}, 150);
}
}
private class BookmarkItemLongClickListener implements ListView.OnItemLongClickListener {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int position, long arg3) {
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
builder.setTitle(mContext.getResources().getString(R.string.action_bookmarks));
builder.setMessage(getResources().getString(R.string.dialog_bookmark))
.setCancelable(true)
.setPositiveButton(getResources().getString(R.string.action_new_tab),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
newTab(mBookmarkList.get(position).getUrl(), false);
mDrawerLayout.closeDrawers();
}
})
.setNegativeButton(getResources().getString(R.string.action_delete),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
deleteBookmark(mBookmarkList.get(position).getUrl());
}
})
.setNeutralButton(getResources().getString(R.string.action_edit),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
editBookmark(position);
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
}
/**
* Takes in the id of which bookmark was selected and shows a dialog that
* allows the user to rename and change the url of the bookmark
*
* @param id
* which id in the list was chosen
*/
public synchronized void editBookmark(final int id) {
final AlertDialog.Builder homePicker = new AlertDialog.Builder(mActivity);
homePicker.setTitle(getResources().getString(R.string.title_edit_bookmark));
final EditText getTitle = new EditText(mContext);
getTitle.setHint(getResources().getString(R.string.hint_title));
getTitle.setText(mBookmarkList.get(id).getTitle());
getTitle.setSingleLine();
final EditText getUrl = new EditText(mContext);
getUrl.setHint(getResources().getString(R.string.hint_url));
getUrl.setText(mBookmarkList.get(id).getUrl());
getUrl.setSingleLine();
LinearLayout layout = new LinearLayout(mContext);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(getTitle);
layout.addView(getUrl);
homePicker.setView(layout);
homePicker.setPositiveButton(getResources().getString(R.string.action_ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mBookmarkList.get(id).setTitle(getTitle.getText().toString());
mBookmarkList.get(id).setUrl(getUrl.getText().toString());
notifyBookmarkDataSetChanged();
File book = new File(getFilesDir(), "bookmarks");
File bookUrl = new File(getFilesDir(), "bookurl");
try {
BufferedWriter bookWriter = new BufferedWriter(new FileWriter(book));
BufferedWriter urlWriter = new BufferedWriter(new FileWriter(bookUrl));
Iterator<HistoryItem> iter = mBookmarkList.iterator();
HistoryItem item;
while (iter.hasNext()) {
item = iter.next();
bookWriter.write(item.getTitle());
urlWriter.write(item.getUrl());
bookWriter.newLine();
urlWriter.newLine();
}
bookWriter.close();
urlWriter.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
Collections.sort(mBookmarkList, new SortIgnoreCase());
notifyBookmarkDataSetChanged();
if (mCurrentView != null) {
if (mCurrentView.getUrl().startsWith(Constants.FILE)
&& mCurrentView.getUrl().endsWith("bookmarks.html")) {
openBookmarkPage(mCurrentView.getWebView());
}
}
}
});
homePicker.show();
}
/**
* displays the WebView contained in the LightningView Also handles the
* removal of previous views
*
* @param view
* the LightningView to show
*/
private synchronized void showTab(LightningView view) {
if (view == null) {
return;
}
mBrowserFrame.removeAllViews();
if (mCurrentView != null) {
mCurrentView.setForegroundTab(false);
mCurrentView.onPause();
}
mCurrentView = view;
mCurrentView.setForegroundTab(true);
if (mCurrentView.getWebView() != null) {
updateUrl(mCurrentView.getUrl());
updateProgress(mCurrentView.getProgress());
} else {
updateUrl("");
updateProgress(0);
}
mBrowserFrame.addView(mCurrentView.getWebView(), mMatchParent);
mCurrentView.onResume();
// Use a delayed handler to make the transition smooth
// otherwise it will get caught up with the showTab code
// and cause a janky motion
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mDrawerLayout.closeDrawers();
}
}, 150);
}
/**
* creates a new tab with the passed in URL if it isn't null
*/
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
}
public void handleNewIntent(Intent intent) {
if (mCurrentView == null) {
initialize();
}
String url = null;
if (intent != null) {
url = intent.getDataString();
}
int num = 0;
if (intent != null && intent.getExtras() != null) {
num = intent.getExtras().getInt(getPackageName() + ".Origin");
}
if (num == 1) {
mCurrentView.loadUrl(url);
} else if (url != null) {
if (url.startsWith(Constants.FILE)) {
Utils.showToast(this, getResources().getString(R.string.message_blocked_local));
url = null;
}
newTab(url, true);
mIsNewIntent = true;
}
}
@Override
public void closeEmptyTab() {
if (mCurrentView != null && mCurrentView.getWebView().copyBackForwardList().getSize() == 0) {
closeCurrentTab();
}
}
private void closeCurrentTab() {
// don't delete the tab because the browser will close and mess stuff up
}
private void selectItem(final int position) {
// update selected item and title, then close the drawer
showTab(mWebViews.get(position));
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
protected synchronized void newTab(String url, boolean show) {
mIsNewIntent = false;
LightningView startingTab = new LightningView(mActivity, url);
if (mIdGenerator == 0) {
startingTab.resumeTimers();
}
mIdList.add(mIdGenerator);
mIdGenerator++;
mWebViews.add(startingTab);
Drawable icon = writeOnDrawable(mWebViews.size());
mActionBar.setIcon(icon);
mTitleAdapter.notifyDataSetChanged();
if (show) {
mDrawerList.setItemChecked(mWebViews.size() - 1, true);
showTab(startingTab);
}
}
private synchronized void deleteTab(int position) {
if (position >= mWebViews.size()) {
return;
}
int current = mDrawerList.getCheckedItemPosition();
LightningView reference = mWebViews.get(position);
if (reference == null) {
return;
}
if (reference.getUrl() != null && !reference.getUrl().startsWith(Constants.FILE)) {
mEditPrefs.putString(PreferenceConstants.SAVE_URL, reference.getUrl()).apply();
}
boolean isShown = reference.isShown();
if (current > position) {
mIdList.remove(position);
mWebViews.remove(position);
mDrawerList.setItemChecked(current - 1, true);
reference.onDestroy();
} else if (mWebViews.size() > position + 1) {
mIdList.remove(position);
if (current == position) {
showTab(mWebViews.get(position + 1));
mWebViews.remove(position);
mDrawerList.setItemChecked(position, true);
} else {
mWebViews.remove(position);
}
reference.onDestroy();
} else if (mWebViews.size() > 1) {
mIdList.remove(position);
if (current == position) {
showTab(mWebViews.get(position - 1));
mWebViews.remove(position);
mDrawerList.setItemChecked(position - 1, true);
} else {
mWebViews.remove(position);
}
reference.onDestroy();
} else {
if (mCurrentView.getUrl() == null || mCurrentView.getUrl().startsWith(Constants.FILE)
|| mCurrentView.getUrl().equals(mHomepage)) {
closeActivity();
} else {
mIdList.remove(position);
mWebViews.remove(position);
if (mPreferences.getBoolean(PreferenceConstants.CLEAR_CACHE_EXIT, false)
&& mCurrentView != null && !isIncognito()) {
mCurrentView.clearCache(true);
Log.i(Constants.TAG, "Cache Cleared");
}
if (mPreferences.getBoolean(PreferenceConstants.CLEAR_HISTORY_EXIT, false)
&& !isIncognito()) {
clearHistory();
Log.i(Constants.TAG, "History Cleared");
}
if (mPreferences.getBoolean(PreferenceConstants.CLEAR_COOKIES_EXIT, false)
&& !isIncognito()) {
clearCookies();
Log.i(Constants.TAG, "Cookies Cleared");
}
if (reference != null) {
reference.pauseTimers();
reference.onDestroy();
}
mCurrentView = null;
mTitleAdapter.notifyDataSetChanged();
finish();
}
}
mTitleAdapter.notifyDataSetChanged();
Drawable icon = writeOnDrawable(mWebViews.size());
mActionBar.setIcon(icon);
if (mIsNewIntent && isShown) {
mIsNewIntent = false;
closeActivity();
}
Log.i(Constants.TAG, "deleted tab");
}
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (mPreferences.getBoolean(PreferenceConstants.CLEAR_CACHE_EXIT, false)
&& mCurrentView != null && !isIncognito()) {
mCurrentView.clearCache(true);
Log.i(Constants.TAG, "Cache Cleared");
}
if (mPreferences.getBoolean(PreferenceConstants.CLEAR_HISTORY_EXIT, false)
&& !isIncognito()) {
clearHistory();
Log.i(Constants.TAG, "History Cleared");
}
if (mPreferences.getBoolean(PreferenceConstants.CLEAR_COOKIES_EXIT, false)
&& !isIncognito()) {
clearCookies();
Log.i(Constants.TAG, "Cookies Cleared");
}
mCurrentView = null;
for (int n = 0; n < mWebViews.size(); n++) {
if (mWebViews.get(n) != null) {
mWebViews.get(n).onDestroy();
}
}
mWebViews.clear();
mTitleAdapter.notifyDataSetChanged();
finish();
}
return true;
}
@SuppressWarnings("deprecation")
public void clearHistory() {
this.deleteDatabase(DatabaseHandler.DATABASE_NAME);
WebViewDatabase m = WebViewDatabase.getInstance(this);
m.clearFormData();
m.clearHttpAuthUsernamePassword();
if (API < 18) {
m.clearUsernamePassword();
WebIconDatabase.getInstance().removeAllIcons();
}
if (mSystemBrowser) {
try {
Browser.clearHistory(getContentResolver());
} catch (NullPointerException ignored) {
}
}
SettingsController.setClearHistory(true);
Utils.trimCache(this);
}
public void clearCookies() {
CookieManager c = CookieManager.getInstance();
CookieSyncManager.createInstance(this);
c.removeAllCookie();
}
@Override
public void onBackPressed() {
if (!mActionBar.isShowing()) {
mActionBar.show();
}
if (mDrawerLayout.isDrawerOpen(mDrawer)) {
mDrawerLayout.closeDrawer(mDrawer);
} else if (mDrawerLayout.isDrawerOpen(mDrawerRight)) {
mDrawerLayout.closeDrawer(mDrawerRight);
} else {
if (mCurrentView != null) {
Log.i(Constants.TAG, "onBackPressed");
if (mCurrentView.canGoBack()) {
if (!mCurrentView.isShown()) {
onHideCustomView();
} else {
mCurrentView.goBack();
}
} else {
deleteTab(mDrawerList.getCheckedItemPosition());
}
} else {
Log.e(Constants.TAG, "So madness. Much confusion. Why happen.");
super.onBackPressed();
}
}
}
@Override
protected void onPause() {
super.onPause();
Log.i(Constants.TAG, "onPause");
if (mCurrentView != null) {
mCurrentView.pauseTimers();
mCurrentView.onPause();
}
if (mHistoryDatabase != null) {
if (mHistoryDatabase.isOpen()) {
mHistoryDatabase.close();
}
}
if (mHistoryHandler != null) {
if (mHistoryHandler.isOpen()) {
mHistoryHandler.close();
}
}
}
public void saveOpenTabs() {
if (mPreferences.getBoolean(PreferenceConstants.RESTORE_LOST_TABS, true)) {
String s = "";
for (int n = 0; n < mWebViews.size(); n++) {
if (mWebViews.get(n).getUrl() != null) {
s = s + mWebViews.get(n).getUrl() + "|$|SEPARATOR|$|";
}
}
mEditPrefs.putString(PreferenceConstants.URL_MEMORY, s);
mEditPrefs.commit();
}
}
@Override
protected void onDestroy() {
Log.i(Constants.TAG, "onDestroy");
if (mHistoryDatabase != null) {
if (mHistoryDatabase.isOpen()) {
mHistoryDatabase.close();
}
}
if (mHistoryHandler != null) {
if (mHistoryHandler.isOpen()) {
mHistoryHandler.close();
}
}
super.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
Log.i(Constants.TAG, "onResume");
if (SettingsController.getClearHistory()) {
}
if (mSearchAdapter != null) {
mSearchAdapter.refreshPreferences();
mSearchAdapter.refreshBookmarks();
}
if (mActionBar != null) {
if (!mActionBar.isShowing()) {
mActionBar.show();
}
}
if (mCurrentView != null) {
mCurrentView.resumeTimers();
mCurrentView.onResume();
if (mHistoryHandler == null) {
mHistoryHandler = new DatabaseHandler(this);
} else if (!mHistoryHandler.isOpen()) {
mHistoryHandler = new DatabaseHandler(this);
}
mHistoryDatabase = mHistoryHandler.getReadableDatabase();
mBookmarkList = getBookmarks();
notifyBookmarkDataSetChanged();
} else {
initialize();
}
initializePreferences();
if (mWebViews != null) {
for (int n = 0; n < mWebViews.size(); n++) {
if (mWebViews.get(n) != null) {
mWebViews.get(n).initializePreferences(this);
} else {
mWebViews.remove(n);
}
}
} else {
initialize();
}
}
/**
* searches the web for the query fixing any and all problems with the input
* checks if it is a search, url, etc.
*/
void searchTheWeb(String query) {
if (query.equals("")) {
return;
}
String SEARCH = mSearchText;
query = query.trim();
mCurrentView.stopLoading();
if (query.startsWith("www.")) {
query = Constants.HTTP + query;
} else if (query.startsWith("ftp.")) {
query = "ftp://" + query;
}
boolean containsPeriod = query.contains(".");
boolean isIPAddress = (TextUtils.isDigitsOnly(query.replace(".", ""))
&& (query.replace(".", "").length() >= 4) && query.contains("."));
boolean aboutScheme = query.contains("about:");
boolean validURL = (query.startsWith("ftp://") || query.startsWith(Constants.HTTP)
|| query.startsWith(Constants.FILE) || query.startsWith(Constants.HTTPS))
|| isIPAddress;
boolean isSearch = ((query.contains(" ") || !containsPeriod) && !aboutScheme);
if (isIPAddress
&& (!query.startsWith(Constants.HTTP) || !query.startsWith(Constants.HTTPS))) {
query = Constants.HTTP + query;
}
if (isSearch) {
try {
query = URLEncoder.encode(query, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
mCurrentView.loadUrl(SEARCH + query);
} else if (!validURL) {
mCurrentView.loadUrl(Constants.HTTP + query);
} else {
mCurrentView.loadUrl(query);
}
}
public void deleteBookmark(String url) {
File book = new File(getFilesDir(), "bookmarks");
File bookUrl = new File(getFilesDir(), "bookurl");
try {
BufferedWriter bookWriter = new BufferedWriter(new FileWriter(book));
BufferedWriter urlWriter = new BufferedWriter(new FileWriter(bookUrl));
Iterator<HistoryItem> iter = mBookmarkList.iterator();
HistoryItem item;
int num = 0;
int deleteIndex = -1;
while (iter.hasNext()) {
item = iter.next();
if (!item.getUrl().equalsIgnoreCase(url)) {
bookWriter.write(item.getTitle());
urlWriter.write(item.getUrl());
bookWriter.newLine();
urlWriter.newLine();
} else {
deleteIndex = num;
}
num++;
}
if (deleteIndex != -1) {
mBookmarkList.remove(deleteIndex);
}
bookWriter.close();
urlWriter.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
notifyBookmarkDataSetChanged();
mSearchAdapter.refreshBookmarks();
openBookmarks();
}
/**
* converts the int num into density pixels
*
* @return density pixels
*/
private int getDp(int num) {
float scale = getResources().getDisplayMetrics().density;
return (int) (num * scale + 0.5f);
}
private int pixelsToDp(int num) {
float scale = getResources().getDisplayMetrics().density;
return (int) ((num - 0.5f) / scale);
}
/**
* writes the number of open tabs on the icon.
*/
public BitmapDrawable writeOnDrawable(int number) {
Bitmap bm = Bitmap.createBitmap(mActionBarSize, mActionBarSize, Config.ARGB_8888);
String text = number + "";
Paint paint = new Paint();
paint.setTextAlign(Paint.Align.CENTER);
paint.setAntiAlias(true);
paint.setStyle(Style.FILL);
paint.setColor(mNumberIconColor);
if (number > 99) {
number = 99;
}
// pixels, 36 dp
if (mActionBarSizeDp < 50) {
if (number > 9) {
paint.setTextSize(mActionBarSize * 3 / 4); // originally
// pixels,
// 24 dp
} else {
paint.setTextSize(mActionBarSize * 9 / 10); // originally 50
// pixels, 30 dp
}
} else {
paint.setTextSize(mActionBarSize * 3 / 4);
}
Canvas canvas = new Canvas(bm);
// originally only vertical padding of 5 pixels
int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 2));
canvas.drawText(text, xPos, yPos, paint);
return new BitmapDrawable(getResources(), bm);
}
public class LightningViewAdapter extends ArrayAdapter<LightningView> {
Context context;
int layoutResourceId;
List<LightningView> data = null;
public LightningViewAdapter(Context context, int layoutResourceId, List<LightningView> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
LightningViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new LightningViewHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.text1);
holder.favicon = (ImageView) row.findViewById(R.id.favicon1);
holder.exit = (ImageView) row.findViewById(R.id.delete1);
holder.exit.setTag(position);
row.setTag(holder);
} else {
holder = (LightningViewHolder) row.getTag();
}
holder.exit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
deleteTab(position);
}
});
LightningView web = data.get(position);
holder.txtTitle.setText(web.getTitle());
if (web.isForegroundTab()) {
holder.txtTitle.setTextAppearance(context, R.style.boldText);
} else {
holder.txtTitle.setTextAppearance(context, R.style.normalText);
}
Bitmap favicon = web.getFavicon();
if (web.isForegroundTab()) {
holder.favicon.setImageBitmap(favicon);
} else {
Bitmap grayscaleBitmap = Bitmap.createBitmap(favicon.getWidth(),
favicon.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(grayscaleBitmap);
Paint p = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(cm);
p.setColorFilter(filter);
c.drawBitmap(favicon, 0, 0, p);
holder.favicon.setImageBitmap(grayscaleBitmap);
}
return row;
}
class LightningViewHolder {
TextView txtTitle;
ImageView favicon;
ImageView exit;
}
}
public class BookmarkViewAdapter extends ArrayAdapter<HistoryItem> {
Context context;
int layoutResourceId;
List<HistoryItem> data = null;
public BookmarkViewAdapter(Context context, int layoutResourceId, List<HistoryItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
BookmarkViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new BookmarkViewHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.text1);
holder.favicon = (ImageView) row.findViewById(R.id.favicon1);
row.setTag(holder);
} else {
holder = (BookmarkViewHolder) row.getTag();
}
HistoryItem web = data.get(position);
holder.txtTitle.setText(web.getTitle());
holder.favicon.setImageBitmap(mWebpageBitmap);
if (web.getBitmap() == null) {
getImage(holder.favicon, web);
} else {
holder.favicon.setImageBitmap(web.getBitmap());
}
return row;
}
class BookmarkViewHolder {
TextView txtTitle;
ImageView favicon;
}
}
public void getImage(ImageView image, HistoryItem web) {
try {
new DownloadImageTask(image, web).execute(Constants.HTTP + getDomainName(web.getUrl())
+ "/favicon.ico");
} catch (URISyntaxException e) {
new DownloadImageTask(image, web)
.execute("https:
e.printStackTrace();
}
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
HistoryItem mWeb;
public DownloadImageTask(ImageView bmImage, HistoryItem web) {
this.bmImage = bmImage;
this.mWeb = web;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
// unique path for each url that is bookmarked.
String hash = String.valueOf(urldisplay.hashCode());
File image = new File(mContext.getCacheDir(), hash + ".png");
// checks to see if the image exists
if (!image.exists()) {
try {
// if not, download it...
URL url = new URL(urldisplay);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream in = connection.getInputStream();
if (in != null) {
mIcon = BitmapFactory.decodeStream(in);
}
// ...and cache it
if (mIcon != null) {
FileOutputStream fos = new FileOutputStream(image);
mIcon.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
Log.i(Constants.TAG, "Downloaded: " + urldisplay);
}
} catch (Exception e) {
} finally {
}
} else {
// if it exists, retrieve it from the cache
mIcon = BitmapFactory.decodeFile(image.getPath());
}
if (mIcon == null) {
try {
// if not, download it...
InputStream in = new java.net.URL(
"https:
.openStream();
if (in != null) {
mIcon = BitmapFactory.decodeStream(in);
}
// ...and cache it
if (mIcon != null) {
FileOutputStream fos = new FileOutputStream(image);
mIcon.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}
} catch (Exception e) {
}
}
if (mIcon == null) {
return mWebpageBitmap;
} else {
return mIcon;
}
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
mWeb.setBitmap(result);
notifyBookmarkDataSetChanged();
}
}
static String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
if (domain == null) {
return url;
}
return domain.startsWith("www.") ? domain.substring(4) : domain;
}
@Override
public void updateUrl(String url) {
if (url == null) {
return;
}
url = url.replaceFirst(Constants.HTTP, "");
if (url.startsWith(Constants.FILE)) {
url = "";
}
mSearch.setText(url);
}
@Override
public void updateProgress(int n) {
if (n > mProgressBar.getProgress()) {
ObjectAnimator animator = ObjectAnimator.ofInt(mProgressBar, "progress", n);
animator.setDuration(200);
animator.setInterpolator(new DecelerateInterpolator());
animator.start();
} else if (n < mProgressBar.getProgress()) {
ObjectAnimator animator = ObjectAnimator.ofInt(mProgressBar, "progress", 0, n);
animator.setDuration(200);
animator.setInterpolator(new DecelerateInterpolator());
animator.start();
}
if (n >= 100) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mProgressBar.setVisibility(View.INVISIBLE);
setIsFinishedLoading();
}
}, 200);
} else {
mProgressBar.setVisibility(View.VISIBLE);
setIsLoading();
}
}
@Override
public void updateHistory(final String title, final String url) {
}
public void addItemToHistory(final String title, final String url) {
Runnable update = new Runnable() {
@Override
public void run() {
if (isSystemBrowserAvailable()
&& mPreferences.getBoolean(PreferenceConstants.SYNC_HISTORY, true)) {
try {
Browser.updateVisitedHistory(getContentResolver(), url, true);
} catch (NullPointerException ignored) {
}
}
try {
StringBuilder sb = new StringBuilder("url" + " = ");
DatabaseUtils.appendEscapedSQLString(sb, url);
if (mHistoryHandler == null) {
mHistoryHandler = new DatabaseHandler(mContext);
mHistoryDatabase = mHistoryHandler.getReadableDatabase();
} else if (!mHistoryHandler.isOpen()) {
mHistoryHandler = new DatabaseHandler(mContext);
mHistoryDatabase = mHistoryHandler.getReadableDatabase();
} else if (mHistoryDatabase == null) {
mHistoryDatabase = mHistoryHandler.getReadableDatabase();
} else if (!mHistoryDatabase.isOpen()) {
mHistoryDatabase = mHistoryHandler.getReadableDatabase();
}
Cursor cursor = mHistoryDatabase.query(DatabaseHandler.TABLE_HISTORY,
new String[] { "id", "url", "title" }, sb.toString(), null, null, null,
null);
if (!cursor.moveToFirst()) {
mHistoryHandler.addHistoryItem(new HistoryItem(url, title));
} else {
mHistoryHandler.delete(url);
mHistoryHandler.addHistoryItem(new HistoryItem(url, title));
}
cursor.close();
cursor = null;
} catch (IllegalStateException e) {
Log.e(Constants.TAG, "IllegalStateException in updateHistory");
} catch (NullPointerException e) {
Log.e(Constants.TAG, "NullPointerException in updateHistory");
} catch (SQLiteException e) {
Log.e(Constants.TAG, "SQLiteException in updateHistory");
}
}
};
if (url != null && !url.startsWith(Constants.FILE)) {
new Thread(update).start();
}
}
public boolean isSystemBrowserAvailable() {
return mSystemBrowser;
}
public boolean getSystemBrowser() {
Cursor c = null;
String[] columns = new String[] { "url", "title" };
boolean browserFlag = false;
try {
Uri bookmarks = Browser.BOOKMARKS_URI;
c = getContentResolver().query(bookmarks, columns, null, null, null);
} catch (SQLiteException ignored) {
} catch (IllegalStateException ignored) {
} catch (NullPointerException ignored) {
}
if (c != null) {
Log.i("Browser", "System Browser Available");
browserFlag = true;
} else {
Log.e("Browser", "System Browser Unavailable");
browserFlag = false;
}
if (c != null) {
c.close();
c = null;
}
mEditPrefs.putBoolean("SystemBrowser", browserFlag);
mEditPrefs.commit();
return browserFlag;
}
/**
* method to generate search suggestions for the AutoCompleteTextView from
* previously searched URLs
*/
private void initializeSearchSuggestions(final AutoCompleteTextView getUrl) {
getUrl.setThreshold(1);
getUrl.setDropDownWidth(-1);
getUrl.setDropDownAnchor(R.id.progressWrapper);
getUrl.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
try {
String url;
url = ((TextView) arg1.findViewById(R.id.url)).getText().toString();
if (url.startsWith(mContext.getString(R.string.suggestion))) {
url = ((TextView) arg1.findViewById(R.id.title)).getText().toString();
} else {
getUrl.setText(url);
}
searchTheWeb(url);
url = null;
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getUrl.getWindowToken(), 0);
if (mCurrentView != null) {
mCurrentView.requestFocus();
}
} catch (NullPointerException e) {
Log.e("Browser Error: ", "NullPointerException on item click");
}
}
});
getUrl.setSelectAllOnFocus(true);
mSearchAdapter = new SearchAdapter(mContext, isIncognito());
getUrl.setAdapter(mSearchAdapter);
}
public boolean isIncognito() {
return false;
}
// Damn it, I regret not using SQLite in the first place for this
private List<HistoryItem> getBookmarks() {
List<HistoryItem> bookmarks = new ArrayList<HistoryItem>();
File bookUrl = new File(getApplicationContext().getFilesDir(), "bookurl");
File book = new File(getApplicationContext().getFilesDir(), "bookmarks");
try {
BufferedReader readUrl = new BufferedReader(new FileReader(bookUrl));
BufferedReader readBook = new BufferedReader(new FileReader(book));
String u, t;
while ((u = readUrl.readLine()) != null && (t = readBook.readLine()) != null) {
HistoryItem map = new HistoryItem(u, t);
bookmarks.add(map);
}
readBook.close();
readUrl.close();
} catch (FileNotFoundException ignored) {
} catch (IOException ignored) {
}
Collections.sort(bookmarks, new SortIgnoreCase());
return bookmarks;
}
/**
* returns a list of HistoryItems
*/
private List<HistoryItem> getLatestHistory() {
DatabaseHandler historyHandler = new DatabaseHandler(mContext);
return historyHandler.getLastHundredItems();
}
/**
* function that opens the HTML history page in the browser
*/
private void openHistory() {
Thread history = new Thread(new Runnable() {
@Override
public void run() {
String historyHtml = HistoryPageVariables.Heading;
List<HistoryItem> historyList = getLatestHistory();
Iterator<HistoryItem> it = historyList.iterator();
HistoryItem helper;
while (it.hasNext()) {
helper = it.next();
historyHtml += HistoryPageVariables.Part1 + helper.getUrl()
+ HistoryPageVariables.Part2 + helper.getTitle()
+ HistoryPageVariables.Part3 + helper.getUrl()
+ HistoryPageVariables.Part4;
}
historyHtml += HistoryPageVariables.End;
File historyWebPage = new File(getFilesDir(), "history.html");
try {
FileWriter hWriter = new FileWriter(historyWebPage, false);
hWriter.write(historyHtml);
hWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
mCurrentView.loadUrl(Constants.FILE + historyWebPage);
mSearch.setText("");
}
});
history.run();
}
/**
* helper function that opens the bookmark drawer
*/
private void openBookmarks() {
if (mDrawerLayout.isDrawerOpen(mDrawer)) {
mDrawerLayout.closeDrawers();
}
mDrawerToggle.syncState();
mDrawerLayout.openDrawer(mDrawerRight);
}
public void closeDrawers() {
mDrawerLayout.closeDrawers();
}
@Override
/**
* open the HTML bookmarks page, parameter view is the WebView that should show the page
*/
public void openBookmarkPage(WebView view) {
String bookmarkHtml = BookmarkPageVariables.Heading;
Iterator<HistoryItem> iter = mBookmarkList.iterator();
HistoryItem helper;
while (iter.hasNext()) {
helper = iter.next();
bookmarkHtml += (BookmarkPageVariables.Part1 + helper.getUrl()
+ BookmarkPageVariables.Part2 + helper.getUrl() + BookmarkPageVariables.Part3
+ helper.getTitle() + BookmarkPageVariables.Part4);
}
bookmarkHtml += BookmarkPageVariables.End;
File bookmarkWebPage = new File(mContext.getFilesDir(), "bookmarks.html");
try {
FileWriter bookWriter = new FileWriter(bookmarkWebPage, false);
bookWriter.write(bookmarkHtml);
bookWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
view.loadUrl(Constants.FILE + bookmarkWebPage);
}
/**
* adds a bookmark with a title and url. Simple.
*/
public void addBookmark(Context context, String title, String url) {
File book = new File(context.getFilesDir(), "bookmarks");
File bookUrl = new File(context.getFilesDir(), "bookurl");
HistoryItem bookmark = new HistoryItem(url, title);
try {
BufferedReader readUrlRead = new BufferedReader(new FileReader(bookUrl));
String u;
while ((u = readUrlRead.readLine()) != null) {
if (u.contentEquals(url)) {
readUrlRead.close();
return;
}
}
readUrlRead.close();
} catch (FileNotFoundException ignored) {
} catch (IOException ignored) {
} catch (NullPointerException ignored) {
}
try {
BufferedWriter bookWriter = new BufferedWriter(new FileWriter(book, true));
BufferedWriter urlWriter = new BufferedWriter(new FileWriter(bookUrl, true));
bookWriter.write(title);
urlWriter.write(url);
bookWriter.newLine();
urlWriter.newLine();
bookWriter.close();
urlWriter.close();
mBookmarkList.add(bookmark);
Collections.sort(mBookmarkList, new SortIgnoreCase());
notifyBookmarkDataSetChanged();
} catch (FileNotFoundException ignored) {
} catch (IOException ignored) {
} catch (NullPointerException ignored) {
}
mSearchAdapter.refreshBookmarks();
}
@Override
public void update() {
mTitleAdapter.notifyDataSetChanged();
}
@Override
/**
* opens a file chooser
* param ValueCallback is the message from the WebView indicating a file chooser
* should be opened
*/
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), 1);
}
@Override
/**
* used to allow uploading into the browser, doesn't get called in KitKat :(
*/
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 1) {
if (null == mUploadMessage) {
return;
}
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
@Override
/**
* handles long presses for the browser, tries to get the
* url of the item that was clicked and sends it (it can be null)
* to the click handler that does cool stuff with it
*/
public void onLongPress() {
if (mClickHandler == null) {
mClickHandler = new ClickHandler(mContext);
}
Message click = mClickHandler.obtainMessage();
if (click != null) {
click.setTarget(mClickHandler);
}
mCurrentView.getWebView().requestFocusNodeHref(click);
}
@Override
public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
if (view == null) {
return;
}
if (mCustomView != null && callback != null) {
callback.onCustomViewHidden();
return;
}
view.setKeepScreenOn(true);
mOriginalOrientation = getRequestedOrientation();
FrameLayout decor = (FrameLayout) getWindow().getDecorView();
mFullscreenContainer = new FullscreenHolder(this);
mCustomView = view;
mFullscreenContainer.addView(mCustomView, COVER_SCREEN_PARAMS);
decor.addView(mFullscreenContainer, COVER_SCREEN_PARAMS);
setFullscreen(true);
mCurrentView.setVisibility(View.GONE);
if (view instanceof FrameLayout) {
if (((FrameLayout) view).getFocusedChild() instanceof VideoView) {
mVideoView = (VideoView) ((FrameLayout) view).getFocusedChild();
mVideoView.setOnErrorListener(new VideoCompletionListener());
mVideoView.setOnCompletionListener(new VideoCompletionListener());
}
}
mCustomViewCallback = callback;
}
@Override
public void onHideCustomView() {
if (mCustomView == null || mCustomViewCallback == null || mCurrentView == null) {
return;
}
Log.i(Constants.TAG, "onHideCustomView");
mCurrentView.setVisibility(View.VISIBLE);
mCustomView.setKeepScreenOn(false);
setFullscreen(mPreferences.getBoolean(PreferenceConstants.HIDE_STATUS_BAR, false));
FrameLayout decor = (FrameLayout) getWindow().getDecorView();
if (decor != null) {
decor.removeView(mFullscreenContainer);
}
if (API < 19) {
try {
mCustomViewCallback.onCustomViewHidden();
} catch (Throwable ignored) {
}
}
mFullscreenContainer = null;
mCustomView = null;
if (mVideoView != null) {
mVideoView.setOnErrorListener(null);
mVideoView.setOnCompletionListener(null);
mVideoView = null;
}
setRequestedOrientation(mOriginalOrientation);
}
private class VideoCompletionListener implements MediaPlayer.OnCompletionListener,
MediaPlayer.OnErrorListener {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
@Override
public void onCompletion(MediaPlayer mp) {
onHideCustomView();
}
}
/**
* turns on fullscreen mode in the app
*
* @param enabled
* whether to enable fullscreen or not
*/
public void setFullscreen(boolean enabled) {
Window win = getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
final int bits = WindowManager.LayoutParams.FLAG_FULLSCREEN;
if (enabled) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
if (mCustomView != null) {
mCustomView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
} else {
mBrowserFrame.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
}
win.setAttributes(winParams);
}
/**
* a class extending FramLayout used to display fullscreen videos
*/
static class FullscreenHolder extends FrameLayout {
public FullscreenHolder(Context ctx) {
super(ctx);
setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent evt) {
return true;
}
}
@Override
/**
* a stupid method that returns the bitmap image to display in place of
* a loading video
*/
public Bitmap getDefaultVideoPoster() {
if (mDefaultVideoPoster == null) {
mDefaultVideoPoster = BitmapFactory.decodeResource(getResources(),
android.R.drawable.ic_media_play);
}
return mDefaultVideoPoster;
}
@SuppressLint("InflateParams")
@Override
/**
* dumb method that returns the loading progress for a video
*/
public View getVideoLoadingProgressView() {
if (mVideoProgressView == null) {
LayoutInflater inflater = LayoutInflater.from(this);
mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
}
return mVideoProgressView;
}
@Override
/**
* handles javascript requests to create a new window in the browser
*/
public void onCreateWindow(boolean isUserGesture, Message resultMsg) {
if (resultMsg == null) {
return;
}
newTab("", true);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(mCurrentView.getWebView());
resultMsg.sendToTarget();
}
@Override
/**
* returns the Activity instance for this activity,
* very helpful when creating things in other classes... I think
*/
public Activity getActivity() {
return mActivity;
}
/**
* it hides the action bar, seriously what else were you expecting
*/
@Override
public void hideActionBar() {
if (mActionBar.isShowing() && mFullScreen) {
mActionBar.hide();
}
}
@Override
/**
* obviously it shows the action bar if it's hidden
*/
public void showActionBar() {
if (!mActionBar.isShowing() && mFullScreen) {
mActionBar.show();
}
}
@Override
/**
* handles a long click on the page, parameter String url
* is the url that should have been obtained from the WebView touch node
* thingy, if it is null, this method tries to deal with it and find a workaround
*/
public void longClickPage(final String url) {
HitTestResult result = null;
if (mCurrentView.getWebView() != null) {
result = mCurrentView.getWebView().getHitTestResult();
}
if (url != null) {
if (result != null) {
if (result.getType() == HitTestResult.SRC_IMAGE_ANCHOR_TYPE
|| result.getType() == HitTestResult.IMAGE_TYPE) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
newTab(url, false);
break;
case DialogInterface.BUTTON_NEGATIVE:
mCurrentView.loadUrl(url);
break;
case DialogInterface.BUTTON_NEUTRAL:
if (API > 8) {
Utils.downloadFile(mActivity, url,
mCurrentView.getUserAgent(), "attachment", false);
}
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); // dialog
builder.setTitle(url.replace(Constants.HTTP, ""))
.setMessage(getResources().getString(R.string.dialog_image))
.setPositiveButton(getResources().getString(R.string.action_new_tab),
dialogClickListener)
.setNegativeButton(getResources().getString(R.string.action_open),
dialogClickListener)
.setNeutralButton(getResources().getString(R.string.action_download),
dialogClickListener).show();
} else {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
newTab(url, false);
break;
case DialogInterface.BUTTON_NEGATIVE:
mCurrentView.loadUrl(url);
break;
case DialogInterface.BUTTON_NEUTRAL:
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", url);
clipboard.setPrimaryClip(clip);
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); // dialog
builder.setTitle(url)
.setMessage(getResources().getString(R.string.dialog_link))
.setPositiveButton(getResources().getString(R.string.action_new_tab),
dialogClickListener)
.setNegativeButton(getResources().getString(R.string.action_open),
dialogClickListener)
.setNeutralButton(getResources().getString(R.string.action_copy),
dialogClickListener).show();
}
} else {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
newTab(url, false);
break;
case DialogInterface.BUTTON_NEGATIVE:
mCurrentView.loadUrl(url);
break;
case DialogInterface.BUTTON_NEUTRAL:
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", url);
clipboard.setPrimaryClip(clip);
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); // dialog
builder.setTitle(url)
.setMessage(getResources().getString(R.string.dialog_link))
.setPositiveButton(getResources().getString(R.string.action_new_tab),
dialogClickListener)
.setNegativeButton(getResources().getString(R.string.action_open),
dialogClickListener)
.setNeutralButton(getResources().getString(R.string.action_copy),
dialogClickListener).show();
}
} else if (result != null) {
if (result.getExtra() != null) {
final String newUrl = result.getExtra();
if (result.getType() == HitTestResult.SRC_IMAGE_ANCHOR_TYPE
|| result.getType() == HitTestResult.IMAGE_TYPE) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
newTab(newUrl, false);
break;
case DialogInterface.BUTTON_NEGATIVE:
mCurrentView.loadUrl(newUrl);
break;
case DialogInterface.BUTTON_NEUTRAL:
if (API > 8) {
Utils.downloadFile(mActivity, newUrl,
mCurrentView.getUserAgent(), "attachment", false);
}
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); // dialog
builder.setTitle(newUrl.replace(Constants.HTTP, ""))
.setMessage(getResources().getString(R.string.dialog_image))
.setPositiveButton(getResources().getString(R.string.action_new_tab),
dialogClickListener)
.setNegativeButton(getResources().getString(R.string.action_open),
dialogClickListener)
.setNeutralButton(getResources().getString(R.string.action_download),
dialogClickListener).show();
} else {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
newTab(newUrl, false);
break;
case DialogInterface.BUTTON_NEGATIVE:
mCurrentView.loadUrl(newUrl);
break;
case DialogInterface.BUTTON_NEUTRAL:
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", newUrl);
clipboard.setPrimaryClip(clip);
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); // dialog
builder.setTitle(newUrl)
.setMessage(getResources().getString(R.string.dialog_link))
.setPositiveButton(getResources().getString(R.string.action_new_tab),
dialogClickListener)
.setNegativeButton(getResources().getString(R.string.action_open),
dialogClickListener)
.setNeutralButton(getResources().getString(R.string.action_copy),
dialogClickListener).show();
}
}
}
}
/**
* This method lets the search bar know that the page is currently loading
* and that it should display the stop icon to indicate to the user that
* pressing it stops the page from loading
*/
public void setIsLoading() {
if (!mSearch.hasFocus()) {
mIcon = mDeleteIcon;
mSearch.setCompoundDrawables(null, null, mDeleteIcon, null);
}
}
/**
* This tells the search bar that the page is finished loading and it should
* display the refresh icon
*/
public void setIsFinishedLoading() {
if (!mSearch.hasFocus()) {
mIcon = mRefreshIcon;
mSearch.setCompoundDrawables(null, null, mRefreshIcon, null);
}
}
/**
* handle presses on the refresh icon in the search bar, if the page is
* loading, stop the page, if it is done loading refresh the page.
*
* See setIsFinishedLoading and setIsLoading for displaying the correct icon
*/
public void refreshOrStop() {
if (mCurrentView != null) {
if (mCurrentView.getProgress() < 100) {
mCurrentView.stopLoading();
} else {
mCurrentView.reload();
}
}
}
@Override
public boolean isActionBarShowing() {
if (mActionBar != null) {
return mActionBar.isShowing();
} else {
return false;
}
}
// Override this, use finish() for Incognito, moveTaskToBack for Main
public void closeActivity() {
finish();
}
public class SortIgnoreCase implements Comparator<HistoryItem> {
public int compare(HistoryItem o1, HistoryItem o2) {
return o1.getTitle().toLowerCase(Locale.getDefault())
.compareTo(o2.getTitle().toLowerCase(Locale.getDefault()));
}
}
} |
/* Pending
* 1) GUI
* 2) Make pending functionalities
* 3) Add functionality of exporting to Excel the traffic matrix
*/
package com.net2plan.gui.plugins.networkDesign.viewEditTopolTables.rightPanelTabs;
import cern.colt.matrix.tdouble.DoubleFactory2D;
import cern.colt.matrix.tdouble.DoubleMatrix2D;
import com.google.common.collect.Sets;
import com.net2plan.gui.plugins.GUINetworkDesign;
import com.net2plan.gui.plugins.networkDesign.CellRenderers;
import com.net2plan.gui.plugins.networkDesign.visualizationControl.VisualizationState;
import com.net2plan.gui.plugins.networkDesign.whatIfAnalysisPane.WhatIfAnalysisPane;
import com.net2plan.gui.utils.AdvancedJTable;
import com.net2plan.gui.utils.ClassAwareTableModel;
import com.net2plan.gui.utils.WiderJComboBox;
import com.net2plan.interfaces.networkDesign.*;
import com.net2plan.internal.Constants.NetworkElementType;
import com.net2plan.internal.ErrorHandling;
import com.net2plan.libraries.TrafficMatrixGenerationModels;
import com.net2plan.utils.Pair;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.collections15.BidiMap;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
public class NetPlanViewTableComponent_trafMatrix extends JPanel
{
private static final int OPTIONINDEX_TRAFFICMODEL_CONSTANT = 1;
private static final int OPTIONINDEX_TRAFFICMODEL_UNIFORM01 = 2;
private static final int OPTIONINDEX_TRAFFICMODEL_UNIFORM5050 = 3;
private static final int OPTIONINDEX_TRAFFICMODEL_UNIFORM2575 = 4;
private static final int OPTIONINDEX_TRAFFICMODEL_GRAVITYMODEL = 5;
private static final int OPTIONINDEX_TRAFFICMODEL_POPULATIONDISTANCE = 6;
private static final int OPTIONINDEX_TRAFFICMODEL_RESET = 7;
private static final int OPTIONINDEX_NORMALIZATION_MAKESYMMETRIC = 1;
private static final int OPTIONINDEX_NORMALIZATION_SCALE = 2;
private static final int OPTIONINDEX_NORMALIZATION_RANDOMVARIATION = 3;
private static final int OPTIONINDEX_NORMALIZATION_TOTAL = 4;
private static final int OPTIONINDEX_NORMALIZATION_PERNODETRAFOUT = 5;
private static final int OPTIONINDEX_NORMALIZATION_PERNODETRAFIN = 6;
private static final int OPTIONINDEX_NORMALIZATION_MAXIMUMSCALEDVERSION = 7;
private final JTable trafficMatrixTable;
private final JCheckBox filterOutNodesNotConnectedThisLayer;
private final JComboBox<String> cmb_tagNodesSelector;
private final JComboBox<String> cmb_tagDemandsSelector;
private final JComboBox<String> cmb_trafficModelPattern;
private final JComboBox<String> cmb_trafficNormalization;
private final JButton applyTrafficNormalizationButton;
private final JButton applyTrafficModelButton;
private final GUINetworkDesign networkViewer;
public NetPlanViewTableComponent_trafMatrix(GUINetworkDesign networkViewer)
{
super(new BorderLayout());
this.networkViewer = networkViewer;
this.trafficMatrixTable = new AdvancedJTable();
trafficMatrixTable.setDefaultRenderer(Object.class, new TotalRowColumnRenderer());
trafficMatrixTable.setDefaultRenderer(Double.class, new TotalRowColumnRenderer());
trafficMatrixTable.setDefaultRenderer(Number.class, new TotalRowColumnRenderer());
trafficMatrixTable.setDefaultRenderer(Integer.class, new TotalRowColumnRenderer());
trafficMatrixTable.setDefaultRenderer(String.class, new TotalRowColumnRenderer());
JScrollPane pane = new JScrollPane(trafficMatrixTable);
this.add(pane, BorderLayout.CENTER);
JPanel pnl_trafficModel = new JPanel();
pnl_trafficModel.setBorder(BorderFactory.createTitledBorder("Traffic matrix synthesis"));
cmb_trafficModelPattern = new WiderJComboBox();
cmb_trafficModelPattern.addItem("Select a method for synthesizing a matrix");
cmb_trafficModelPattern.addItem("1. Constant");
cmb_trafficModelPattern.addItem("2. Uniform (0, 10)");
cmb_trafficModelPattern.addItem("3. 50% Uniform (0, 100) & 50% Uniform(0, 10)");
cmb_trafficModelPattern.addItem("4. 25% Uniform (0, 100) & 75% Uniform(0, 10)");
cmb_trafficModelPattern.addItem("5. Gravity model");
cmb_trafficModelPattern.addItem("6. Population-distance model");
cmb_trafficModelPattern.addItem("7. Reset");
pnl_trafficModel.add(cmb_trafficModelPattern);
this.applyTrafficModelButton = new JButton("Apply");
applyTrafficModelButton.addActionListener(new CommonActionPerformListenerModelAndNormalization());
pnl_trafficModel.setLayout(new MigLayout("insets 0 0 0 0", "[grow][][]", "[grow]"));
pnl_trafficModel.add(cmb_trafficModelPattern, "grow, wmin 50");
pnl_trafficModel.add(applyTrafficModelButton);
JPanel pnl_normalization = new JPanel();
pnl_normalization.setBorder(BorderFactory.createTitledBorder("Traffic normalization and adjustments"));
cmb_trafficNormalization = new WiderJComboBox();
cmb_trafficNormalization.addItem("Select a method");
cmb_trafficNormalization.addItem("1. Make symmetric");
cmb_trafficNormalization.addItem("2. Scale by a factor");
cmb_trafficNormalization.addItem("3. Apply random variation (truncated gaussian)");
cmb_trafficNormalization.addItem("4. Normalization: fit to given total traffic");
cmb_trafficNormalization.addItem("5. Normalization: fit to given out traffic per node");
cmb_trafficNormalization.addItem("6. Normalization: fit to given in traffic per node");
cmb_trafficNormalization.addItem("7. Normalization: scale to theoretical maximum traffic");
pnl_normalization.add(cmb_trafficNormalization);
this.applyTrafficNormalizationButton = new JButton("Apply");
applyTrafficNormalizationButton.addActionListener(new CommonActionPerformListenerModelAndNormalization());
pnl_normalization.setLayout(new MigLayout("insets 0 0 0 0", "[grow][][]", "[grow]"));
pnl_normalization.add(cmb_trafficNormalization, "grow, wmin 50");
pnl_normalization.add(applyTrafficNormalizationButton);
final JPanel filterPanel = new JPanel(new MigLayout("wrap 2", "[][grow]"));
filterPanel.setBorder(BorderFactory.createTitledBorder("Filters"));
this.filterOutNodesNotConnectedThisLayer = new JCheckBox();
filterPanel.add(new JLabel("Filter out linkless nodes at this layer"), "align label");
filterPanel.add(filterOutNodesNotConnectedThisLayer);
this.cmb_tagNodesSelector = new WiderJComboBox();
this.cmb_tagDemandsSelector = new WiderJComboBox();
cmb_tagDemandsSelector.addItemListener(new ItemListener()
{
@Override
public void itemStateChanged(ItemEvent itemEvent)
{
updateNetPlanView();
}
});
cmb_tagDemandsSelector.addItemListener(new ItemListener()
{
@Override
public void itemStateChanged(ItemEvent itemEvent)
{
updateNetPlanView();
}
});
filterPanel.add(new JLabel("Consider only demands between nodes tagged by..."), "align label");
filterPanel.add(cmb_tagNodesSelector, "grow");
filterPanel.add(new JLabel("Consider only demands tagged by..."), "align label");
filterPanel.add(cmb_tagDemandsSelector, "grow");
final JPanel bottomPanel = new JPanel(new MigLayout("fill, wrap 1"));
bottomPanel.add(filterPanel, "grow");
bottomPanel.add(pnl_trafficModel, "grow");
bottomPanel.add(pnl_normalization, "grow");
this.add(bottomPanel, BorderLayout.SOUTH);
updateNetPlanView();
}
private Pair<List<Node>, Set<Demand>> computeFilteringNodesAndDemands()
{
final NetPlan np = networkViewer.getDesign();
final List<Node> filteredNodes = new ArrayList<>(np.getNumberOfNodes());
final String filteringNodeTag = this.cmb_tagNodesSelector.getSelectedIndex() == 0 ? null : (String) this.cmb_tagNodesSelector.getSelectedItem();
final String filteringDemandTag = this.cmb_tagDemandsSelector.getSelectedIndex() == 0 ? null : (String) this.cmb_tagDemandsSelector.getSelectedItem();
for (Node n : np.getNodes())
{
if (filteringNodeTag != null)
if (!n.hasTag(filteringNodeTag)) continue;
if (this.filterOutNodesNotConnectedThisLayer.isSelected())
if (!n.getOutgoingLinksAllLayers().stream().anyMatch(e -> e.getLayer().isDefaultLayer())
&& (!n.getIncomingLinksAllLayers().stream().anyMatch(e -> e.getLayer().isDefaultLayer())))
continue;
filteredNodes.add(n);
}
Set<Demand> filteredDemands;
if (filteringDemandTag == null) filteredDemands = new HashSet<>(np.getDemands());
else
{
filteredDemands = new HashSet<>();
for (Demand d : np.getDemands())
if (d.hasTag(filteringDemandTag)) filteredDemands.add(d);
}
return Pair.of(filteredNodes, filteredDemands);
}
public void updateNetPlanView()
{
final NetPlan np = networkViewer.getDesign();
final Pair<List<Node>, Set<Demand>> filtInfo = computeFilteringNodesAndDemands();
final List<Node> filteredNodes = filtInfo.getFirst();
final Set<Demand> filteredDemands = filtInfo.getSecond();
this.trafficMatrixTable.setModel(createTrafficMatrix(filteredNodes, filteredDemands));
cmb_tagNodesSelector.removeAllItems();
cmb_tagNodesSelector.addItem("[NO FILTER]");
final Set<String> allTagsNodes = np.getNodes().stream().map(n -> n.getTags()).flatMap(e -> e.stream()).collect(Collectors.toSet());
final List<String> allTagsNodesOrdered = allTagsNodes.stream().sorted().collect(Collectors.toList());
for (String tag : allTagsNodesOrdered) this.cmb_tagNodesSelector.addItem(tag);
cmb_tagDemandsSelector.removeAllItems();
cmb_tagDemandsSelector.addItem("[NO FILTER]");
final Set<String> allTagsDemands = np.getDemands().stream().map(n -> n.getTags()).flatMap(e -> e.stream()).collect(Collectors.toSet());
final List<String> allTagsDemandsOrdered = allTagsDemands.stream().sorted().collect(Collectors.toList());
for (String tag : allTagsDemandsOrdered) this.cmb_tagDemandsSelector.addItem(tag);
}
private DefaultTableModel createTrafficMatrix(List<Node> filteredNodes, Set<Demand> filteredDemands)
{
final NetPlan np = this.networkViewer.getDesign();
final int N = filteredNodes.size();
final NetworkLayer layer = np.getNetworkLayerDefault();
String[] columnHeaders = new String[N + 2];
Object[][] data = new Object[N + 1][N + 2];
final Map<Node, Integer> nodeToIndexInFilteredListMap = new HashMap<>();
for (int cont = 0; cont < filteredNodes.size(); cont++)
nodeToIndexInFilteredListMap.put(filteredNodes.get(cont), cont);
for (int inNodeListIndex = 0; inNodeListIndex < N; inNodeListIndex++)
{
final Node n = filteredNodes.get(inNodeListIndex);
String aux = n.getName().equals("") ? "Node " + n.getIndex() : n.getName();
columnHeaders[1 + inNodeListIndex] = aux;
Arrays.fill(data[inNodeListIndex], 0.0);
data[inNodeListIndex][0] = aux;
}
Arrays.fill(data[data.length - 1], 0.0);
final int totalsRowIndex = N;
final int totalsColumnIndex = N + 1;
double totalTraffic = 0;
for (Demand d : filteredDemands)
{
final int row = nodeToIndexInFilteredListMap.get(d.getIngressNode());
final int column = nodeToIndexInFilteredListMap.get(d.getEgressNode()) + 1;
totalTraffic += d.getOfferedTraffic();
data[row][column] = ((Double) data[row][column]) + d.getOfferedTraffic();
data[totalsRowIndex][column] = ((Double) data[totalsRowIndex][column]) + d.getOfferedTraffic();
data[row][totalsColumnIndex] = ((Double) data[row][totalsColumnIndex]) + d.getOfferedTraffic();
}
data[totalsRowIndex][totalsColumnIndex] = totalTraffic;
data[data.length - 1][0] = "";
columnHeaders[0] = "";
data[totalsRowIndex][0] = "Total";
columnHeaders[columnHeaders.length - 1] = "Total";
final DefaultTableModel model = new ClassAwareTableModel(data, columnHeaders)
{
private static final long serialVersionUID = 1L;
@Override
public boolean isCellEditable(int row, int column)
{
final int columnCount = getColumnCount();
final int rowCount = getRowCount();
if (column == 0 || column == columnCount - 1 || row == rowCount - 1 || row == column - 1) return false;
final Node n1 = filteredNodes.get(row);
final Node n2 = filteredNodes.get(column - 1);
final Set<Demand> applicableDemands = Sets.intersection(
np.getNodePairDemands(n1, n2, false, layer), filteredDemands);
if (applicableDemands.isEmpty()) return false;
if (applicableDemands.size() > 1) return false;
if (applicableDemands.iterator().next().isCoupled()) return false;
return true;
}
@Override
public void setValueAt(Object newValue, int row, int column)
{
Object oldValue = getValueAt(row, column);
try
{
if (Math.abs((double) newValue - (double) oldValue) < 1e-10) return;
final double newOfferedTraffic = (Double) newValue;
if (newOfferedTraffic < 0) throw new Net2PlanException("Wrong traffic value");
final Node n1 = filteredNodes.get(row);
final Node n2 = filteredNodes.get(column - 1);
final Set<Demand> applicableDemands = Sets.intersection(
np.getNodePairDemands(n1, n2, false, layer), filteredDemands);
final Demand demand = applicableDemands.iterator().next();
if (networkViewer.getVisualizationState().isWhatIfAnalysisActive())
{
final WhatIfAnalysisPane whatIfPane = networkViewer.getWhatIfAnalysisPane();
whatIfPane.whatIfDemandOfferedTrafficModified(demand, newOfferedTraffic);
super.setValueAt(newValue, row, column);
final VisualizationState vs = networkViewer.getVisualizationState();
Pair<BidiMap<NetworkLayer, Integer>, Map<NetworkLayer, Boolean>> res =
vs.suggestCanvasUpdatedVisualizationLayerInfoForNewDesign(new HashSet<>(networkViewer.getDesign().getNetworkLayers()));
vs.setCanvasLayerVisibilityAndOrder(networkViewer.getDesign(), res.getFirst(), res.getSecond());
networkViewer.updateVisualizationAfterNewTopology();
} else
{
demand.setOfferedTraffic(newOfferedTraffic);
super.setValueAt(newValue, row, column);
networkViewer.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.DEMAND));
networkViewer.getVisualizationState().pickElement(demand);
networkViewer.updateVisualizationAfterPick();
networkViewer.addNetPlanChange();
}
} catch (Throwable e)
{
ErrorHandling.showErrorDialog("Wrong traffic value");
return;
}
}
};
return model;
}
private static class TotalRowColumnRenderer extends CellRenderers.NumberCellRenderer
{
private final static Color BACKGROUND_COLOR = new Color(200, 200, 200);
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (row == table.getRowCount() - 1 || column == table.getColumnCount() - 1)
{
c.setBackground(BACKGROUND_COLOR);
if (isSelected) c.setForeground(Color.BLACK);
}
return c;
}
}
private class ApplyTrafficModels
{
private final List<Node> filteredNodes;
private final Set<Demand> filteredDemands;
ApplyTrafficModels(List<Node> filteredNodes, Set<Demand> filteredDemands)
{
this.filteredDemands = filteredDemands;
this.filteredNodes = filteredNodes;
}
DoubleMatrix2D applyOption(int selectedOptionIndex)
{
if (selectedOptionIndex == 0)
{
ErrorHandling.showWarningDialog("Please, select a traffic model", "Error applying traffic model");
return null;
}
final NetPlan np = networkViewer.getDesign();
final int N = filteredNodes.size();
switch (selectedOptionIndex)
{
case OPTIONINDEX_TRAFFICMODEL_CONSTANT:
final JTextField txt_constantValue = new JTextField(5);
final JPanel pane = new JPanel(new GridLayout(0, 2));
pane.add(new JLabel("Traffic per cell: "));
pane.add(txt_constantValue);
while (true)
{
int result = JOptionPane.showConfirmDialog(null, pane, "Please enter the traffic per cell", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result != JOptionPane.OK_OPTION) return null;
final double constantValue = Double.parseDouble(txt_constantValue.getText());
if (constantValue < 0)
throw new IllegalArgumentException("Constant value must be greater or equal than zero");
return TrafficMatrixGenerationModels.constantTrafficMatrix(N, constantValue);
}
case OPTIONINDEX_TRAFFICMODEL_RESET:
return DoubleFactory2D.sparse.make(N, N);
case OPTIONINDEX_TRAFFICMODEL_UNIFORM01:
return TrafficMatrixGenerationModels.uniformRandom(N, 0, 10);
case OPTIONINDEX_TRAFFICMODEL_UNIFORM5050:
return TrafficMatrixGenerationModels.bimodalUniformRandom(N, 0.5, 0, 100, 0, 10);
case OPTIONINDEX_TRAFFICMODEL_UNIFORM2575:
return TrafficMatrixGenerationModels.bimodalUniformRandom(N, 0.25, 0, 100, 0, 10);
case OPTIONINDEX_TRAFFICMODEL_GRAVITYMODEL:
DefaultTableModel gravityModelTableModel = new ClassAwareTableModel()
{
private static final long serialVersionUID = 1L;
@Override
public boolean isCellEditable(int row, int col)
{
return true;
}
@Override
public void setValueAt(Object newValue, int row, int column)
{
Object oldValue = getValueAt(row, column);
/* If value doesn't change, exit from function */
if (Math.abs((double) newValue - (double) oldValue) < 1e-10) return;
double trafficAmount = (Double) newValue;
if (trafficAmount < 0)
{
ErrorHandling.showErrorDialog("Traffic amount must be greater or equal than zero", "Error introducing traffic amount");
return;
}
super.setValueAt(newValue, row, column);
}
};
Object[][] gravityModelData = new Object[N][2];
for (int n = 0; n < N; n++)
{
gravityModelData[n][0] = 0.0;
gravityModelData[n][1] = 0.0;
}
String[] gravityModelHeader = new String[]{"Total ingress traffic per node", "Total egress traffic per node"};
gravityModelTableModel.setDataVector(gravityModelData, gravityModelHeader);
JTable gravityModelTable = new AdvancedJTable(gravityModelTableModel);
JPanel gravityModelPanel = new JPanel();
JScrollPane gPane = new JScrollPane(gravityModelTable);
gravityModelPanel.add(gPane);
double[] ingressTrafficPerNode = new double[N];
double[] egressTrafficPerNode = new double[N];
while (true)
{
int gravityModelResult = JOptionPane.showConfirmDialog(null, gravityModelPanel, "Please enter total ingress/egress traffic per node (one value per row)", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (gravityModelResult != JOptionPane.OK_OPTION) return null;
for (int n = 0; n < N; n++)
{
ingressTrafficPerNode[n] = (Double) gravityModelTableModel.getValueAt(n, 0);
egressTrafficPerNode[n] = (Double) gravityModelTableModel.getValueAt(n, 1);
}
try
{
return TrafficMatrixGenerationModels.gravityModel(ingressTrafficPerNode, egressTrafficPerNode);
} catch (Throwable ex)
{
ErrorHandling.showErrorDialog(ex.getMessage(), "Error applying gravity model");
}
}
default:
throw new RuntimeException("Bad");
}
}
}
;
private class ApplyTrafficNormalizationsAndAdjustments
{
private final List<Node> filteredNodes;
private final Set<Demand> filteredDemands;
ApplyTrafficNormalizationsAndAdjustments(List<Node> filteredNodes, Set<Demand> filteredDemands)
{
this.filteredDemands = filteredDemands;
this.filteredNodes = filteredNodes;
}
DoubleMatrix2D applyOption(int selectedOptionIndex)
{
if (selectedOptionIndex == 0)
{
ErrorHandling.showWarningDialog("Please, select a valid traffic normalization/adjustment method", "Error applying method");
return null;
}
final NetPlan np = networkViewer.getDesign();
final int N = filteredNodes.size();
switch (selectedOptionIndex)
{
case OPTIONINDEX_NORMALIZATION_SCALE:
{
final JTextField txt_scalingValue = new JTextField(10);
final JPanel pane = new JPanel(new GridLayout(0, 2));
pane.add(new JLabel("Multiply cells by factor: "));
pane.add(txt_scalingValue);
final int result = JOptionPane.showConfirmDialog(null, pane, "Please enter the traffic saling factor", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result != JOptionPane.OK_OPTION) return null;
final double constantValue = Double.parseDouble(txt_scalingValue.getText());
if (constantValue < 0)
throw new IllegalArgumentException("Scaling value must be greater or equal than zero");
final DoubleMatrix2D res = DoubleFactory2D.sparse.make(N, N);
for (int n1 = 0; n1 < N; n1++)
for (int n2 = 0; n2 < N; n2++)
if (n1 != n2)
res.set(n1, n2, ((Double) trafficMatrixTable.getValueAt(n1, n2 + 1)) * constantValue);
return res;
}
case OPTIONINDEX_NORMALIZATION_MAKESYMMETRIC:
{
final DoubleMatrix2D res = DoubleFactory2D.sparse.make(N, N);
for (int n1 = 0; n1 < N; n1++)
for (int n2 = 0; n2 < N; n2++)
if (n1 != n2)
res.set(n1, n2, ((Double) trafficMatrixTable.getValueAt(n1, n2 + 1) + (Double) trafficMatrixTable.getValueAt(n2, n1 + 1)) / 2.0);
return res;
}
case OPTIONINDEX_NORMALIZATION_TOTAL:
{
final JTextField txt_scalingValue = new JTextField(10);
final JPanel pane = new JPanel(new GridLayout(0, 2));
pane.add(new JLabel("Total sum of matrix cells should be: "));
pane.add(txt_scalingValue);
final int result = JOptionPane.showConfirmDialog(null, pane, "Please enter the total traffic", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result != JOptionPane.OK_OPTION) return null;
final double constantValue = Double.parseDouble(txt_scalingValue.getText());
if (constantValue < 0)
throw new IllegalArgumentException("Traffic value must be greater or equal than zero");
final DoubleMatrix2D res = DoubleFactory2D.sparse.make(N, N);
final double currentTotalTraffic = filteredDemands.stream().mapToDouble(d -> d.getOfferedTraffic()).sum();
for (int n1 = 0; n1 < N; n1++)
for (int n2 = 0; n2 < N; n2++)
if (n1 != n2)
res.set(n1, n2, ((Double) trafficMatrixTable.getValueAt(n1, n2 + 1)) * constantValue / currentTotalTraffic);
return res;
}
default:
throw new RuntimeException("Bad");
}
}
}
;
private class CommonActionPerformListenerModelAndNormalization implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
final Pair<List<Node>, Set<Demand>> filtInfo = computeFilteringNodesAndDemands();
final List<Node> filteredNodes = filtInfo.getFirst();
final Set<Demand> filteredDemands = filtInfo.getSecond();
if (filteredNodes.size() <= 1) throw new Net2PlanException("No demands are selected");
if (filteredDemands.isEmpty()) throw new Net2PlanException("No demands are selected");
boolean allCellsEditable = true;
for (int row = 0; row < trafficMatrixTable.getRowCount() - 1; row++)
for (int col = 1; col < trafficMatrixTable.getColumnCount() - 1; col++)
if (row != col - 1 && !trafficMatrixTable.isCellEditable(row, col))
{
allCellsEditable = false;
break;
}
if (!allCellsEditable)
throw new Net2PlanException("Traffic matrix modification is only possible when all the cells are editable");
DoubleMatrix2D newTraffic2D = null;
if (e.getSource() == applyTrafficModelButton)
newTraffic2D = new ApplyTrafficModels(filteredNodes, filteredDemands).applyOption(cmb_trafficModelPattern.getSelectedIndex());
else if (e.getSource() == applyTrafficNormalizationButton)
newTraffic2D = new ApplyTrafficNormalizationsAndAdjustments(filteredNodes, filteredDemands).applyOption(cmb_trafficNormalization.getSelectedIndex());
else throw new RuntimeException();
if (newTraffic2D == null) return;
final Map<Node, Integer> node2IndexInFilteredListMap = new HashMap<>();
for (int cont = 0; cont < filteredNodes.size(); cont++)
node2IndexInFilteredListMap.put(filteredNodes.get(cont), cont);
final List<Demand> filteredDemandList = new ArrayList<>(filteredDemands);
final List<Double> demandOfferedTrafficsList = new ArrayList<>(filteredDemands.size());
for (Demand d : filteredDemandList)
demandOfferedTrafficsList.add(newTraffic2D.get(node2IndexInFilteredListMap.get(d.getIngressNode()), node2IndexInFilteredListMap.get(d.getEgressNode())));
if (networkViewer.getVisualizationState().isWhatIfAnalysisActive())
{
final WhatIfAnalysisPane whatIfPane = networkViewer.getWhatIfAnalysisPane();
whatIfPane.whatIfDemandOfferedTrafficModified(filteredDemandList, demandOfferedTrafficsList);
final VisualizationState vs = networkViewer.getVisualizationState();
Pair<BidiMap<NetworkLayer, Integer>, Map<NetworkLayer, Boolean>> res =
vs.suggestCanvasUpdatedVisualizationLayerInfoForNewDesign(new HashSet<>(networkViewer.getDesign().getNetworkLayers()));
vs.setCanvasLayerVisibilityAndOrder(networkViewer.getDesign(), res.getFirst(), res.getSecond());
networkViewer.updateVisualizationAfterNewTopology();
} else
{
for (int cont = 0; cont < filteredDemandList.size(); cont++)
filteredDemandList.get(cont).setOfferedTraffic(demandOfferedTrafficsList.get(cont));
networkViewer.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.DEMAND));
networkViewer.addNetPlanChange();
}
} catch (Net2PlanException ee)
{
ErrorHandling.showErrorDialog(ee.getMessage(), "Error");
} catch (Throwable eee)
{
throw new Net2PlanException("Impossible to complete this action");
}
}
}
} |
package seedu.taskell.logic;
import com.google.common.eventbus.Subscribe;
import seedu.taskell.commons.core.EventsCenter;
import seedu.taskell.commons.events.model.TaskManagerChangedEvent;
import seedu.taskell.commons.events.ui.JumpToListRequestEvent;
import seedu.taskell.commons.events.ui.ShowHelpRequestEvent;
import seedu.taskell.logic.Logic;
import seedu.taskell.logic.LogicManager;
import seedu.taskell.logic.commands.*;
import seedu.taskell.model.TaskManager;
import seedu.taskell.model.Model;
import seedu.taskell.model.ModelManager;
import seedu.taskell.model.ReadOnlyTaskManager;
import seedu.taskell.model.tag.Tag;
import seedu.taskell.model.tag.UniqueTagList;
import seedu.taskell.model.task.*;
import seedu.taskell.storage.StorageManager;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static seedu.taskell.commons.core.Messages.*;
public class LogicManagerTest {
@Rule
public TemporaryFolder saveFolder = new TemporaryFolder();
private Model model;
private Logic logic;
//These are for checking the correctness of the events raised
private ReadOnlyTaskManager latestSavedTaskManager;
private boolean helpShown;
private int targetedJumpIndex;
@Subscribe
private void handleLocalModelChangedEvent(TaskManagerChangedEvent abce) {
latestSavedTaskManager = new TaskManager(abce.data);
}
@Subscribe
private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) {
helpShown = true;
}
@Subscribe
private void handleJumpToListRequestEvent(JumpToListRequestEvent je) {
targetedJumpIndex = je.targetIndex;
}
@Before
public void setup() {
model = new ModelManager();
String tempTaskManagerFile = saveFolder.getRoot().getPath() + "TempTaskManager.xml";
String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json";
logic = new LogicManager(model, new StorageManager(tempTaskManagerFile, tempPreferencesFile));
EventsCenter.getInstance().registerHandler(this);
latestSavedTaskManager = new TaskManager(model.getTaskManager()); // last saved assumed to be up to date before.
helpShown = false;
targetedJumpIndex = -1; // non yet
}
@After
public void teardown() {
EventsCenter.clearSubscribers();
}
@Test
public void execute_invalid() throws Exception {
String invalidCommand = " ";
assertCommandBehavior(invalidCommand,
String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
/**
* Executes the command and confirms that the result message is correct.
* Both the 'task manager' and the 'last shown list' are expected to be empty.
* @see #assertCommandBehavior(String, String, ReadOnlyTaskManager, List)
*/
private void assertCommandBehavior(String inputCommand, String expectedMessage) throws Exception {
assertCommandBehavior(inputCommand, expectedMessage, new TaskManager(), Collections.emptyList());
}
/**
* Executes the command and confirms that the result message is correct and
* also confirms that the following three parts of the LogicManager object's state are as expected:<br>
* - the internal task manager data are same as those in the {@code expectedTaskManager} <br>
* - the backing list shown by UI matches the {@code shownList} <br>
* - {@code expectedTaskManager} was saved to the storage file. <br>
*/
private void assertCommandBehavior(String inputCommand, String expectedMessage,
ReadOnlyTaskManager expectedTaskManager,
List<? extends ReadOnlyTask> expectedShownList) throws Exception {
//Execute the command
CommandResult result = logic.execute(inputCommand);
//Confirm the ui display elements should contain the right data
assertEquals(expectedMessage, result.feedbackToUser);
assertEquals(expectedShownList, model.getFilteredTaskList());
//Confirm the state of data (saved and in-memory) is as expected
assertEquals(expectedTaskManager, model.getTaskManager());
assertEquals(expectedTaskManager, latestSavedTaskManager);
}
@Test
public void execute_unknownCommandWord() throws Exception {
String unknownCommand = "uicfhmowqewca";
assertCommandBehavior(unknownCommand, MESSAGE_UNKNOWN_COMMAND);
}
@Test
public void execute_help() throws Exception {
assertCommandBehavior("help", HelpCommand.SHOWING_HELP_MESSAGE);
assertTrue(helpShown);
}
@Test
public void execute_exit() throws Exception {
assertCommandBehavior("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT);
}
@Test
public void execute_clear() throws Exception {
TestDataHelper helper = new TestDataHelper();
model.addTask(helper.generateTask(1));
model.addTask(helper.generateTask(2));
model.addTask(helper.generateTask(3));
assertCommandBehavior("clear", ClearCommand.MESSAGE_SUCCESS, new TaskManager(), Collections.emptyList());
}
@Test
public void execute_add_invalidArgsFormat() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE);
assertCommandBehavior(
"add wrong args wrong args", expectedMessage);
assertCommandBehavior(
"add Valid Description 12345 e/valid@taskTime.butNoPhonePrefix a/valid, taskPriority", expectedMessage);
assertCommandBehavior(
"add Valid Description p/12345 valid@taskTime.butNoPrefix a/valid, taskPriority", expectedMessage);
assertCommandBehavior(
"add Valid Description p/12345 e/valid@taskTime.butNoTaskPriorityPrefix valid, taskPriority", expectedMessage);
}
@Test
public void execute_add_invalidTaskData() throws Exception {
assertCommandBehavior(
"add []\\[;] p/12345 e/valid@taskTime a/valid, taskPriority", Description.MESSAGE_DESCRIPTION_CONSTRAINTS);
assertCommandBehavior(
"add Valid Description p/not_numbers e/valid@taskTime a/valid, taskPriority", TaskDate.MESSAGE_TASK_DATE_CONSTRAINTS);
assertCommandBehavior(
"add Valid Description p/12345 e/notATaskTime a/valid, taskPriority", TaskTime.MESSAGE_TASK_TIME_CONSTRAINTS);
assertCommandBehavior(
"add Valid Description p/12345 e/valid@taskTime a/valid, taskPriority t/invalid_-[.tag", Tag.MESSAGE_TAG_CONSTRAINTS);
}
@Test
public void execute_add_successful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.adam();
TaskManager expectedAB = new TaskManager();
expectedAB.addTask(toBeAdded);
// execute command and verify result
assertCommandBehavior(helper.generateAddCommand(toBeAdded),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded),
expectedAB,
expectedAB.getTaskList());
}
@Test
public void execute_addDuplicate_notAllowed() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.adam();
TaskManager expectedAB = new TaskManager();
expectedAB.addTask(toBeAdded);
// setup starting state
model.addTask(toBeAdded); // task already in internal task manager
// execute command and verify result
assertCommandBehavior(
helper.generateAddCommand(toBeAdded),
AddCommand.MESSAGE_DUPLICATE_TASK,
expectedAB,
expectedAB.getTaskList());
}
@Test
public void execute_list_showsAllTasks() throws Exception {
// prepare expectations
TestDataHelper helper = new TestDataHelper();
TaskManager expectedAB = helper.generateTaskManager(2);
List<? extends ReadOnlyTask> expectedList = expectedAB.getTaskList();
// prepare task manager state
helper.addToModel(model, 2);
assertCommandBehavior("list",
ListCommand.MESSAGE_SUCCESS,
expectedAB,
expectedList);
}
/**
* Confirms the 'invalid argument index number behaviour' for the given command
* targeting a single task in the shown list, using visible index.
* @param commandWord to test assuming it targets a single task in the last shown list based on visible index.
*/
private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception {
assertCommandBehavior(commandWord , expectedMessage); //index missing
assertCommandBehavior(commandWord + " +1", expectedMessage); //index should be unsigned
assertCommandBehavior(commandWord + " -1", expectedMessage); //index should be unsigned
assertCommandBehavior(commandWord + " 0", expectedMessage); //index cannot be 0
assertCommandBehavior(commandWord + " not_a_number", expectedMessage);
}
/**
* Confirms the 'invalid argument index number behaviour' for the given command
* targeting a single task in the shown list, using visible index.
* @param commandWord to test assuming it targets a single task in the last shown list based on visible index.
*/
private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception {
String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX;
TestDataHelper helper = new TestDataHelper();
List<Task> taskList = helper.generateTaskList(2);
// set AB state to 2 tasks
model.resetData(new TaskManager());
for (Task p : taskList) {
model.addTask(p);
}
assertCommandBehavior(commandWord + " 3", expectedMessage, model.getTaskManager(), taskList);
}
@Test
public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage);
}
@Test
public void execute_selectIndexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("select");
}
@Test
public void execute_select_jumpsToCorrectTask() throws Exception {
TestDataHelper helper = new TestDataHelper();
List<Task> threeTasks = helper.generateTaskList(3);
TaskManager expectedAB = helper.generateTaskManager(threeTasks);
helper.addToModel(model, threeTasks);
assertCommandBehavior("select 2",
String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2),
expectedAB,
expectedAB.getTaskList());
assertEquals(1, targetedJumpIndex);
assertEquals(model.getFilteredTaskList().get(1), threeTasks.get(1));
}
@Test
public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage);
}
@Test
public void execute_deleteIndexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("delete");
}
@Test
public void execute_delete_removesCorrectTask() throws Exception {
TestDataHelper helper = new TestDataHelper();
List<Task> threeTasks = helper.generateTaskList(3);
TaskManager expectedAB = helper.generateTaskManager(threeTasks);
expectedAB.removeTask(threeTasks.get(1));
helper.addToModel(model, threeTasks);
assertCommandBehavior("delete 2",
String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, threeTasks.get(1)),
expectedAB,
expectedAB.getTaskList());
}
@Test
public void execute_find_invalidArgsFormat() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE);
assertCommandBehavior("find ", expectedMessage);
}
@Test
public void execute_find_onlyMatchesFullWordsInNames() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla");
Task pTarget2 = helper.generateTaskWithName("bla KEY bla bceofeia");
Task p1 = helper.generateTaskWithName("KE Y");
Task p2 = helper.generateTaskWithName("KEYKEYKEY sduauo");
List<Task> fourTasks = helper.generateTaskList(p1, pTarget1, p2, pTarget2);
TaskManager expectedAB = helper.generateTaskManager(fourTasks);
List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2);
helper.addToModel(model, fourTasks);
assertCommandBehavior("find KEY",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedAB,
expectedList);
}
@Test
public void execute_find_isNotCaseSensitive() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task p1 = helper.generateTaskWithName("bla bla KEY bla");
Task p2 = helper.generateTaskWithName("bla KEY bla bceofeia");
Task p3 = helper.generateTaskWithName("key key");
Task p4 = helper.generateTaskWithName("KEy sduauo");
List<Task> fourTasks = helper.generateTaskList(p3, p1, p4, p2);
TaskManager expectedAB = helper.generateTaskManager(fourTasks);
List<Task> expectedList = fourTasks;
helper.addToModel(model, fourTasks);
assertCommandBehavior("find KEY",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedAB,
expectedList);
}
@Test
public void execute_find_matchesIfAllKeywordsPresent() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task pTarget = helper.generateTaskWithName("bla KEY rAnDoM bla bceofeia");
Task p1 = helper.generateTaskWithName("sduauo");
Task p2 = helper.generateTaskWithName("bla bla KEY bla");
Task p3 = helper.generateTaskWithName("key key");
List<Task> oneTask = helper.generateTaskList(pTarget);
TaskManager expectedAB = helper.generateTaskManager(oneTask);
List<Task> expectedList = helper.generateTaskList(pTarget);
helper.addToModel(model, oneTask);
assertCommandBehavior("find key rAnDoM",
Command.getMessageForTaskListShownSummary(expectedList.size()),
expectedAB,
expectedList);
}
/**
* A utility class to generate test data.
*/
class TestDataHelper{
Task adam() throws Exception {
Description description = new Description("Adam Brown");
TaskDate privatePhone = new TaskDate("111111");
TaskTime taskTime = new TaskTime("adam@gmail.com");
TaskPriority privatetaskPriority = new TaskPriority("111, alpha street");
Tag tag1 = new Tag("tag1");
Tag tag2 = new Tag("tag2");
UniqueTagList tags = new UniqueTagList(tag1, tag2);
return new Task(description, privatePhone, taskTime, privatetaskPriority, tags);
}
/**
* Generates a valid task using the given seed.
* Running this function with the same parameter values guarantees the returned task will have the same state.
* Each unique seed will generate a unique Task object.
*
* @param seed used to generate the task data field values
*/
Task generateTask(int seed) throws Exception {
return new Task(
new Description("Task " + seed),
new TaskDate("" + Math.abs(seed)),
new TaskTime(seed + "@taskTime"),
new TaskPriority("House of " + seed),
new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1)))
);
}
/** Generates the correct add command based on the task given */
String generateAddCommand(Task p) {
StringBuffer cmd = new StringBuffer();
cmd.append("add ");
cmd.append(p.getDescription().toString());
cmd.append(" p/").append(p.getTaskDate());
cmd.append(" e/").append(p.getTaskTime());
cmd.append(" a/").append(p.getTaskPriority());
UniqueTagList tags = p.getTags();
for(Tag t: tags){
cmd.append(" t/").append(t.tagName);
}
return cmd.toString();
}
/**
* Generates an TaskManager with auto-generated tasks.
*/
TaskManager generateTaskManager(int numGenerated) throws Exception{
TaskManager taskManager = new TaskManager();
addToTaskManager(taskManager, numGenerated);
return taskManager;
}
/**
* Generates an TaskManager based on the list of Tasks given.
*/
TaskManager generateTaskManager(List<Task> tasks) throws Exception{
TaskManager taskManager = new TaskManager();
addToTaskManager(taskManager, tasks);
return taskManager;
}
/**
* Adds auto-generated Task objects to the given TaskManager
* @param taskManager The TaskManager to which the Tasks will be added
*/
void addToTaskManager(TaskManager taskManager, int numGenerated) throws Exception{
addToTaskManager(taskManager, generateTaskList(numGenerated));
}
/**
* Adds the given list of Tasks to the given TaskManager
*/
void addToTaskManager(TaskManager taskManager, List<Task> tasksToAdd) throws Exception{
for(Task p: tasksToAdd){
taskManager.addTask(p);
}
}
/**
* Adds auto-generated Task objects to the given model
* @param model The model to which the Tasks will be added
*/
void addToModel(Model model, int numGenerated) throws Exception{
addToModel(model, generateTaskList(numGenerated));
}
/**
* Adds the given list of Tasks to the given model
*/
void addToModel(Model model, List<Task> tasksToAdd) throws Exception{
for(Task p: tasksToAdd){
model.addTask(p);
}
}
/**
* Generates a list of Tasks based on the flags.
*/
List<Task> generateTaskList(int numGenerated) throws Exception{
List<Task> tasks = new ArrayList<>();
for(int i = 1; i <= numGenerated; i++){
tasks.add(generateTask(i));
}
return tasks;
}
List<Task> generateTaskList(Task... tasks) {
return Arrays.asList(tasks);
}
/**
* Generates a Task object with given description. Other fields will have some dummy values.
*/
Task generateTaskWithName(String description) throws Exception {
return new Task(
new Description(description),
new TaskDate("1"),
new TaskTime("1@taskTime"),
new TaskPriority("House of 1"),
new UniqueTagList(new Tag("tag"))
);
}
}
} |
package net.gigimoi.zombietc.block;
import net.gigimoi.zombietc.ZombieTC;
import net.gigimoi.zombietc.entity.EntityZZombie;
import net.gigimoi.zombietc.event.GameManager;
import net.gigimoi.zombietc.net.map.MessageAddBarricade;
import net.gigimoi.zombietc.net.map.MessageRemoveBarricade;
import net.gigimoi.zombietc.tile.TileBarricade;
import net.gigimoi.zombietc.util.Point3;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import java.util.List;
public class BlockBarricade extends BlockContainerZTC {
public static BlockBarricade wooden = new BlockBarricade("Wooden");
public BlockBarricade(String prefix) {
super(Material.rock);
setBlockName(prefix + " Barricade");
setHardness(1.0f);
}
@Override
public TileEntity createNewTileEntity(World world, int meta) {
return new TileBarricade();
}
@Override
public int getLightOpacity() {
return 0;
}
@Override
public boolean isBlockSolid(IBlockAccess access, int x, int y, int z, int meta) {
return false;
}
@Override
public void addCollisionBoxesToList(World world, int x, int y, int z, AxisAlignedBB aabb, List mask, Entity entity) {
if (entity != null) {
if (entity.getClass() == EntityZZombie.class) {
if (((TileBarricade) world.getTileEntity(x, y, z)).damage == 5) {
return;
}
super.addCollisionBoxesToList(world, x, y, z, aabb, mask, entity);
} else {
if (!ZombieTC.editorModeManager.enabled) {
super.addCollisionBoxesToList(world, x, y, z, aabb, mask, entity);
}
}
} else {
super.addCollisionBoxesToList(world, x, y, z, aabb, mask, entity);
}
}
@Override
public boolean isOpaqueCube() {
return false;
}
@Override
public void setBlockBoundsBasedOnState(IBlockAccess access, int x, int y, int z) {
super.setBlockBoundsBasedOnState(access, x, y, z);
}
@Override
public boolean renderAsNormalBlock() {
return false;
}
@Override
public boolean getBlocksMovement(IBlockAccess access, int x, int y, int z) {
return false;
}
@Override
public void onBlockAdded(World world, int x, int y, int z) {
super.onBlockAdded(world, x, y, z);
GameManager.blockBarricades.add(new Point3(x, y, z));
ZombieTC.network.sendToAll(new MessageAddBarricade(x, y, z));
}
@Override
public void breakBlock(World world, int x, int y, int z, Block block, int side) {
super.breakBlock(world, x, y, z, block, side);
for (int i = 0; i < GameManager.blockBarricades.size(); i++) {
Point3 vec = GameManager.blockBarricades.get(i);
if (vec.distanceTo(new Point3(x, y, z)) < 0.01) {
GameManager.blockBarricades.remove(i);
}
}
ZombieTC.network.sendToAll(new MessageRemoveBarricade(x, y, z));
}
} |
package com.namelessdev.mpdroid.fragments;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.a0z.mpd.MPDPlaylist;
import org.a0z.mpd.MPDStatus;
import org.a0z.mpd.Music;
import org.a0z.mpd.event.StatusChangeListener;
import org.a0z.mpd.exception.MPDServerException;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ListFragment;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.SimpleAdapter;
import com.mobeta.android.dslv.DragSortController;
import com.mobeta.android.dslv.DragSortListView;
import com.namelessdev.mpdroid.MPDApplication;
import com.namelessdev.mpdroid.MainMenuActivity;
import com.namelessdev.mpdroid.R;
import com.namelessdev.mpdroid.helpers.AlbumCoverDownloadListener;
import com.namelessdev.mpdroid.helpers.CoverAsyncHelper;
import com.namelessdev.mpdroid.helpers.CoverAsyncHelper.CoverRetrievers;
import com.namelessdev.mpdroid.library.PlaylistEditActivity;
import com.namelessdev.mpdroid.tools.Tools;
public class PlaylistFragment extends ListFragment implements StatusChangeListener, OnMenuItemClickListener {
private ArrayList<HashMap<String, Object>> songlist;
private List<Music> musics;
private MPDApplication app;
private DragSortListView list;
private ActionMode actionMode;
private SearchView searchView;
private String filter = null;
private PopupMenu popupMenu;
private Integer popupSongID;
private DragSortController controller;
private int lastPlayingID = -1;
public static final int MAIN = 0;
public static final int CLEAR = 1;
public static final int MANAGER = 3;
public static final int SAVE = 4;
public static final int EDIT = 2;
public PlaylistFragment() {
super();
setHasOptionsMenu(true);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
app = (MPDApplication) getActivity().getApplication();
refreshListColorCacheHint();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.playlist_activity, container, false);
searchView = (SearchView) view.findViewById(R.id.search);
searchView.setOnQueryTextListener(new OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
// Hide the keyboard and give focus to the list
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
list.requestFocus();
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
filter = newText;
if ("".equals(newText))
filter = null;
if (filter != null)
filter = filter.toLowerCase();
list.setDragEnabled(filter == null);
update(false);
return false;
}
});
list = (DragSortListView) view.findViewById(android.R.id.list);
list.requestFocus();
list.setDropListener(onDrop);
controller = new DragSortController(list);
controller.setDragHandleId(R.id.icon);
controller.setRemoveEnabled(false);
controller.setSortEnabled(true);
controller.setDragInitMode(1);
list.setFloatViewManager(controller);
list.setOnTouchListener(controller);
list.setDragEnabled(true);
refreshListColorCacheHint();
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
list.setMultiChoiceModeListener(new MultiChoiceModeListener() {
@Override
public boolean onPrepareActionMode(ActionMode mode, android.view.Menu menu) {
actionMode = mode;
controller.setSortEnabled(false);
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
actionMode = null;
controller.setSortEnabled(true);
}
@Override
public boolean onCreateActionMode(ActionMode mode, android.view.Menu menu) {
final android.view.MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.mpd_queuemenu, menu);
return true;
}
@SuppressWarnings("unchecked")
@Override
public boolean onActionItemClicked(ActionMode mode, android.view.MenuItem item) {
final SparseBooleanArray checkedItems = list.getCheckedItemPositions();
final int count = list.getCount();
final ListAdapter adapter = list.getAdapter();
int j = 0;
final int positions[];
switch (item.getItemId()) {
case R.id.menu_delete:
positions = new int[list.getCheckedItemCount()];
for (int i = 0; i < count && j < positions.length; i++) {
if (checkedItems.get(i)) {
positions[j] = ((Integer) ((HashMap<String, Object>) adapter.getItem(i)).get("songid")).intValue();
j++;
}
}
app.oMPDAsyncHelper.execAsync(new Runnable() {
@Override
public void run() {
try {
app.oMPDAsyncHelper.oMPD.getPlaylist().removeById(positions);
} catch (MPDServerException e) {
e.printStackTrace();
}
}
});
mode.finish();
return true;
case R.id.menu_crop:
positions = new int[list.getCount() - list.getCheckedItemCount()];
for (int i = 0; i < count && j < positions.length; i++) {
if (!checkedItems.get(i)) {
positions[j] = ((Integer) ((HashMap<String, Object>) adapter.getItem(i)).get("songid")).intValue();
j++;
}
}
app.oMPDAsyncHelper.execAsync(new Runnable() {
@Override
public void run() {
try {
app.oMPDAsyncHelper.oMPD.getPlaylist().removeById(positions);
} catch (MPDServerException e) {
e.printStackTrace();
}
}
});
mode.finish();
return true;
default:
return false;
}
}
@Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
final int selectCount = list.getCheckedItemCount();
if (selectCount == 0)
mode.finish();
if (selectCount == 1) {
mode.setTitle(R.string.actionSongSelected);
} else {
mode.setTitle(getString(R.string.actionSongsSelected, selectCount));
}
}
});
return view;
}
private void refreshListColorCacheHint() {
if (app == null || list == null)
return;
if ((getActivity() instanceof MainMenuActivity && app.isLightNowPlayingThemeSelected()) ||
(!(getActivity() instanceof MainMenuActivity) && app.isLightThemeSelected())) {
list.setCacheColorHint(getResources().getColor(android.R.color.background_light));
} else {
list.setCacheColorHint(getResources().getColor(R.color.nowplaying_background));
}
}
protected void update() {
update(true);
}
protected void update(boolean forcePlayingIDRefresh) {
try {
MPDPlaylist playlist = app.oMPDAsyncHelper.oMPD.getPlaylist();
songlist = new ArrayList<HashMap<String, Object>>();
musics = playlist.getMusicList();
if (lastPlayingID == -1 || forcePlayingIDRefresh)
lastPlayingID = app.oMPDAsyncHelper.oMPD.getStatus().getSongId();
// The position in the songlist of the currently played song
int listPlayingID = -1;
String tmpArtist = null;
String tmpAlbum = null;
String tmpAlbumArtist = null;
String tmpTitle = null;
for (Music m : musics) {
if (m == null) {
continue;
}
tmpArtist = m.getArtist();
tmpAlbum = m.getAlbum();
tmpAlbumArtist = m.getAlbumArtist();
tmpTitle = m.getTitle();
if (filter != null) {
if (tmpArtist == null)
tmpArtist = "";
if (tmpAlbum == null)
tmpAlbum = "";
if (tmpAlbumArtist == null)
tmpAlbumArtist = "";
if (tmpTitle == null)
tmpTitle = "";
if (!tmpArtist.toLowerCase(Locale.getDefault()).contains(filter) &&
!tmpAlbum.toLowerCase(Locale.getDefault()).contains(filter) &&
!tmpAlbumArtist.toLowerCase(Locale.getDefault()).contains(filter) &&
!tmpTitle.toLowerCase(Locale.getDefault()).contains(filter)) {
continue;
}
}
HashMap<String, Object> item = new HashMap<String, Object>();
item.put("songid", m.getSongId());
item.put("_artist", tmpArtist);
item.put("_album", tmpAlbum);
if (m.isStream()) {
if (m.haveTitle()) {
item.put("title", tmpTitle);
if (Tools.isStringEmptyOrNull(m.getName())) {
item.put("artist", tmpArtist);
} else if (Tools.isStringEmptyOrNull(tmpArtist)) {
item.put("artist", m.getName());
} else {
item.put("artist", tmpArtist + " - " + m.getName());
}
} else {
item.put("title", m.getName());
}
} else {
if (Tools.isStringEmptyOrNull(tmpAlbum)) {
item.put("artist", tmpArtist);
} else {
item.put("artist", tmpArtist + " - " + tmpAlbum);
}
item.put("title", tmpTitle);
}
if (m.getSongId() == lastPlayingID) {
item.put("play", android.R.drawable.ic_media_play);
// Lie a little. Scroll to the previous song than the one playing. That way it shows that there are other songs before
listPlayingID = songlist.size() - 1;
} else {
item.put("play", 0);
}
songlist.add(item);
}
final int finalListPlayingID = listPlayingID;
getActivity().runOnUiThread(new Runnable() {
public void run() {
SimpleAdapter songs = new QueueAdapter(getActivity(), songlist, R.layout.playlist_queue_item, new String[]{
"play",
"title", "artist"}, new int[]{R.id.picture, android.R.id.text1, android.R.id.text2});
setListAdapter(songs);
if (actionMode != null)
actionMode.finish();
// Only scroll if there is a valid song to scroll to. 0 is a valid song but does not require scroll anyway.
// Also, only scroll if it's the first update. You don't want your playlist to scroll itself while you are looking at
// other
// stuff.
if (finalListPlayingID > 0)
setSelection(finalListPlayingID);
}
});
} catch (MPDServerException e) {
}
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onResume() {
super.onResume();
app.oMPDAsyncHelper.addStatusChangeListener(this);
new Thread(new Runnable() {
public void run() {
update();
}
}).start();
}
@Override
public void onPause() {
app.oMPDAsyncHelper.removeStatusChangeListener(this);
super.onPause();
}
/*
* Create Menu for Playlist View
*
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
*/
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.mpd_playlistmenu, menu);
menu.removeItem(R.id.PLM_EditPL);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Menu actions...
Intent i;
switch (item.getItemId()) {
case R.id.PLM_Clear:
try {
app.oMPDAsyncHelper.oMPD.getPlaylist().clear();
songlist.clear();
Tools.notifyUser(getResources().getString(R.string.playlistCleared), getActivity());
((SimpleAdapter) getListAdapter()).notifyDataSetChanged();
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
case R.id.PLM_EditPL:
i = new Intent(getActivity(), PlaylistEditActivity.class);
startActivity(i);
return true;
case R.id.PLM_Save:
final EditText input = new EditText(getActivity());
new AlertDialog.Builder(getActivity())
.setTitle(R.string.playlistName)
.setMessage(R.string.newPlaylistPrompt)
.setView(input)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final String name = input.getText().toString().trim();
if (null != name && name.length() > 0) {
app.oMPDAsyncHelper.execAsync(new Runnable() {
@Override
public void run() {
try {
app.oMPDAsyncHelper.oMPD.getPlaylist().savePlaylist(name);
} catch (MPDServerException e) {
e.printStackTrace();
}
}
});
}
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).show();
return true;
default:
return false;
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
MPDApplication app = (MPDApplication) getActivity().getApplication(); // Play selected Song
@SuppressWarnings("unchecked")
final Integer song = (Integer) ((HashMap<String, Object>) l.getAdapter().getItem(position)).get("songid");
try {
app.oMPDAsyncHelper.oMPD.skipToId(song);
} catch (MPDServerException e) {
}
}
public void scrollToNowPlaying() {
for (HashMap<String, Object> song : songlist) {
try {
if (((Integer) song.get("songid")).intValue() == ((MPDApplication) getActivity().getApplication()).oMPDAsyncHelper.oMPD
.getStatus()
.getSongId()) {
getListView().requestFocusFromTouch();
getListView().setSelection(songlist.indexOf(song));
}
} catch (MPDServerException e) {
}
}
}
@Override
public void volumeChanged(MPDStatus mpdStatus, int oldVolume) {
// TODO Auto-generated method stub
}
@Override
public void playlistChanged(MPDStatus mpdStatus, int oldPlaylistVersion) {
update();
}
@Override
public void trackChanged(MPDStatus mpdStatus, int oldTrack) {
// Mark running track...
for (HashMap<String, Object> song : songlist) {
if (((Integer) song.get("songid")).intValue() == mpdStatus.getSongId())
song.put("play", android.R.drawable.ic_media_play);
else
song.put("play", 0);
}
final SimpleAdapter adapter = (SimpleAdapter) getListAdapter();
if (adapter != null)
adapter.notifyDataSetChanged();
}
@Override
public void stateChanged(MPDStatus mpdStatus, String oldState) {
// TODO Auto-generated method stub
}
@Override
public void repeatChanged(boolean repeating) {
// TODO Auto-generated method stub
}
@Override
public void randomChanged(boolean random) {
// TODO Auto-generated method stub
}
@Override
public void connectionStateChanged(boolean connected, boolean connectionLost) {
// TODO Auto-generated method stub
}
@Override
public void libraryStateChanged(boolean updating) {
// TODO Auto-generated method stub
}
private DragSortListView.DropListener onDrop = new DragSortListView.DropListener() {
public void drop(int from, int to) {
if (from == to || filter != null) {
return;
}
HashMap<String, Object> itemFrom = songlist.get(from);
Integer songID = (Integer) itemFrom.get("songid");
try {
app.oMPDAsyncHelper.oMPD.getPlaylist().move(songID, to);
} catch (MPDServerException e) {
}
}
};
private OnClickListener itemMenuButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
popupSongID = (Integer) v.getTag();
popupMenu = new PopupMenu(getActivity(), v);
popupMenu.getMenuInflater().inflate(R.menu.mpd_playlistcnxmenu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(PlaylistFragment.this);
popupMenu.show();
}
};
@Override
public boolean onMenuItemClick(android.view.MenuItem item) {
switch (item.getItemId()) {
case R.id.PLCX_SkipToHere:
// skip to selected Song
try {
app.oMPDAsyncHelper.oMPD.skipToId(popupSongID);
} catch (MPDServerException e) {
}
return true;
case R.id.PLCX_playNext:
try { // Move song to next in playlist
MPDStatus status = app.oMPDAsyncHelper.oMPD.getStatus();
if (popupSongID < status.getSongPos()) {
app.oMPDAsyncHelper.oMPD.getPlaylist().move(popupSongID, status.getSongPos());
} else {
app.oMPDAsyncHelper.oMPD.getPlaylist().move(popupSongID, status.getSongPos() + 1);
}
Tools.notifyUser("Song moved to next in list", getActivity());
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
case R.id.PLCX_moveFirst:
try { // Move song to first in playlist
app.oMPDAsyncHelper.oMPD.getPlaylist().move(popupSongID, 0);
Tools.notifyUser("Song moved to first in list", getActivity());
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
case R.id.PLCX_moveLast:
try { // Move song to last in playlist
MPDStatus status = app.oMPDAsyncHelper.oMPD.getStatus();
app.oMPDAsyncHelper.oMPD.getPlaylist().move(popupSongID, status.getPlaylistLength() - 1);
Tools.notifyUser("Song moved to last in list", getActivity());
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
case R.id.PLCX_removeFromPlaylist:
try {
app.oMPDAsyncHelper.oMPD.getPlaylist().removeById(popupSongID);
Tools.notifyUser(getResources().getString(R.string.deletedSongFromPlaylist), getActivity());
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
default:
return true;
}
}
private class QueueAdapter extends SimpleAdapter {
private List<CoverRetrievers> enabledRetrievers;
private MPDApplication app;
private SharedPreferences settings;
private boolean lightTheme;
public QueueAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
enabledRetrievers = null;
app = (MPDApplication) getActivity().getApplication();
settings = PreferenceManager.getDefaultSharedPreferences(app);
lightTheme = app.isLightNowPlayingThemeSelected();
if (settings.getBoolean(CoverAsyncHelper.PREFERENCE_CACHE, true)) {
enabledRetrievers = new ArrayList<CoverAsyncHelper.CoverRetrievers>();
enabledRetrievers.add(CoverRetrievers.CACHE);
}
}
@SuppressWarnings("unchecked")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final View view = super.getView(position, convertView, parent);
view.findViewById(R.id.icon).setVisibility(filter == null ? View.VISIBLE : View.GONE);
final View menuButton = view.findViewById(R.id.menu);
if (convertView == null) {
menuButton.setOnClickListener(itemMenuButtonListener);
if (enabledRetrievers == null)
view.findViewById(R.id.cover).setVisibility(View.GONE);
}
final Map<String, ?> item = (Map<String, ?>) getItem(position);
menuButton.setTag(item.get("songid"));
if (enabledRetrievers != null) {
final ImageView albumCover = (ImageView) view.findViewById(R.id.cover);
final CoverAsyncHelper coverHelper = new CoverAsyncHelper(app, settings);
coverHelper.setCoverRetrievers(enabledRetrievers);
final int height = albumCover.getHeight();
// If the list is not displayed yet, the height is 0. This is a problem, so set a fallback one.
coverHelper.setCoverMaxSize(height == 0 ? 128 : height);
final AlbumCoverDownloadListener acd = new AlbumCoverDownloadListener(getActivity(), albumCover, lightTheme);
final AlbumCoverDownloadListener oldAcd = (AlbumCoverDownloadListener) albumCover
.getTag(R.id.AlbumCoverDownloadListener);
if (oldAcd != null) {
oldAcd.detach();
}
albumCover.setTag(R.id.AlbumCoverDownloadListener, acd);
coverHelper.addCoverDownloadListener(acd);
coverHelper.downloadCover((String) item.get("_artist"), (String) item.get("_album"), null, null);
}
return view;
}
}
} |
package com.flytxt.tp.processor;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import com.flytxt.tp.processor.filefilter.FlyFileFilter;
public class Processor {
@Autowired
private ApplicationContext ctx;
private final Logger logger = LoggerFactory.getLogger(this.getClass());
List<FlyReader> fileReaders;
private ThreadPoolExecutor executor;
public void stopFileReads() {
if(fileReaders == null){
logger.info("No jobs configured... nothing to stop ");
return;
}
logger.debug("Total FlyReaders to close:"+fileReaders.size());
for (FlyReader aReader : fileReaders)
aReader.preDestroy();
}
@PostConstruct
public void startFileReaders() throws Exception {
ProcessorConfig pConfig = ctx.getBean(ProcessorConfig.class);
List<Job> jobs = pConfig.getJobs();
int size = jobs.size();
if (size < 1) {
logger.info("No jobs configured... ");
return;
}
fileReaders = new ArrayList<FlyReader>(size);
executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(size);
String folder;
for (Job aJob : jobs) {
FlyReader reader = ctx.getBean(FlyReader.class);
LineProcessor lP = pConfig.getLp(aJob.getByteCode(), aJob.getName());
folder = lP.getSourceFolder();
reader.set(folder, lP, getFileFilter(folder, aJob.getName()));
fileReaders.add(reader);
executor.submit(reader);
}
}
/**
*
* @param folder
* @param filterName2
* @return
*/
private FlyFileFilter getFileFilter(String folder, String filterName) {
FlyFileFilter fileFilter = ctx.getBean(FlyFileFilter.class);
fileFilter.set(folder, filterName);
return fileFilter;
}
public void handleEvent(String folderName, String fileName) {
for (FlyReader aReader : fileReaders)
if (aReader.canProcess(folderName, fileName) && aReader.getStatus() != FlyReader.Status.RUNNING) {
executor.submit(aReader);
break;
}
}
@PreDestroy
public void preDestroy() {
for (FlyReader aReader : fileReaders)
aReader.preDestroy();
executor.shutdown();
}
} |
package gov.nih.nci.ncicb.cadsr.loader.ui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
public class AddButtonPanel extends JPanel implements PropertyChangeListener, MouseListener
{
private DropDownButton addButton;
static final String ADD = "Add",
ADD_INHERITANCE = "Add Inheritance";
private ConceptEditorPanel conceptEditorPanel;
public AddButtonPanel(ConceptEditorPanel p) {
conceptEditorPanel = p;
addButton = new DropDownButton(ADD);
JLabel addLabel = new JLabel(ADD),
addInheritanceLabel = new JLabel(ADD_INHERITANCE);
addButton.addComponent(addLabel);
addButton.addComponent(addInheritanceLabel);
addLabel.addMouseListener(this);
addInheritanceLabel.addMouseListener(this);
this.add(addButton);
}
public void propertyChange(PropertyChangeEvent e)
{
if(e.getPropertyName().equals(ADD)) {
addButton.setEnabled((Boolean)e.getNewValue());
}
}
public void mouseClicked(MouseEvent e) {
// cadsrVDPanel.setBackground(Color.WHITE);
// lvdPanel.setBackground(Color.WHITE);
addButton.unfocus();
if(((JLabel)e.getSource()).getText().equals(ADD))
conceptEditorPanel.addPressed();
else if(((JLabel)e.getSource()).getText().equals(ADD_INHERITANCE))
conceptEditorPanel.addInheritancePressed();
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {
// if(((JLabel)e.getSource()).getText().equals(MAP_CADSR_VD))
// cadsrVDPanel.setBackground(Color.LIGHT_GRAY);
// else if(((JLabel)e.getSource()).getText().equals(MAP_LOCAL_VD))
// lvdPanel.setBackground(Color.LIGHT_GRAY);
}
public void mouseExited(MouseEvent e) {
// if(((JLabel)e.getSource()).getText().equals(MAP_CADSR_VD))
// cadsrVDPanel.setBackground(Color.WHITE);
// else if(((JLabel)e.getSource()).getText().equals(MAP_LOCAL_VD))
// lvdPanel.setBackground(Color.WHITE);
}
} |
package shiro.definitions;
import junit.framework.Assert;
import org.junit.Test;
import shiro.expressions.Path;
/**
*
* @author jeffreyguenther
*/
public class PortAssignmentTest {
@Test
public void toCode(){
String expected = "startPoint.x(100)";
PortAssignment a = new PortAssignment(Path.createPath("startPoint.x"),
new shiro.expressions.Number(100d));
Assert.assertEquals("should match", expected, a.toCode());
}
@Test
public void equals(){
PortAssignment a = new PortAssignment(Path.createPath("startPoint.x"),
new shiro.expressions.Number(100d));
PortAssignment b = new PortAssignment(Path.createPath("startPoint.x"),
new shiro.expressions.Number(100d));
PortAssignment c = new PortAssignment(Path.createPath("startPoint.y"),
new shiro.expressions.Number(100d));
Assert.assertEquals(a, b);
Assert.assertFalse(a.equals(c));
}
} |
package cvut.arenaq.mashup;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.GradientDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import org.apmem.tools.layouts.FlowLayout;
import java.io.IOException;
import java.util.StringTokenizer;
import cvut.arenaq.mashup.AlchemyApi.AlchemyApiService;
import cvut.arenaq.mashup.AlchemyApi.GetRankedTaxonomy;
import cvut.arenaq.mashup.AlchemyApi.Taxonomy;
import cvut.arenaq.mashup.IpApi.IpApiModel;
import cvut.arenaq.mashup.IpApi.IpApiService;
import cvut.arenaq.mashup.WhoisApi.WhoisApiService;
import cvut.arenaq.mashup.WhoisApi.WhoisWrapper;
import retrofit.Call;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
public class MainActivity extends Activity {
public static final String WHOIS_API_URL = "http://arenaq-mashup.duke-hq.net/";
public static final String IP_API_URL = "http://ip-api.com/";
public static final String ALCHEMY_API_URL = "http://gateway-a.watsonplatform.net/";
public static final String ALCHEMY_API_KEY = "e9b2175fdaa36af4febe23ec32b3b9ad47154727";
WhoisApiService whoisApiService;
IpApiService ipApiService;
AlchemyApiService alchemyApiService;
TextView domain, ip, owner, created, expire, isp, nameservers, language, location;
FlowLayout taxonomy;
GoogleMap map;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_table);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(IP_API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ipApiService = retrofit.create(IpApiService.class);
retrofit = new Retrofit.Builder()
.baseUrl(ALCHEMY_API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
alchemyApiService = retrofit.create(AlchemyApiService.class);
retrofit = new Retrofit.Builder()
.baseUrl(WHOIS_API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
whoisApiService = retrofit.create(WhoisApiService.class);
domain = (TextView) findViewById(R.id.domain);
ip = (TextView) findViewById(R.id.ip);
owner = (TextView) findViewById(R.id.owner);
created = (TextView) findViewById(R.id.created);
expire = (TextView) findViewById(R.id.expire);
isp = (TextView) findViewById(R.id.isp);
nameservers = (TextView) findViewById(R.id.nameservers);
language = (TextView) findViewById(R.id.language);
taxonomy = (FlowLayout) findViewById(R.id.taxonomy);
location = (TextView) findViewById(R.id.location);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
map.getUiSettings().setScrollGesturesEnabled(false);
}
public void getInfo(final String url) {
domain.setText(url);
new AsyncTask<Void, Void, WhoisWrapper>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
created.setText("");
expire.setText("");
nameservers.setText("");
}
@Override
protected WhoisWrapper doInBackground(Void... params) {
final Call<WhoisWrapper> call = whoisApiService.whois(url);
try {
return call.execute().body();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(WhoisWrapper response) {
super.onPostExecute(response);
if (response == null) return;
created.setText(response.getWhois().getCreated());
expire.setText(response.getWhois().getExpired());
String s = response.getWhois().getNameServer()[0];
if (response.getWhois().getNameServer().length > 1) {
for (int i = 1; i < response.getWhois().getNameServer().length; i++) s += "\n" + response.getWhois().getNameServer()[i];
}
nameservers.setText(s);
}
}.execute();
new AsyncTask<Void, Void, IpApiModel>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
ip.setText("");
owner.setText("");
isp.setText("");
location.setText("");
if (map != null) {
map.clear();
}
}
@Override
protected IpApiModel doInBackground(Void... params) {
final Call<IpApiModel> call = ipApiService.lookup(url);
try {
return call.execute().body();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(IpApiModel response) {
super.onPostExecute(response);
if (response == null) return;
ip.setText(response.getQuery());
owner.setText(response.getOrg());
isp.setText(response.getIsp());
location.setText(response.getCity() + ", " + response.getRegion() + ", " + response.getCountry());
if (map != null) {
LatLng pos = new LatLng(Double.parseDouble(response.getLat()), Double.parseDouble(response.getLon()));
map.addMarker(new MarkerOptions().position(pos))
.setTitle(response.getCity());
map.moveCamera(CameraUpdateFactory.newLatLngZoom(pos, 10));
map.animateCamera(CameraUpdateFactory.zoomTo(14), 2000, null);
}
}
}.execute();
new AsyncTask<Void, Void, GetRankedTaxonomy>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
language.setText("");
taxonomy.removeAllViewsInLayout();
taxonomy.addView(new TextView(MainActivity.this));
}
@Override
protected GetRankedTaxonomy doInBackground(Void... params) {
final Call<GetRankedTaxonomy> call = alchemyApiService.getRankedTaxonomy(ALCHEMY_API_KEY, "json", url);
try {
return call.execute().body();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(GetRankedTaxonomy response) {
super.onPostExecute(response);
if (response == null) return;
language.setText(response.getLanguage());
if (response.getTaxonomy() != null) {
for (Taxonomy t : response.getTaxonomy()) {
String line = t.getLabel();
StringTokenizer st = new StringTokenizer(line, "/");
while (st.hasMoreTokens()) {
String tag = st.nextToken();
TextView v = new TextView(MainActivity.this);
GradientDrawable shape = new GradientDrawable();
shape.setCornerRadius(12);
shape.setColor(Color.parseColor("#468847"));
v.setBackground(shape);
FlowLayout.LayoutParams params = new FlowLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 8, 8, 8);
v.setLayoutParams(params);
v.setPadding(16, 12, 16, 12);
v.setTextColor(Color.WHITE);
v.setTypeface(null, Typeface.BOLD);
v.setText(tag);
taxonomy.addView(v);
//taxonomy.addView(v, llp);
}
}
taxonomy.invalidate();
} else {
String s = "error";
TextView t = new TextView(MainActivity.this);
t.setTextColor(Color.parseColor("#ff0000"));
if (response.getStatusInfo() != null) {
s = response.getStatusInfo();
} else if (response.getStatus() != null) {
s = response.getStatus();
}
t.setText(s);
taxonomy.removeAllViewsInLayout();
taxonomy.addView(t);
}
}
}.execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
final MenuItem item = menu.findItem(R.id.action_lookup);
View v = (View) item.getActionView();
final EditText txtSearch = ( EditText ) v.findViewById(R.id.lookup);
txtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
getInfo(v.getText().toString());
return false;
}
});
item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
txtSearch.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
} if (id == R.id.action_lookup) {
}
return super.onOptionsItemSelected(item);
}
} |
package mobi.hsz.idea.gitignore.lang.kind;
import com.intellij.lang.Language;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import git4idea.config.GitVcsApplicationSettings;
import mobi.hsz.idea.gitignore.file.type.IgnoreFileType;
import mobi.hsz.idea.gitignore.file.type.kind.GitFileType;
import mobi.hsz.idea.gitignore.lang.IgnoreLanguage;
import mobi.hsz.idea.gitignore.util.Icons;
import mobi.hsz.idea.gitignore.util.Utils;
import org.jetbrains.annotations.Nullable;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Gitignore {@link Language} definition.
*
* @author Jakub Chrzanowski <jakub@hsz.mobi>
* @since 0.1
*/
public class GitLanguage extends IgnoreLanguage {
/** The {@link GitLanguage} instance. */
public static final GitLanguage INSTANCE = new GitLanguage();
/** The outer file. */
public static VirtualFile OUTER_FILE;
/** Flag to mark that outer file was fetched. */
private static boolean OUTER_FILE_FETCHED = false;
/** {@link IgnoreLanguage} is a non-instantiable static class. */
private GitLanguage() {
super("Git", "gitignore", Icons.GIT);
}
/** Language file type. */
@Override
public IgnoreFileType getFileType() {
return GitFileType.INSTANCE;
}
/**
* Returns path to the global excludes file.
*
* @return excludes file path
*/
@Nullable
@Override
public VirtualFile getOuterFile() {
if (OUTER_FILE_FETCHED) {
return OUTER_FILE;
}
if (Utils.isGitPluginEnabled()) {
final String bin = GitVcsApplicationSettings.getInstance().getPathToGit();
if (StringUtil.isNotEmpty(bin)) {
try {
Process pr = Runtime.getRuntime().exec(bin + " config --global core.excludesfile");
pr.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String path = Utils.resolveUserDir(reader.readLine());
if (StringUtil.isNotEmpty(path)) {
OUTER_FILE = VfsUtil.findFileByIoFile(new File(path), true);
}
}
catch (IOException ignored) {}
catch (InterruptedException ignored) {}
}
}
OUTER_FILE_FETCHED = true;
return OUTER_FILE;
}
/** The Git specific directory. */
public String getGitDirectory() {
return ".git";
}
} |
package org.eclipse.smarthome.automation.module.script.rulesupport.shared;
import java.util.ArrayList;
import java.util.HashSet;
import org.eclipse.smarthome.automation.Action;
import org.eclipse.smarthome.automation.Condition;
import org.eclipse.smarthome.automation.Rule;
import org.eclipse.smarthome.automation.Trigger;
import org.eclipse.smarthome.automation.module.script.rulesupport.internal.ScriptedCustomModuleHandlerFactory;
import org.eclipse.smarthome.automation.module.script.rulesupport.internal.ScriptedCustomModuleTypeProvider;
import org.eclipse.smarthome.automation.module.script.rulesupport.internal.ScriptedPrivateModuleHandlerFactory;
import org.eclipse.smarthome.automation.module.script.rulesupport.shared.simple.SimpleActionHandler;
import org.eclipse.smarthome.automation.module.script.rulesupport.shared.simple.SimpleConditionHandler;
import org.eclipse.smarthome.automation.module.script.rulesupport.shared.simple.SimpleRuleActionHandler;
import org.eclipse.smarthome.automation.module.script.rulesupport.shared.simple.SimpleRuleActionHandlerDelegate;
import org.eclipse.smarthome.automation.module.script.rulesupport.shared.simple.SimpleTriggerHandler;
import org.eclipse.smarthome.automation.type.ActionType;
import org.eclipse.smarthome.automation.type.ConditionType;
import org.eclipse.smarthome.automation.type.TriggerType;
import org.eclipse.smarthome.config.core.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This Registry is used for a single ScriptEngine instance. It allows the adding and removing of handlers.
* It allows the removal of previously added modules on unload.
*
* @author Simon Merschjohann
*
*/
public class ScriptedAutomationManager {
private static final Logger logger = LoggerFactory.getLogger(ScriptedAutomationManager.class);
private RuleSupportRuleRegistryDelegate ruleRegistryDelegate;
private HashSet<String> modules = new HashSet<>();
private HashSet<String> moduleHandlers = new HashSet<>();
private HashSet<String> privateHandlers = new HashSet<>();
private ScriptedCustomModuleHandlerFactory scriptedCustomModuleHandlerFactory;
private ScriptedCustomModuleTypeProvider scriptedCustomModuleTypeProvider;
private ScriptedPrivateModuleHandlerFactory scriptedPrivateModuleHandlerFactory;
public ScriptedAutomationManager(RuleSupportRuleRegistryDelegate ruleRegistryDelegate,
ScriptedCustomModuleHandlerFactory scriptedCustomModuleHandlerFactory,
ScriptedCustomModuleTypeProvider scriptedCustomModuleTypeProvider,
ScriptedPrivateModuleHandlerFactory scriptedPrivateModuleHandlerFactory) {
this.ruleRegistryDelegate = ruleRegistryDelegate;
this.scriptedCustomModuleHandlerFactory = scriptedCustomModuleHandlerFactory;
this.scriptedCustomModuleTypeProvider = scriptedCustomModuleTypeProvider;
this.scriptedPrivateModuleHandlerFactory = scriptedPrivateModuleHandlerFactory;
}
public void removeModuleType(String UID) {
if (modules.remove(UID)) {
scriptedCustomModuleTypeProvider.removeModuleType(UID);
removeHandler(UID);
}
}
public void removeHandler(String typeUID) {
if (moduleHandlers.remove(typeUID)) {
scriptedCustomModuleHandlerFactory.removeModuleHandler(typeUID);
}
}
public void removePrivateHandler(String privId) {
if (privateHandlers.remove(privId)) {
scriptedPrivateModuleHandlerFactory.removeHandler(privId);
}
}
public void removeAll() {
logger.info("removeAll added handlers");
HashSet<String> types = new HashSet<>(modules);
for (String moduleType : types) {
removeModuleType(moduleType);
}
HashSet<String> moduleHandlers = new HashSet<>(this.moduleHandlers);
for (String uid : moduleHandlers) {
removeHandler(uid);
}
HashSet<String> privateHandlers = new HashSet<>(this.privateHandlers);
for (String privId : privateHandlers) {
removePrivateHandler(privId);
}
ruleRegistryDelegate.removeAllAddedByScript();
}
public Rule addRule(Rule element) {
Rule rule = element.getUID() == null ? new Rule() : new Rule(element.getUID());
String name = element.getName();
if (name == null || name.isEmpty()) {
name = element.getClass().getSimpleName();
if (name.contains("$")) {
name = name.substring(0, name.indexOf('$'));
}
}
rule.setName(name);
rule.setDescription(element.getDescription());
rule.setTags(element.getTags());
// used for numbering the modules of the rule
int moduleIndex = 1;
try {
ArrayList<Condition> conditions = new ArrayList<>();
for (Condition cond : element.getConditions()) {
Condition toAdd = cond;
if (cond.getId() == null || cond.getId().isEmpty()) {
toAdd = new Condition(Integer.toString(moduleIndex++), cond.getTypeUID(), cond.getConfiguration(),
cond.getInputs());
}
conditions.add(toAdd);
}
rule.setConditions(conditions);
} catch (Exception ex) {
// conditions are optional
}
try {
ArrayList<Trigger> triggers = new ArrayList<>();
for (Trigger trigger : element.getTriggers()) {
Trigger toAdd = trigger;
if (trigger.getId() == null || trigger.getId().isEmpty()) {
toAdd = new Trigger(Integer.toString(moduleIndex++), trigger.getTypeUID(),
trigger.getConfiguration());
}
triggers.add(toAdd);
}
rule.setTriggers(triggers);
} catch (Exception ex) {
// triggers are optional
}
ArrayList<Action> actions = new ArrayList<>();
actions.addAll(element.getActions());
if (element instanceof SimpleRuleActionHandler) {
String privId = addPrivateActionHandler(
new SimpleRuleActionHandlerDelegate((SimpleRuleActionHandler) element));
Action scriptedAction = new Action(Integer.toString(moduleIndex++), "jsr223.ScriptedAction",
new Configuration(), null);
scriptedAction.getConfiguration().put("privId", privId);
actions.add(scriptedAction);
}
rule.setActions(actions);
ruleRegistryDelegate.add(rule);
return rule;
}
public void addConditionType(ConditionType condititonType) {
modules.add(condititonType.getUID());
scriptedCustomModuleTypeProvider.addModuleType(condititonType);
}
public void addConditionHandler(String uid, ScriptedHandler conditionHandler) {
moduleHandlers.add(uid);
scriptedCustomModuleHandlerFactory.addModuleHandler(uid, conditionHandler);
scriptedCustomModuleTypeProvider.updateModuleHandler(uid);
}
public String addPrivateConditionHandler(SimpleConditionHandler conditionHandler) {
String uid = scriptedPrivateModuleHandlerFactory.addHandler(conditionHandler);
privateHandlers.add(uid);
return uid;
}
public void addActionType(ActionType actionType) {
modules.add(actionType.getUID());
scriptedCustomModuleTypeProvider.addModuleType(actionType);
}
public void addActionHandler(String uid, ScriptedHandler actionHandler) {
moduleHandlers.add(uid);
scriptedCustomModuleHandlerFactory.addModuleHandler(uid, actionHandler);
scriptedCustomModuleTypeProvider.updateModuleHandler(uid);
}
public String addPrivateActionHandler(SimpleActionHandler actionHandler) {
String uid = scriptedPrivateModuleHandlerFactory.addHandler(actionHandler);
privateHandlers.add(uid);
return uid;
}
public void addTriggerType(TriggerType triggerType) {
modules.add(triggerType.getUID());
scriptedCustomModuleTypeProvider.addModuleType(triggerType);
}
public void addTriggerHandler(String uid, ScriptedHandler triggerHandler) {
moduleHandlers.add(uid);
scriptedCustomModuleHandlerFactory.addModuleHandler(uid, triggerHandler);
scriptedCustomModuleTypeProvider.updateModuleHandler(uid);
}
public String addPrivateTriggerHandler(SimpleTriggerHandler triggerHandler) {
String uid = scriptedPrivateModuleHandlerFactory.addHandler(triggerHandler);
privateHandlers.add(uid);
return uid;
}
} |
package net.rk.splendid.dao.entities;
import net.rk.splendid.dto.GameState;
import net.rk.splendid.dto.PlayerState;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class OfyGameState {
private int round;
private OfyBoard board;
private Map<String, OfyPlayerState> playerState = new HashMap<>();
private OfyGameState() {}
public static OfyGameState fromDto(GameState gameState) {
OfyGameState ofyGameState = new OfyGameState();
ofyGameState.round = gameState.getRound();
ofyGameState.board = OfyBoard.fromDto(gameState.getBoard());
ofyGameState.playerState =
Arrays.stream(gameState.getPlayerState())
.collect(Collectors.toMap(
player -> "unset",
OfyPlayerState::fromDto
));
return ofyGameState;
}
public static GameState toDto(OfyGameState ofyGameState) {
return new GameState(
ofyGameState.round,
OfyBoard.toDto(ofyGameState.board),
ofyGameState.playerState.values().stream()
.map(OfyPlayerState::toDto)
.toArray(PlayerState[]::new)
);
}
} |
package test.serviceloader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import org.testng.TestNG;
import org.testng.annotations.Test;
import junit.framework.Assert;
import test.SimpleBaseTest;
public class ServiceLoaderTest extends SimpleBaseTest {
@Test
public void serviceLoaderShouldWork() throws MalformedURLException {
TestNG tng = create(ServiceLoaderSampleTest.class);
URL url = getClass().getClassLoader().getResource("serviceloader.jar");
URLClassLoader ucl = URLClassLoader.newInstance(new URL[] { url });
tng.setServiceLoaderClassLoader(ucl);
tng.run();
Assert.assertEquals(1, tng.getServiceLoaderListeners().size());
}
} |
package smartfood;
import jade.core.AID;
import jade.core.Agent;
import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.core.behaviours.CyclicBehaviour;
import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;
import jade.wrapper.AgentContainer;
import jade.wrapper.AgentController;
import jade.wrapper.StaleProxyException;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
//apparently Logger is not such a good package, is it?
import java.util.logging.Logger;
public class Communicator extends Agent
{
final Logger logger = jade.util.Logger.getMyLogger(this.getClass().getName());
private static final long serialVersionUID = 1L;
private final AID sf_aid = new AID("SmartFood@SmartFoodSystem", true);
@Override
protected void setup()
{
//apparently this is bad practice
/**basic initiation*/
addBehaviour(new OneShotBehaviour(this)
{
private static final long serialVersionUID = 1L;
@Override
public void action()
{
initMobile();
logger.log(Level.INFO, "{0} initiated", getAID().getName());
}
});
addBehaviour(new CyclicBehaviour(this)
{
@Override
public void action()
{
//reading ALL message received
String sender_name, msg_topic, msg_request;
ACLMessage msg = myAgent.receive();
if (msg != null)
{
sender_name = msg.getSender().getName();
switch(msg.getPerformative())
{
case ACLMessage.REQUEST:
//incoming agents requesting some kind of service/data
msg_topic = msg.getContent().substring(0, msg.getContent().indexOf(":"));
msg_request = msg.getContent().substring(msg.getContent().indexOf(":")+1);
switch(msg_topic)
{
case "products":
//asking for the list of all products
sendMessage(sf_aid.getName(), msg_topic + " " + msg_request, ACLMessage.REQUEST, msg.getOntology());
//TODO: add asynchronized version
String return_content = waitForMessage(ACLMessage.INFORM,
msg.getOntology());
//return back the message
sendMessage(sender_name, return_content,
ACLMessage.INFORM, msg.getOntology());
break;
default:
logger.log(Level.WARNING, "Unknown message topic received");
break;
}
break;
case ACLMessage.INFORM:
//retrieving data from mobile platform
break;
}
}
}
});
}
@Override
protected void takeDown()
{
logger.log(Level.INFO, "Agent {0} terminating.", getAID().getName());
}
/**
* A workaround for running two containers in one process
* It is crucial, that the mobile containers is set up correctly
*/
private void initMobile()
{
try
{
jade.core.Runtime rt = jade.core.Runtime.instance();
jade.core.Profile p = new ProfileImpl();
p.setParameter(Profile.MAIN_HOST, "");
p.setParameter(Profile.MAIN_PORT, "");
p.setParameter(Profile.CONTAINER_NAME, "Mobile");
AgentContainer cc = rt.createAgentContainer(p);
AgentController mobile_comm = cc.createNewAgent("Comm",
"smartfood.mobile.Comm", null);
mobile_comm.start();
}catch(StaleProxyException exc)
{
logger.log(Level.SEVERE, exc.getMessage());
throw new RuntimeException("Cannot init mobile agent");
}
}
/**
* Sends a message to agent
*
* @param to agent GUID name
* @param content content to be sent
* @param performative performative level
*/
private void sendMessage(String to, String content, int performative, String ontology)
{
ACLMessage msg;
msg = new ACLMessage(performative);
msg.addReceiver(new AID(to, true));
msg.setOntology(ontology);
msg.setContent(content);
send(msg);
}
/**
* Waits for the message to return of specific performative and ontology
*
* @param performative message's performative
* @param ontology message's ontology
* @return String content
*/
private String waitForMessage(int performative, String ontology)
{
ACLMessage msg = receive();
int waitTime = 10;//seconds
//using the time comparisson method rather than Thread.sleep()
Calendar current_time = Calendar.getInstance();
current_time.setTime(new Date());
Calendar wait_time = Calendar.getInstance();
wait_time.setTime(new Date());
wait_time.add(Calendar.SECOND, waitTime);
while(msg == null &&
current_time.get(Calendar.SECOND) !=
wait_time.get(Calendar.SECOND))
{
msg = receive();
if (msg != null)
{
if (msg.getPerformative() != performative ||
!msg.getOntology().equals(ontology)) {
msg = null;//not the message we're waiting for
}
}
}
if (msg != null)
{
return msg.getContent();
}else
{
logger.log(Level.SEVERE, "Waited for 10 seconds and no response!");
return "-";
}
}
} |
package net.sf.mzmine.modules.batchmode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import net.sf.mzmine.datamodel.MZmineProject;
import net.sf.mzmine.datamodel.MZmineProjectListener;
import net.sf.mzmine.datamodel.PeakList;
import net.sf.mzmine.datamodel.RawDataFile;
import net.sf.mzmine.main.MZmineCore;
import net.sf.mzmine.modules.MZmineProcessingModule;
import net.sf.mzmine.modules.MZmineProcessingStep;
import net.sf.mzmine.parameters.Parameter;
import net.sf.mzmine.parameters.ParameterSet;
import net.sf.mzmine.parameters.parametertypes.PeakListsParameter;
import net.sf.mzmine.parameters.parametertypes.RawDataFilesParameter;
import net.sf.mzmine.taskcontrol.AbstractTask;
import net.sf.mzmine.taskcontrol.Task;
import net.sf.mzmine.taskcontrol.TaskStatus;
import net.sf.mzmine.util.ExitCode;
/**
* Batch mode task
*/
public class BatchTask extends AbstractTask {
private Logger logger = Logger.getLogger(this.getClass().getName());
private int totalSteps, processedSteps;
private final MZmineProject project;
private final BatchQueue queue;
private final List<RawDataFile> createdDataFiles;
private final List<PeakList> createdPeakLists;
BatchTask(MZmineProject project, ParameterSet parameters) {
this.project = project;
this.queue = parameters.getParameter(BatchModeParameters.batchQueue)
.getValue();
totalSteps = queue.size();
createdDataFiles = new ArrayList<>();
createdPeakLists = new ArrayList<>();
}
public void run() {
setStatus(TaskStatus.PROCESSING);
logger.info("Starting a batch of " + totalSteps + " steps");
// Listen for new items in the project
MZmineProjectListener listener = new MZmineProjectListener() {
@Override
public void peakListAdded(PeakList newPeakList) {
createdPeakLists.add(newPeakList);
}
@Override
public void dataFileAdded(RawDataFile newFile) {
createdDataFiles.add(newFile);
}
};
project.addProjectListener(listener);
// Process individual batch steps
for (int i = 0; i < totalSteps; i++) {
processQueueStep(i);
processedSteps++;
// If we are canceled or ran into error, stop here
if (isCanceled() || (getStatus() == TaskStatus.ERROR)) {
return;
}
}
project.removeProjectListener(listener);
logger.info("Finished a batch of " + totalSteps + " steps");
setStatus(TaskStatus.FINISHED);
}
private void processQueueStep(int stepNumber) {
logger.info("Starting step # " + (stepNumber + 1));
// Run next step of the batch
MZmineProcessingStep<?> currentStep = queue.get(stepNumber);
MZmineProcessingModule method = (MZmineProcessingModule) currentStep
.getModule();
ParameterSet batchStepParameters = currentStep.getParameterSet();
// Update the RawDataFilesParameter parameters to reflect the current
// state of the batch
for (Parameter<?> p : batchStepParameters.getParameters()) {
if (p instanceof RawDataFilesParameter) {
RawDataFilesParameter rdp = (RawDataFilesParameter) p;
RawDataFile createdFiles[] = createdDataFiles
.toArray(new RawDataFile[0]);
rdp.getValue().setBatchLastFiles(createdFiles);
}
}
// Update the PeakListsParameter parameters to reflect the current
// state of the batch
for (Parameter<?> p : batchStepParameters.getParameters()) {
if (p instanceof PeakListsParameter) {
PeakListsParameter rdp = (PeakListsParameter) p;
PeakList createdPls[] = createdPeakLists
.toArray(new PeakList[0]);
rdp.getValue().setBatchLastPeakLists(createdPls);
}
}
// Clear the saved data files and peak lists
createdDataFiles.clear();
createdPeakLists.clear();
// Check if the parameter settings are valid
ArrayList<String> messages = new ArrayList<String>();
boolean paramsCheck = batchStepParameters
.checkParameterValues(messages);
if (!paramsCheck) {
setStatus(TaskStatus.ERROR);
setErrorMessage("Invalid parameter settings for module "
+ method.getName() + ": "
+ Arrays.toString(messages.toArray()));
}
ArrayList<Task> currentStepTasks = new ArrayList<Task>();
ExitCode exitCode = method.runModule(project, batchStepParameters,
currentStepTasks);
if (exitCode != ExitCode.OK) {
setStatus(TaskStatus.ERROR);
setErrorMessage("Could not start batch step " + method.getName());
return;
}
// If current step didn't produce any tasks, continue with next step
if (currentStepTasks.isEmpty())
return;
boolean allTasksFinished = false;
// Submit the tasks to the task controller for processing
MZmineCore.getTaskController().addTasks(
currentStepTasks.toArray(new Task[0]));
while (!allTasksFinished) {
// If we canceled the batch, cancel all running tasks
if (isCanceled()) {
for (Task stepTask : currentStepTasks)
stepTask.cancel();
return;
}
// First set to true, then check all tasks
allTasksFinished = true;
for (Task stepTask : currentStepTasks) {
TaskStatus stepStatus = stepTask.getStatus();
// If any of them is not finished, keep checking
if (stepStatus != TaskStatus.FINISHED)
allTasksFinished = false;
// If there was an error, we have to stop the whole batch
if (stepStatus == TaskStatus.ERROR) {
setStatus(TaskStatus.ERROR);
setErrorMessage(stepTask.getTaskDescription() + ": "
+ stepTask.getErrorMessage());
return;
}
// If user canceled any of the tasks, we have to cancel the
// whole batch
if (stepStatus == TaskStatus.CANCELED) {
setStatus(TaskStatus.CANCELED);
for (Task t : currentStepTasks)
t.cancel();
return;
}
}
// Wait 1s before checking the tasks again
if (!allTasksFinished) {
synchronized (this) {
try {
this.wait(1000);
} catch (InterruptedException e) {
// ignore
}
}
}
}
}
public double getFinishedPercentage() {
if (totalSteps == 0)
return 0;
return (double) processedSteps / totalSteps;
}
public String getTaskDescription() {
return "Batch of " + totalSteps + " steps";
}
} |
package tk.hintss.jbrainfuck;
import org.junit.Test;
import static org.junit.Assert.*;
public class InterpreterTest {
@Test
public void interpretert() {
Interpreter bfInter = new Interpreter(".");
bfInter.exec();
assertEquals(". outputs the current byte and getOutput() returns output", "\0", bfInter.getOutput());
assertEquals("getNewOutput() returns new output", "\0", bfInter.getNewOutput());
assertEquals("getNewOutput() ONLY returns new output", "", bfInter.getNewOutput());
bfInter = new Interpreter("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.");
bfInter.exec();
assertEquals("+ increments properly", "A", bfInter.getOutput());
bfInter = new Interpreter("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-.");
bfInter.exec();
assertEquals("- decrements properly", "A", bfInter.getOutput());
bfInter = new Interpreter("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<.>.");
bfInter.exec();
assertEquals("> and < work", "AB", bfInter.getOutput());
bfInter = new Interpreter("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[>+<-]>.");
bfInter.exec();
assertEquals("[ and ] work", "A", bfInter.getOutput());
bfInter = new Interpreter("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[>+<-[>+<-]]>.");
bfInter.exec();
assertEquals("nested [ and ] work", "A", bfInter.getOutput());
}
} |
package som.interpreter;
import som.interpreter.LexicalScope.MethodScope;
import som.interpreter.nodes.ExpressionNode;
import com.oracle.truffle.api.frame.FrameDescriptor;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.api.nodes.NodeUtil;
import com.oracle.truffle.api.source.SourceSection;
public final class Method extends Invokable {
private final MethodScope currentMethodScope;
public Method(final SourceSection sourceSection,
final ExpressionNode expressions,
final MethodScope currentLexicalScope,
final ExpressionNode uninitialized) {
super(sourceSection, currentLexicalScope.getFrameDescriptor(),
expressions, uninitialized);
this.currentMethodScope = currentLexicalScope;
currentLexicalScope.setMethod(this);
}
@Override
public String toString() {
SourceSection ss = getSourceSection();
final String id = ss == null ? "" : ss.getIdentifier();
return "Method " + id + "\t@" + Integer.toHexString(hashCode());
}
@Override
public Invokable cloneWithNewLexicalContext(final MethodScope outerMethodScope) {
FrameDescriptor inlinedFrameDescriptor = getFrameDescriptor().copy();
MethodScope inlinedCurrentScope = new MethodScope(
inlinedFrameDescriptor, outerMethodScope,
null /* because we got an enclosing method anyway */);
ExpressionNode inlinedBody = SplitterForLexicallyEmbeddedCode.doInline(
uninitializedBody, inlinedCurrentScope);
Method clone = new Method(getSourceSection(), inlinedBody,
inlinedCurrentScope, uninitializedBody);
return clone;
}
public Invokable cloneAndAdaptToEmbeddedOuterContext(
final InlinerForLexicallyEmbeddedMethods inliner) {
MethodScope currentAdaptedScope = new MethodScope(
getFrameDescriptor().copy(), inliner.getCurrentMethodScope(),
null /* because we got an enclosing method anyway */);
ExpressionNode adaptedBody = InlinerAdaptToEmbeddedOuterContext.doInline(
uninitializedBody, inliner, currentAdaptedScope);
ExpressionNode uninitAdaptedBody = NodeUtil.cloneNode(adaptedBody);
Method clone = new Method(getSourceSection(), adaptedBody,
currentAdaptedScope, uninitAdaptedBody);
return clone;
}
public Invokable cloneAndAdaptToSomeOuterContextBeingEmbedded(
final InlinerAdaptToEmbeddedOuterContext inliner) {
MethodScope currentAdaptedScope = new MethodScope(
getFrameDescriptor().copy(), inliner.getCurrentMethodScope(),
null /* because we got an enclosing method anyway */);
ExpressionNode adaptedBody = InlinerAdaptToEmbeddedOuterContext.doInline(
uninitializedBody, inliner, currentAdaptedScope);
ExpressionNode uninitAdaptedBody = NodeUtil.cloneNode(adaptedBody);
Method clone = new Method(getSourceSection(),
adaptedBody, currentAdaptedScope, uninitAdaptedBody);
return clone;
}
@Override
public void propagateLoopCountThroughoutMethodScope(final long count) {
assert count >= 0;
currentMethodScope.propagateLoopCountThroughoutMethodScope(count);
reportLoopCount((count > Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) count);
}
@Override
public Node deepCopy() {
return cloneWithNewLexicalContext(currentMethodScope.getOuterMethodScopeOrNull());
}
} |
package nl.hsac.fitnesse.junit;
import fitnesse.ContextConfigurator;
import fitnesse.FitNesseContext;
import fitnesse.components.PluginsClassLoaderFactory;
import fitnesse.junit.DescriptionFactory;
import fitnesse.junit.FitNesseRunner;
import fitnesse.testrunner.MultipleTestsRunner;
import fitnesse.wiki.WikiPage;
import nl.hsac.fitnesse.fixture.Environment;
import nl.hsac.fitnesse.fixture.slim.web.LayoutTest;
import nl.hsac.fitnesse.fixture.slim.web.SeleniumDriverSetup;
import nl.hsac.fitnesse.fixture.util.FileUtil;
import nl.hsac.fitnesse.fixture.util.selenium.driverfactory.DriverFactory;
import nl.hsac.fitnesse.junit.selenium.LocalSeleniumDriverClassFactoryFactory;
import nl.hsac.fitnesse.junit.selenium.LocalSeleniumDriverFactoryFactory;
import nl.hsac.fitnesse.junit.selenium.SeleniumDriverFactoryFactory;
import nl.hsac.fitnesse.junit.selenium.SeleniumGridDriverFactoryFactory;
import nl.hsac.fitnesse.junit.selenium.SeleniumJsonGridDriverFactoryFactory;
import nl.hsac.fitnesse.junit.selenium.SimpleSeleniumGridDriverFactoryFactory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.NotFileFilter;
import org.apache.commons.io.filefilter.OrFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.model.InitializationError;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* JUnit Runner to run a FitNesse suite or page as JUnit test.
*
* The suite/page to run must be specified either via the Java property
* 'fitnesseSuiteToRun', or by adding a {@Link FitNesseRunner.Name} annotation to the test class.
* If both are present the system property is used.
*
* The Selenium driver used for tests may be overridden (from what is configured in the wiki)
* by specifying the property 'seleniumGridUrl' and either 'seleniumBrowser' or 'seleniumCapabilities'.
* The default timeout (in seconds) for Selenium tests may be overridden by specifying the property
* 'seleniumDefaultTimeout'.
*
* The HTML generated for each page is saved in the location specified by the system property 'fitnesseResultsDir',
* or in the location configured using the {@link FitNesseRunner.OutputDir} annotation, or in target/fitnesse-results.
*/
public class HsacFitNesseRunner extends FitNesseRunner {
/**
* The <code>FilesSectionCopy</code> annotation specifies which directories in the FitNesseRoot files
* section to exclude from tests output (which makes them available in tests and in the generated test reports).
* Each excludes can use wildcards.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface FilesSectionCopy {
List<String> DEFAULT_EXCLUDES = Arrays.asList(
"testResults", "testProgress", // FitNesse
"screenshots", "pagesources", "downloads", // BrowserTest
"galen-reports", // LayoutTest
"fileFixture", // FileFixture
"test", // HsacExamples.SlimTests.UtilityFixtures.FileFixture
"galenExamples", // HsacExamples.SlimTests.BrowserTest.LayoutTest
"httpPostExamples", // HsacExamples.SlimTests.HttpTest.HttpPostFileTest
"Desktop.ini", // Windows
".DS_Store", // macOS
".svn"); // Subversion
String[] exclude() default {};
boolean addDefaultExcludes() default true;
}
/** Output path for HTML results */
public final static String FITNESSE_RESULTS_PATH_OVERRIDE_VARIABLE_NAME = "fitnesseResultsDir";
public final static String FITNESSE_RESULTS_PATH = "target/fitnesse-results";
/** Property to override suite to run */
public final static String SUITE_OVERRIDE_VARIABLE_NAME = "fitnesseSuiteToRun";
public final static String SUITE_FILTER_STRATEGY_OVERRIDE_VARIABLE_NAME = "suiteFilterStrategy";
public final static String SUITE_FILTER_OVERRIDE_VARIABLE_NAME = "suiteFilter";
public final static String EXCLUDE_SUITE_FILTER_OVERRIDE_VARIABLE_NAME = "excludeSuiteFilter";
public final static String SELENIUM_DEFAULT_TIMEOUT_PROP = "seleniumDefaultTimeout";
public final static String RE_RUN_SUITE_LOCATION_OVERRIDE_VARIABLE_NAME = "reRunSuiteLocation";
protected final List<SeleniumDriverFactoryFactory> factoryFactories = new ArrayList<>();
public HsacFitNesseRunner(Class<?> suiteClass) throws InitializationError {
super(suiteClass);
try {
factoryFactories.add(new SimpleSeleniumGridDriverFactoryFactory());
factoryFactories.add(new SeleniumGridDriverFactoryFactory());
factoryFactories.add(new SeleniumJsonGridDriverFactoryFactory());
factoryFactories.add(new LocalSeleniumDriverFactoryFactory());
factoryFactories.add(new LocalSeleniumDriverClassFactoryFactory());
Environment environment = Environment.getInstance();
// we include images in output so build server will have single
// we must ensure any files present in the wiki's files section are also present there, so tests
// can use them
String outputDir = getOutputDir(suiteClass);
new File(outputDir).mkdirs();
String fitNesseDir = getFitNesseDir(suiteClass);
environment.setFitNesseDir(fitNesseDir);
String srcRootDir = fitNesseDir + "/" + getFitNesseRoot(suiteClass);
environment.setFitNesseRoot(srcRootDir);
String srcFilesDir = environment.getFitNesseFilesSectionDir();
environment.setFitNesseRoot(outputDir);
String targetFilesDir = environment.getFitNesseFilesSectionDir();
copyFilesToOutputDir(suiteClass, srcFilesDir, targetFilesDir);
} catch (Exception e) {
throw new InitializationError(e);
}
}
protected void copyFilesToOutputDir(Class<?> suiteClass, String srcFilesDir, String targetFilesDir) throws IOException {
File srcDir = new File(srcFilesDir);
if (srcDir.exists()) {
FileFilter fileSectionFilter = getFileSectionCopyFilter(suiteClass);
FileUtils.copyDirectory(srcDir, new File(targetFilesDir), fileSectionFilter);
}
}
protected FileFilter getFileSectionCopyFilter(Class<?> suiteClass) {
List<String> excludes = getFileSectionCopyExcludes(suiteClass);
List<IOFileFilter> excludeFilters = new ArrayList<>(excludes.size());
excludes.forEach(x -> excludeFilters.add(new WildcardFileFilter(x)));
return new NotFileFilter(new OrFileFilter(excludeFilters));
}
protected List<String> getFileSectionCopyExcludes(Class<?> suiteClass) {
List<String> excludes = FilesSectionCopy.DEFAULT_EXCLUDES;
FilesSectionCopy fsAnn = suiteClass.getAnnotation(FilesSectionCopy.class);
if (fsAnn != null) {
excludes = new ArrayList<>();
String[] explicitExcludes = fsAnn.exclude();
if (explicitExcludes.length > 0) {
excludes.addAll(Arrays.asList(explicitExcludes));
}
if (fsAnn.addDefaultExcludes()) {
excludes.addAll(FilesSectionCopy.DEFAULT_EXCLUDES);
}
}
return excludes;
}
@Override
protected String getSuiteName(Class<?> klass) throws InitializationError {
String name = System.getProperty(SUITE_OVERRIDE_VARIABLE_NAME);
if (StringUtils.isEmpty(name)) {
Suite nameAnnotation = klass.getAnnotation(Suite.class);
if (nameAnnotation == null) {
throw new InitializationError("There must be a @Suite annotation");
}
name = nameAnnotation.value();
}
return name;
}
@Override
protected String getFitNesseDir(Class<?> suiteClass) throws InitializationError {
String dir = "wiki";
if (suiteClass.isAnnotationPresent(FitnesseDir.class)) {
dir = super.getFitNesseDir(suiteClass);
}
return dir;
}
@Override
protected String getOutputDir(Class<?> klass) throws InitializationError {
String dir = System.getProperty(FITNESSE_RESULTS_PATH_OVERRIDE_VARIABLE_NAME);
if (StringUtils.isEmpty(dir)) {
dir = FITNESSE_RESULTS_PATH;
if (klass.isAnnotationPresent(OutputDir.class)) {
dir = super.getOutputDir(klass);
}
}
return dir;
}
@Override
protected String getFitNesseRoot(Class<?> suiteClass) {
String root = ContextConfigurator.DEFAULT_ROOT;
if (suiteClass.isAnnotationPresent(FitnesseDir.class)) {
root = super.getFitNesseRoot(suiteClass);
}
return root;
}
@Override
protected FitNesseContext createContext(Class<?> suiteClass) throws Exception {
// disable maven-classpath-plugin, we expect all jars to be loaded as part of this jUnit run
System.setProperty("fitnesse.wikitext.widgets.MavenClasspathSymbolType.Disable", "true");
ClassLoader cl = new PluginsClassLoaderFactory().getClassLoader(getFitNesseDir(suiteClass));
ContextConfigurator configurator = initContextConfigurator().withClassLoader(cl);
return configurator.makeFitNesseContext();
}
@Override
protected void runPages(List<WikiPage> pages, RunNotifier notifier) {
boolean seleniumConfigOverridden = configureSeleniumIfNeeded();
try {
super.runPages(pages, notifier);
} finally {
if (seleniumConfigOverridden) {
try {
shutdownSelenium();
}
catch (Exception e) {
System.err.println("Error shutting down selenium");
e.printStackTrace();
}
}
try {
Class<?> suiteClass = getTestClass().getJavaClass();
String outputDir = getOutputDir(suiteClass);
String suiteName = getSuiteName(suiteClass);
String filename = suiteName + ".html";
File overviewFile = new File(outputDir, filename);
if (overviewFile.exists()) {
String path = overviewFile.getAbsolutePath();
String overviewHtml = FileUtil.streamToString(new FileInputStream(path), path);
if (overviewHtml != null) {
String indexHtml = getIndexHtmlContent(overviewHtml);
FileUtil.writeFile(new File(outputDir, "index.html").getAbsolutePath(), indexHtml);
}
}
} catch (Exception e) {
System.err.println("Unable to create index.html for top level suite");
e.printStackTrace();
}
}
}
@Override
protected void addTestSystemListeners(RunNotifier notifier, MultipleTestsRunner testRunner, Class<?> suiteClass, DescriptionFactory descriptionFactory) {
super.addTestSystemListeners(notifier, testRunner, suiteClass, descriptionFactory);
try {
String fitNesseRootDir = getReRunSuiteLocation(suiteClass);
String fileToCreate = fitNesseRootDir + "/ReRunLastFailures.wiki";
testRunner.addTestSystemListener(new ReRunSuiteTestSystemListener(fileToCreate));
} catch (Exception e) {
System.err.println("Unable to create re-run suite generator: " + e);
}
}
protected String getReRunSuiteLocation(Class<?> suiteClass) throws InitializationError {
String reRunSuiteLocation = System.getProperty(RE_RUN_SUITE_LOCATION_OVERRIDE_VARIABLE_NAME);
if (StringUtils.isEmpty(reRunSuiteLocation)) {
reRunSuiteLocation = getFitNesseDir(suiteClass) + "/" + getFitNesseRoot(suiteClass);
}
return reRunSuiteLocation;
}
@Override
protected boolean getSuiteFilterAndStrategy(Class<?> klass) throws Exception {
String strategy = System.getProperty(SUITE_FILTER_STRATEGY_OVERRIDE_VARIABLE_NAME);
if (StringUtils.isEmpty(strategy)) {
return super.getSuiteFilterAndStrategy(klass);
} else {
return strategy.equalsIgnoreCase("and");
}
}
@Override
protected String getSuiteFilter(Class<?> klass) throws Exception {
String suiteFilter = System.getProperty(SUITE_FILTER_OVERRIDE_VARIABLE_NAME);
if (StringUtils.isEmpty(suiteFilter)) {
suiteFilter = super.getSuiteFilter(klass);
}
return suiteFilter;
}
@Override
protected String getExcludeSuiteFilter(Class<?> klass) throws Exception {
String excludeSuiteFilter = System.getProperty(EXCLUDE_SUITE_FILTER_OVERRIDE_VARIABLE_NAME);
if (StringUtils.isEmpty(excludeSuiteFilter)) {
excludeSuiteFilter = super.getExcludeSuiteFilter(klass);
}
return excludeSuiteFilter;
}
/**
* Determines whether system properties should override Selenium configuration in wiki.
* If so Selenium will be configured according to property values, and locked so that wiki pages
* no longer control Selenium setup.
* @return true if Selenium was configured.
*/
protected boolean configureSeleniumIfNeeded() {
setSeleniumDefaultTimeOut();
try {
DriverFactory factory = null;
SeleniumDriverFactoryFactory factoryFactory = getSeleniumDriverFactoryFactory();
if (factoryFactory != null) {
factory = factoryFactory.getDriverFactory();
if (factory != null) {
SeleniumDriverSetup.lockConfig();
Environment.getInstance().getSeleniumDriverManager().setFactory(factory);
}
}
return factory != null;
} catch (Exception e) {
throw new RuntimeException("Error overriding Selenium config", e);
}
}
protected void setSeleniumDefaultTimeOut() {
String propValue = System.getProperty(SELENIUM_DEFAULT_TIMEOUT_PROP);
if (StringUtils.isNotEmpty(propValue)) {
try {
int timeoutSeconds = Integer.parseInt(propValue);
Environment.getInstance().getSeleniumDriverManager().setDefaultTimeoutSeconds(timeoutSeconds);
} catch (NumberFormatException e) {
throw new RuntimeException("Bad " + SELENIUM_DEFAULT_TIMEOUT_PROP + " system property: " + propValue, e);
}
}
}
protected SeleniumDriverFactoryFactory getSeleniumDriverFactoryFactory() {
SeleniumDriverFactoryFactory result = null;
for (SeleniumDriverFactoryFactory factory : factoryFactories) {
if (factory.willOverride()) {
result = factory;
break;
}
}
return result;
}
protected void shutdownSelenium() {
SeleniumDriverSetup.unlockConfig();
new SeleniumDriverSetup().stopDriver();
}
protected String getIndexHtmlContent(String overviewHtml) {
String result = overviewHtml;
String runSummary = getRunSummary();
if (!"".equals(runSummary)) {
result = overviewHtml.replaceFirst("<table", runSummary + "<table");
}
return result;
}
protected String getRunSummary() {
String runSummary = "";
String seleniumSummary = SeleniumDriverSetup.getLastRunSummary();
if (seleniumSummary != null) {
runSummary += seleniumSummary;
}
String galenReport = LayoutTest.getOverallReportLink();
if (galenReport != null) {
runSummary += galenReport;
}
return runSummary;
}
} |
package no.uio.ifi.trackfind.frontend;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.annotations.Widgetset;
import com.vaadin.data.HasValue;
import com.vaadin.event.ShortcutAction;
import com.vaadin.event.ShortcutListener;
import com.vaadin.server.FileDownloader;
import com.vaadin.server.Resource;
import com.vaadin.server.StreamResource;
import com.vaadin.server.VaadinRequest;
import com.vaadin.shared.ui.ContentMode;
import com.vaadin.shared.ui.ValueChangeMode;
import com.vaadin.shared.ui.dnd.DropEffect;
import com.vaadin.shared.ui.dnd.EffectAllowed;
import com.vaadin.spring.annotation.SpringUI;
import com.vaadin.ui.*;
import com.vaadin.ui.components.grid.TreeGridDragSource;
import com.vaadin.ui.dnd.DropTargetExtension;
import lombok.extern.slf4j.Slf4j;
import no.uio.ifi.trackfind.backend.data.providers.DataProvider;
import no.uio.ifi.trackfind.backend.data.providers.DataProvidersRepository;
import no.uio.ifi.trackfind.backend.services.TrackFindService;
import no.uio.ifi.trackfind.frontend.components.KeyboardInterceptorExtension;
import no.uio.ifi.trackfind.frontend.components.TrackFindTree;
import no.uio.ifi.trackfind.frontend.data.TreeNode;
import no.uio.ifi.trackfind.frontend.listeners.TextAreaDropListener;
import no.uio.ifi.trackfind.frontend.listeners.TreeItemClickListener;
import no.uio.ifi.trackfind.frontend.listeners.TreeSelectionListener;
import no.uio.ifi.trackfind.frontend.providers.TrackDataProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import java.io.ByteArrayInputStream;
import java.nio.charset.Charset;
import java.util.*;
@SpringUI
@Widgetset("TrackFindWidgetSet")
@Title("TrackFind")
@Theme("trackfind")
@Slf4j
public class TrackFindUI extends UI {
private final DataProvidersRepository dataProvidersRepository;
private final TrackFindService trackFindService;
private final Gson gson;
private Collection<Map> lastResults;
private TextArea queryTextArea;
private TextArea resultsTextArea;
private FileDownloader fileDownloader;
private Button exportButton;
@Autowired
public TrackFindUI(DataProvidersRepository dataProvidersRepository, TrackFindService trackFindService) {
this.dataProvidersRepository = dataProvidersRepository;
this.trackFindService = trackFindService;
this.gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
}
@Override
protected void init(VaadinRequest vaadinRequest) {
HorizontalLayout headerLayout = buildHeaderLayout();
VerticalLayout treeLayout = buildTreeLayout();
VerticalLayout queryLayout = buildQueryLayout();
VerticalLayout resultsLayout = buildResultsLayout();
HorizontalLayout mainLayout = buildMainLayout(treeLayout, queryLayout, resultsLayout);
HorizontalLayout footerLayout = buildFooterLayout();
VerticalLayout outerLayout = buildOuterLayout(headerLayout, mainLayout, footerLayout);
setContent(outerLayout);
}
private VerticalLayout buildOuterLayout(HorizontalLayout headerLayout, HorizontalLayout mainLayout, HorizontalLayout footerLayout) {
VerticalLayout outerLayout = new VerticalLayout(headerLayout, mainLayout, footerLayout);
outerLayout.setSizeFull();
outerLayout.setExpandRatio(headerLayout, 0.05f);
outerLayout.setExpandRatio(mainLayout, 0.9f);
outerLayout.setExpandRatio(footerLayout, 0.05f);
return outerLayout;
}
private HorizontalLayout buildMainLayout(VerticalLayout treeLayout, VerticalLayout queryLayout, VerticalLayout resultsLayout) {
HorizontalLayout mainLayout = new HorizontalLayout(treeLayout, queryLayout, resultsLayout);
mainLayout.setSizeFull();
return mainLayout;
}
private VerticalLayout buildResultsLayout() {
resultsTextArea = new TextArea();
resultsTextArea.setSizeFull();
resultsTextArea.setReadOnly(true);
resultsTextArea.addStyleName("scrollable-text-area");
resultsTextArea.addValueChangeListener((HasValue.ValueChangeListener<String>) event -> {
if (StringUtils.isEmpty(event.getValue())) {
exportButton.setEnabled(false);
exportButton.setCaption("Export as GSuite file");
} else {
exportButton.setEnabled(true);
exportButton.setCaption("Export (" + lastResults.size() + ") entries as GSuite file");
}
});
Panel resultsPanel = new Panel("Data", resultsTextArea);
resultsPanel.setSizeFull();
exportButton = new Button("Export as GSuite file");
exportButton.setEnabled(false);
VerticalLayout resultsLayout = new VerticalLayout(resultsPanel, exportButton);
resultsLayout.setSizeFull();
resultsLayout.setExpandRatio(resultsPanel, 1f);
return resultsLayout;
}
private VerticalLayout buildQueryLayout() {
queryTextArea = new TextArea();
queryTextArea.setSizeFull();
queryTextArea.addShortcutListener(new ShortcutListener("Execute query", ShortcutAction.KeyCode.ENTER, new int[]{ShortcutAction.ModifierKey.CTRL}) {
@Override
public void handleAction(Object sender, Object target) {
executeQuery(queryTextArea.getValue());
}
});
queryTextArea.addShortcutListener(new ShortcutListener("Execute query", ShortcutAction.KeyCode.ENTER, new int[]{ShortcutAction.ModifierKey.META}) {
@Override
public void handleAction(Object sender, Object target) {
executeQuery(queryTextArea.getValue());
}
});
DropTargetExtension<TextArea> dropTarget = new DropTargetExtension<>(queryTextArea);
dropTarget.setDropEffect(DropEffect.COPY);
dropTarget.addDropListener(new TextAreaDropListener(queryTextArea));
Panel queryPanel = new Panel("Search query", queryTextArea);
queryPanel.setSizeFull();
VerticalLayout helpLayout = buildHelpLayout();
PopupView popup = new PopupView("Help", helpLayout);
VerticalLayout queryLayout = new VerticalLayout(queryPanel, popup);
queryLayout.setSizeFull();
queryLayout.setExpandRatio(queryPanel, 1f);
return queryLayout;
}
private VerticalLayout buildHelpLayout() {
Collection<Component> instructions = new ArrayList<>();
instructions.add(new Label("<b>How to perform a search:<b> ", ContentMode.HTML));
instructions.add(new Label("1. Navigate through metamodel tree using browser on the left."));
instructions.add(new Label("2. Filter values using text-field in the bottom if needed."));
instructions.add(new Label("3. Drag and drop attribute name or value to the query area."));
instructions.add(new Label("4. Correct query manually if necessary."));
instructions.add(new Label("5. Press <i>Ctrl+Shift</i> or <i>Command+Shift</i> to execute the query.", ContentMode.HTML));
instructions.add(new Label("<b>Hotkeys:<b> ", ContentMode.HTML));
instructions.add(new Label("Use <i>Ctrl</i> or <i>Command</i> to select multiple values in tree.", ContentMode.HTML));
instructions.add(new Label("Use <i>Shift</i> to select range of values in tree.", ContentMode.HTML));
instructions.add(new Label("Hold <i>Alt</i> or <i>Option</i> key while dragging to use OR operator instead of AND.", ContentMode.HTML));
instructions.add(new Label("Hold <i>Shift</i> key while dragging to add NOT operator.", ContentMode.HTML));
VerticalLayout helpLayout = new VerticalLayout();
instructions.forEach(helpLayout::addComponent);
TextField sampleQueryTextField = new TextField("Sample query", "sample_id: SRS306625_*_471 OR other_attributes>lab: U??D AND ihec_data_portal>assay: (WGB-Seq OR something)");
sampleQueryTextField.setEnabled(false);
sampleQueryTextField.setWidth(100, Unit.PERCENTAGE);
helpLayout.addComponent(sampleQueryTextField);
return helpLayout;
}
private void executeQuery(String query) {
lastResults = trackFindService.search(query);
String jsonResult = gson.toJson(lastResults);
if (CollectionUtils.isEmpty(lastResults)) {
resultsTextArea.setValue("");
} else {
resultsTextArea.setValue(jsonResult);
}
String result = "##location: remote\n" +
"##file format: unknown\n" +
"##track type: unknown\n" +
"##genome: hg19\n" +
"###uri";
for (Map lastResult : lastResults) {
String dataProviderName = String.valueOf(lastResult.get(DataProvidersRepository.JSON_KEY));
Optional<DataProvider> dataProviderOptional = dataProvidersRepository.getDataProvider(dataProviderName);
if (dataProviderOptional.isPresent()) {
result += "\n" + dataProviderOptional.get().getUrlFromDataset(lastResult);
} else {
result += "\n error: can't find DataProvider for " + dataProviderName;
}
}
if (fileDownloader != null) {
exportButton.removeExtension(fileDownloader);
}
String finalResult = result;
Resource resource = new StreamResource((StreamResource.StreamSource) () -> new ByteArrayInputStream(finalResult.getBytes(Charset.defaultCharset())),
Calendar.getInstance().getTime().toString() + ".gsuite");
fileDownloader = new FileDownloader(resource);
fileDownloader.extend(exportButton);
}
@SuppressWarnings("unchecked")
private VerticalLayout buildTreeLayout() {
TrackFindTree<TreeNode> tree = new TrackFindTree<>();
tree.setSelectionMode(Grid.SelectionMode.MULTI);
tree.addItemClickListener(new TreeItemClickListener(tree));
tree.addSelectionListener(new TreeSelectionListener(tree, new KeyboardInterceptorExtension(tree)));
TreeGridDragSource<TreeNode> dragSource = new TreeGridDragSource<>((TreeGrid<TreeNode>) tree.getCompositionRoot());
dragSource.setEffectAllowed(EffectAllowed.COPY);
TrackDataProvider trackDataProvider = new TrackDataProvider(new TreeNode(trackFindService.getMetamodelTree()));
tree.setDataProvider(trackDataProvider);
TextField valuesFilterTextField = new TextField("Filter values", (HasValue.ValueChangeListener<String>) event -> {
trackDataProvider.setValuesFilter(event.getValue());
trackDataProvider.refreshAll();
});
valuesFilterTextField.setValueChangeMode(ValueChangeMode.EAGER);
valuesFilterTextField.setWidth(100, Unit.PERCENTAGE);
tree.setSizeFull();
tree.setStyleGenerator((StyleGenerator<TreeNode>) item -> item.isFinalAttribute() || item.isLeaf() ? null : "disabled-tree-node");
Panel treePanel = new Panel("Model browser", tree);
treePanel.setSizeFull();
VerticalLayout treeLayout = new VerticalLayout(treePanel, valuesFilterTextField);
treeLayout.setSizeFull();
treeLayout.setExpandRatio(treePanel, 1f);
return treeLayout;
}
private HorizontalLayout buildFooterLayout() {
Label footerLabel = new Label("2017");
HorizontalLayout footerLayout = new HorizontalLayout(footerLabel);
footerLayout.setSizeFull();
footerLayout.setComponentAlignment(footerLabel, Alignment.BOTTOM_CENTER);
return footerLayout;
}
private HorizontalLayout buildHeaderLayout() {
Label headerLabel = new Label("TrackFind");
HorizontalLayout headerLayout = new HorizontalLayout(headerLabel);
headerLayout.setSizeFull();
headerLayout.setComponentAlignment(headerLabel, Alignment.TOP_CENTER);
return headerLayout;
}
} |
package timeBench.data.io;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import prefuse.data.Edge;
import prefuse.data.Node;
import prefuse.data.Table;
import prefuse.data.Tuple;
import prefuse.data.io.DataIOException;
import prefuse.data.io.GraphMLReader.Tokens;
import prefuse.util.collections.IntIterator;
import timeBench.data.TemporalDataException;
import timeBench.data.TemporalDataset;
import timeBench.data.TemporalElement;
import timeBench.data.TemporalObject;
import javax.xml.stream.*;
import javax.xml.stream.events.XMLEvent;
import org.apache.log4j.Logger;
public class GraphMLTemporalDatasetReader extends AbstractTemporalDatasetReader {
private static final String EDGE_TARGET = "_target";
private static final String EDGE_SOURCE = "_source";
/**
* TemporalDataset to be filled and accessible via the readData method.
*/
private TemporalDataset tds = new TemporalDataset();
//Constants for the use in class
private static String TEMP_ELEMENT_ATTR_PREFIX = prefuse.util.PrefuseConfig.getConfig().getProperty("data.visual.fieldPrefix");
private static String ROOT = "root";
private static String GRAPH_DIRECTED = "directed";
/**
* Returns the TemporalDataset read from a GraphML file. Overrides method of the superclass.
* @throws TemporalDataException
* @see timeBench.data.io.AbstractTemporalDatasetReader#readData(java.io.InputStream)
*/
@Override
public TemporalDataset readData(InputStream is) throws DataIOException, TemporalDataException {
//Try catch for all the various exception that can occur in the mainReader and it's subcalls.
try {
//mainReader is called upon the start the reading
mainReader(is);
} catch (XMLStreamException e) {
e.printStackTrace();
throw new DataIOException(e);
} catch (FactoryConfigurationError e) {
e.printStackTrace();
throw new DataIOException(e);
} catch (IOException e) {
e.printStackTrace();
throw new DataIOException(e);
}
finally{
try {
//close the InputStream when done reading
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//return the TemporalDataset in which all the data of the GraphML has been stored in
return tds;
}
/**
* Reads the GraphML-file and checks it's content.
*
* @param is
* @throws XMLStreamException
* @throws FactoryConfigurationError
* @throws IOException
* @throws TemporalDataException
* @throws DataIOException
*/
private void mainReader(InputStream is) throws XMLStreamException, FactoryConfigurationError, IOException, TemporalDataException, DataIOException
{
//create an instance of the XMLStreamReader via the InputStream
XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(is);
//Objects needed for operation
int event; //Takes the type of the occurring XMLEvent
int graphCounter = 0; //Used to count graph occurrences, only 1 allowed
String nextFieldName = null; //Used to save the name of the current data element and to add it's value to the hashMap in the CHARACTERS event
String lastID = null; //Used to block out root elements as TE/TO and to add the current ID of a node to the hashMap
String oldElement = null; //Used to check the key/graph validity
// TODO check edge directed || edgedefault -- each edge must be directed either by default or separately --> not needed now
// boolean edgedefault = false;
HashMap<String, String> dataMap = new HashMap<String, String>(); //hashMap that temporarily stores the data of a node, gathers as the necessary values to add it to the TMDS
ArrayList<Long> rootList = new ArrayList<Long>(); //Used to save the IDs of the root nodes
Table edgeCache = prepareEdgeCache();
HashMap<String, String> attributeIdToName = new HashMap<String, String>();
//Read the GraphML line for line
while (reader.hasNext()) {
//saves the next occurring event type
event = reader.next();
//Switch through the event type enumeration of XMLEvent
switch (event) {
//Determines if an element starts and after that the type of the element
case XMLEvent.START_ELEMENT:
//On the occurrence of a key element it checks if there was a graph element before, if yes, invalidity -> exception
if(Tokens.KEY.equals(reader.getLocalName()) && oldElement != null) {
if(Tokens.GRAPH.equals(oldElement))
throw new DataIOException("Element KEY is not expected.");
}
//save the current XML tag name for the key/graph validity check
oldElement = reader.getLocalName();
//save the current ID of the element as long as it is not null
if(reader.getAttributeValue(null, Tokens.ID) != null)
lastID = reader.getAttributeValue(null, Tokens.ID);
//Check if a node is a root element or if an edge refers to a root element
if(ROOT.equals(lastID) || ROOT.equals(reader.getAttributeValue(null, Tokens.TARGET))) {
if(Tokens.EDGE.equals(reader.getLocalName())){
//Adds the ID of the nodes referenced to root
long rootID = Long.parseLong(reader.getAttributeValue(0).substring(1), 10);
rootList.add(rootID);
}
}
//Read the data columns from the key elements
else if(Tokens.KEY.equals(reader.getLocalName()))
configReader(reader, edgeCache, attributeIdToName);
//add the ID to the hashMap
else if(Tokens.NODE.equals(reader.getLocalName()))
dataMap.put(TemporalElement.ID, lastID);
//get the key for the value of the next hashMap data
else if(Tokens.DATA.equals(reader.getLocalName()) && reader.getAttributeValue(null, Tokens.KEY) != null)
nextFieldName = reader.getAttributeValue(null, Tokens.KEY);
//add an Edge to the EdgeList
else if(Tokens.EDGE.equals(reader.getLocalName()))
parseEdge(reader, edgeCache, attributeIdToName);
//Check graph direction and number of graphs, throw exception on invadility
else if(Tokens.GRAPH.equals(reader.getLocalName())) {
if(! GRAPH_DIRECTED.equals(reader.getAttributeValue(null, Tokens.EDGEDEF)))
throw new DataIOException("Graph is not directed. (At the moment only edgedefault is supported.)");
// edgedefault = true;
if(graphCounter > 0) {
throw new DataIOException("Unexpected graph element detected.");
}
graphCounter++;
}
break; // START_ELEMENT
//Value saved to the HashMap to later add it as a bulk
case XMLEvent.CHARACTERS:
// TODO check the StAX API if it is possible that an element content is more than one character events -> concatenate, no overwrite
// StAX does not see the second set of characters of data split by another tag as a CHARACTERS event. Therefore I see no possibility to achieve this so far.
if(nextFieldName != null){
//Removal of the prefix for TemporalElements "_"
if(nextFieldName.startsWith(TEMP_ELEMENT_ATTR_PREFIX))
dataMap.put(nextFieldName.split(TEMP_ELEMENT_ATTR_PREFIX)[1], reader.getText());
else
dataMap.put(nextFieldName, reader.getText());
nextFieldName = null;
}
break; // CHARACTERS
//When the element ends, call the appropriate method to add it to the TemporalDataset
case XMLEvent.END_ELEMENT:
if(Tokens.NODE.equals(reader.getLocalName()) && !(ROOT.equals(lastID))){
//decides per prefix if TemporalElement or TemporalObject
if (NodeType.ELEMENT == NodeType.byPrefix(lastID)) {
createTemporalElement(dataMap);
dataMap.clear();
}
else if (NodeType.OBJECT == NodeType.byPrefix(lastID)) {
createTemporalObject(dataMap);
dataMap.clear();
}
}
if(Tokens.GRAPH.equals(reader.getLocalName()))
oldElement = Tokens.GRAPH;
break; // END_ELEMENT
//When the file ends, the edges are created and the latest compatibility checks are being made
case XMLEvent.END_DOCUMENT:
createEdges(edgeCache, rootList); //add the edges to the TemporalDataset
checkTemporalObjects(); //Check if every TemporalObject has a TemporalElement it belongs to
break; // END_DOCUMENT
default:
break;
}
}
}
/**
* reads XML content until the edge element ends and adds it to the cache.
* @param reader
* @param edgeCache
* @throws XMLStreamException
* @throws DataIOException
*/
private void parseEdge(XMLStreamReader reader, Table edgeCache,
HashMap<String, String> attributeIdToName)
throws XMLStreamException, DataIOException {
// parse source and target from attributes -> cache
Tuple edge = edgeCache.getTuple(edgeCache.addRow());
edge.set(EDGE_SOURCE, reader.getAttributeValue(null, Tokens.SOURCE));
edge.set(EDGE_TARGET, reader.getAttributeValue(null, Tokens.TARGET));
while (reader.hasNext()) {
switch (reader.next()) {
case XMLEvent.START_ELEMENT:
if (Tokens.DATA.equals(reader.getLocalName())) {
parseData(reader, edge, attributeIdToName);
}
break;
case XMLEvent.END_ELEMENT:
if (Tokens.EDGE.equals(reader.getLocalName())) {
// edge parsing complete
return;
}
}
}
throw new IllegalStateException(
"GraphML document ended prematurely in <edge>.");
}
private void parseData(XMLStreamReader reader, Tuple tuple,
HashMap<String, String> attributeIdToName)
throws XMLStreamException, DataIOException {
// we assume that reader is on a <data> element
String key = reader.getAttributeValue(null, Tokens.KEY);
if (key == null) {
throw new DataIOException("<data> element without key.");
}
// build string from possibly multiple characters events
StringBuilder value = new StringBuilder();
// keep track of nested elements
int depth = 0;
while (reader.hasNext()) {
switch (reader.next()) {
case XMLEvent.CHARACTERS:
if (depth == 0) {
value.append(reader.getText());
}
break;
case XMLEvent.START_ELEMENT:
depth++;
break;
case XMLEvent.END_ELEMENT:
if (depth == 0 && Tokens.DATA.equals(reader.getLocalName())) {
// <data> parsing complete
String attName = attributeIdToName.get(key);
if (tuple.getColumnIndex(attName) >= 0) {
tuple.setString(attName, value.toString());
} else {
throw new DataIOException("Unknown attribute key "
+ key + " with value " + value.toString());
}
return;
} else {
depth
}
}
}
throw new DataIOException(
"GraphML document ended prematurely in <data>.");
}
/**
* Determines the content of a key element and configures the TemporalDataset accordingly.
* Returns the Number of elements defined for a TemporalElement.
*
* @param reader
* @throws XMLStreamException
* @throws FactoryConfigurationError
* @throws IOException
* @throws TemporalDataException
*/
private void configReader(XMLStreamReader reader, Table edgeCache, HashMap<String, String> attributeIdToName) throws XMLStreamException, FactoryConfigurationError, IOException, TemporalDataException
{
final String attId = reader.getAttributeValue(null, Tokens.ID);
final String attName = reader.getAttributeValue(null, Tokens.ATTRNAME);
final String attFor = reader.getAttributeValue(null, Tokens.FOR);
final String attType = reader.getAttributeValue(null, Tokens.ATTRTYPE);
if (Logger.getLogger(this.getClass()).isDebugEnabled()) {
Logger.getLogger(this.getClass()).debug(
"consider KEY for " + attFor + " column: " + attName);
}
// ignore GraphML attributes with a reserved name (e.g. TemporalElement schema) since they are known
if(! attId.startsWith(TEMP_ELEMENT_ATTR_PREFIX)) {
@SuppressWarnings("rawtypes")
Class type = null;
//get the defined data type as class object
if(Tokens.STRING.equals(attType))
type = String.class;
else if(Tokens.INT.equals(attType))
type = int.class;
else if(Tokens.LONG.equals(attType))
type = long.class;
else if(Tokens.DOUBLE.equals(attType))
type = double.class;
else if(Tokens.FLOAT.equals(attType))
type = float.class;
else if(Tokens.BOOLEAN.equals(attType))
type = boolean.class;
//generate a new column for edges in the TemporalDataset
if (Tokens.EDGE.equals(attFor) || Tokens.ALL.equals(attFor)) {
tds.getEdgeTable().addColumn(attName, type, null);
edgeCache.addColumn(attName, String.class, null);
}
//generate a new data column for the TemporalDataset
if (Tokens.NODE.equals(attFor) || Tokens.ALL.equals(attFor)) {
tds.addDataColumn(reader.getAttributeValue(null, Tokens.ATTRNAME), type, null);
}
// keep track of attribute ids
attributeIdToName.put(attId, attName);
}
}
/**
* Creates a TemporalElement with the Data given in the HashMap.
* @param dataMap
*/
private void createTemporalElement(HashMap<String, String> dataMap)
{
//Get all the know attributes of a TemporalElement
int id = Integer.parseInt(dataMap.get(TemporalElement.ID).split(GraphMLTemporalDatasetWriter.ELEMENT_PREFIX)[1]);
long inf = Long.parseLong(dataMap.get(TemporalElement.INF), 10);
long sup = Long.parseLong(dataMap.get(TemporalElement.SUP), 10);
int granularityID = Integer.parseInt(dataMap.get(TemporalElement.GRANULARITY_ID));
int granularityContextID = Integer.parseInt(dataMap.get(TemporalElement.GRANULARITY_CONTEXT_ID));
int kind = Integer.parseInt(dataMap.get(TemporalElement.KIND));
//add a new TemporalElement to the TemporalDataset with these values
tds.addTemporalElement(id, inf, sup, granularityID, granularityContextID, kind);
}
/**
* Creates a TemporalObject with the Data given in the HashMap.
* @param dataMap
*/
private void createTemporalObject(HashMap<String, String> dataMap)
{
String currentCol = null;
@SuppressWarnings("rawtypes")
Class currentType = null;
//Needs to be added as a node since the TemporalObject constructor needs the TemporalElement ID (information in edges)
Node node = tds.addNode();
node.set(TemporalObject.ID, Integer.parseInt(dataMap.get(TemporalElement.ID).substring(1)));
//for the amount of dataColumns in the TemporalDataset, set all their values
for (int j = 0; j < tds.getDataColumnSchema().getColumnCount(); j++) {
currentCol = tds.getDataColumnSchema().getColumnName(j); //gets the current column name via the index
currentType = tds.getDataColumnSchema().getColumnType(j); //gets the current column type via the index
String value = dataMap.get(currentCol); //get the current value from the hashMap via the column name
// TODO check if missing -> future work/not necessary now
//Convert the value to the type defined for the column
if(String.class.equals(currentType))
node.set(currentCol, value);
else if(int.class.equals(currentType))
node.set(currentCol, Integer.parseInt(value));
else if(double.class.equals(currentType))
node.set(currentCol, Double.parseDouble(value));
else if(long.class.equals(currentType)) {
if(value.endsWith("L")) // TL not sure is this is allowed for GraphML, but "best practice" is being lenient
value = value.substring(0, value.length()-1);
node.setLong(currentCol, Long.parseLong(value));
}
else if(float.class.equals(currentType))
node.set(currentCol, Float.parseFloat(value));
else if(boolean.class.equals(currentType))
node.set(currentCol, Boolean.valueOf(value));
}
}
/**
* Adds the Edges from the edgeList to the TemporalDataset. (Use only after adding nodes!)
* @param edgeList
* @throws DataIOException
*/
private void createEdges(Table edgeCache, ArrayList<Long> rootList) throws DataIOException
{
IntIterator edgeRows = edgeCache.rows();
while (edgeRows.hasNext()) {
Tuple edge = edgeCache.getTuple(edgeRows.nextInt());
// extract types and TimeBench id from GraphML node id
NodeType sType = NodeType.byPrefix(edge.getString(EDGE_SOURCE));
NodeType tType = NodeType.byPrefix(edge.getString(EDGE_TARGET));
long sId = Long.parseLong(edge.getString(EDGE_SOURCE).substring(1));
long tId = Long.parseLong(edge.getString(EDGE_TARGET).substring(1));
// Relationships between mutual types of nodes
if (sType == tType) {
if (NodeType.ELEMENT.equals(sType)) {
Node source = tds.getTemporalElement(sId);
Node target = tds.getTemporalElement(tId);
tds.getTemporalElements().addEdge(source, target);
} else if (NodeType.OBJECT.equals(sType)) {
Node source = tds.getTemporalObject(sId);
Node target = tds.getTemporalObject(tId);
Edge tdEdge = tds.addEdge(source, target);
// the fields 0 and 1 contain source and target
// the other fields contain domain data
for (int i = 2; i < edge.getColumnCount(); i++) {
// XXX here we trust the string parsing to prefuse
tdEdge.set(edge.getColumnName(i), edge.getString(i));
}
} else {
throw new DataIOException(
"Unappropriate node ids in edge: "
+ edge.getString(EDGE_SOURCE) + ", "
+ edge.getString(EDGE_TARGET));
}
// TemporalElements needed for the TemporalObject
} else if (NodeType.OBJECT.equals(sType)
&& NodeType.ELEMENT.equals(tType)) {
// get the object via the source ID and set the element ID
Node node = tds.getTemporalObject(sId);
node.set(TemporalObject.TEMPORAL_ELEMENT_ID, tId);
} else {
throw new DataIOException("Unappropriate node ids in edge: "
+ edge.getString(EDGE_SOURCE) + ", "
+ edge.getString(EDGE_TARGET));
}
}
//adds the root elements to the TemporalDataset by first converting it to an array based on the ArrayList's length
// TODO consider different data structure in TemporalDataset -> AR
long[] roots = new long[rootList.size()];
for(int i = 0; i < rootList.size(); i++)
roots[i] = rootList.get(i);
tds.setRoots(roots);
}
/**
* Checks if all the TemporalObject of an TemporalDataset have a
* TemporalElement. If not, it throws the TemporalDataException.
*
* @throws TemporalDataException
*/
private void checkTemporalObjects() throws TemporalDataException {
for (TemporalObject to : tds.temporalObjects()) {
if (to.getTemporalElement() == null) {
throw new TemporalDataException(
"TemporalObject without a TemporalElement: "
+ to.getId());
}
}
}
enum NodeType {
OBJECT, ELEMENT;
/**
* determines the type of a node by the prefix of its id.
*
* @param prefix
* node id starting with the prefix (e.g., "o2") or only the
* prefix ("t").
* @return the NodeType or <tt>null</tt>
*/
static NodeType byPrefix(String prefix) {
if (prefix == null)
return null;
if (prefix.startsWith(GraphMLTemporalDatasetWriter.ELEMENT_PREFIX))
return ELEMENT;
if (prefix.startsWith(GraphMLTemporalDatasetWriter.OBJECT_PREFIX))
return OBJECT;
else
return null;
}
}
private Table prepareEdgeCache() {
Table cache = new Table();
cache.addColumn(EDGE_SOURCE, String.class);
cache.addColumn(EDGE_TARGET, String.class);
return cache;
}
/**
* Edge object for handling Edge-related data from a GraphML file in an easy
* way.
*
* @author Sascha Plessberger, Alexander Rind
*
*/
class MyEdge {
private NodeType sourceType;
private NodeType targetType;
private long sourceId;
private long targetId;
/**
* Constructor
*
* @param source
* @param target
*/
public MyEdge(String source, String target) {
this.sourceType = NodeType.byPrefix(source);
this.targetType = NodeType.byPrefix(target);
sourceId = Long.parseLong(source.substring(1), 10);
targetId = Long.parseLong(target.substring(1), 10);
}
/**
* Returns the type of the starting point of an edge.
*
* @return
*/
public NodeType getSourceType() {
return sourceType;
}
/**
* Returns the type of the ending point of an edge.
*
* @return
*/
public NodeType getTargetType() {
return targetType;
}
/**
* Returns the Source ID as a long.
*
* @return
*/
public long getSourceId() {
return sourceId;
}
/**
* Returns the Target ID as a long.
*
* @return
*/
public long getTargetId() {
return targetId;
}
}
} |
package de.cooperateproject.modeling.transformation.transformations.tests.transforms.plain;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.gmf.runtime.notation.Shape;
import org.eclipse.m2m.qvt.oml.ModelExtent;
import org.eclipse.m2m.qvt.oml.util.Trace;
import org.junit.Test;
import de.cooperateproject.modeling.textual.cls.cls.ClassDiagram;
import de.cooperateproject.modeling.textual.cls.cls.ClsPackage;
public class GraphicalToTextualClassTest extends DirectionalTransformationTestBase {
private static final URI TRANSFORMATION_URI = createTransformationURI("Graphical_to_Textual_for_Class.qvto");
static {
ClsPackage.eINSTANCE.eClass();
}
public GraphicalToTextualClassTest() {
super(TRANSFORMATION_URI, "notation", "xmi");
}
@Test
public void testWithoutPackages() throws Exception {
testRegular("ClassDiagram");
}
@Test
public void testWithoutPackagesIncremental() throws Exception {
testIncremental("ClassDiagram");
}
@Test
public void testPackages() throws Exception {
testRegular("ClassDiagramPackages");
}
@Test
public void testPackagesIncremental() throws Exception {
testIncremental("ClassDiagramPackages");
}
@Test
public void testSelfReference() throws Exception {
testRegular("ClassDiagramSelfReference");
}
@Test
public void testSelfReferenceIncremental() throws Exception {
testIncremental("ClassDiagramSelfReference");
}
@Test
public void testDeleteClass() throws Exception {
URI sourceModelURI = createResourceModelURI("ClassDiagramSingleClass.notation");
URI umlModelURI = createResourceModelURI("ClassDiagramSingleClass.uml");
// first transformation
Trace transformationTrace = new Trace(Collections.emptyList());
ModelExtent transformationResult = runTransformation(TRANSFORMATION_URI, sourceModelURI, umlModelURI,
transformationTrace);
// delete class from graphical model
Resource notationResource = getResourceSet().getResource(sourceModelURI, false);
Shape umlClassShape = ((Shape) ((Diagram) notationResource.getContents().get(0)).getChildren().get(0));
org.eclipse.uml2.uml.Class umlClass = (org.eclipse.uml2.uml.Class) umlClassShape.getElement();
EcoreUtil.remove(umlClassShape);
EcoreUtil.remove(umlClass);
ClassDiagram textualDiagram = (ClassDiagram) transformationResult.getContents().get(0);
textualDiagram.getRootPackage().getClassifiers().get(0)
.eUnset(ClsPackage.Literals.UML_REFERENCING_ELEMENT__REFERENCED_ELEMENT);
// second transformation (incremental)
transformationResult = runTransformation(TRANSFORMATION_URI, sourceModelURI, umlModelURI, transformationResult,
transformationTrace);
assertEquals(0, textualDiagram.getRootPackage().getClassifiers().size());
}
} |
package fr.openwide.core.wicket.more.markup.html.template.js.jquery.plugins.bootstrap.popover;
import org.apache.wicket.Component;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.odlabs.wiquery.core.javascript.JsStatement;
public class BootstrapPopoverBehavior extends Behavior {
private static final long serialVersionUID = -4381194681563091269L;
private static final String BOOTSTRAP_POPOVER = "popover";
private BootstrapPopoverOptions options;
public BootstrapPopoverBehavior(BootstrapPopoverOptions options) {
super();
this.options = options;
}
public JsStatement statement(Component component) {
return new JsStatement().$(component).chain(BOOTSTRAP_POPOVER, options.getJavaScriptOptions(component));
}
@Override
public void renderHead(Component component, IHeaderResponse response) {
response.render(JavaScriptHeaderItem.forReference(BootstrapPopoverJavascriptResourceReference.get()));
response.render(OnDomReadyHeaderItem.forScript(statement(component).render()));
}
@Override
public void detach(Component component) {
super.detach(component);
if (options != null) {
options.detach();
}
}
} |
package org.animotron.graph.builder;
import org.animotron.AbstractExpression;
import org.animotron.Expression;
import org.animotron.Properties;
import org.animotron.exception.AnimoException;
import org.animotron.graph.GraphOperation;
import org.animotron.statement.relation.IS;
import org.animotron.utils.MessageDigester;
import org.neo4j.graphdb.Relationship;
import java.io.*;
import java.security.MessageDigest;
import java.util.UUID;
import java.util.regex.Pattern;
import static org.animotron.graph.AnimoGraph.getStorage;
/**
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
* @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a>
*
*/
public class BinaryBuilder extends AbstractExpression {
private final static File BIN_STORAGE = new File(getStorage(), "binany");
private final static File TMP_STORAGE = new File(getStorage(), "tmp");
static {
BIN_STORAGE.mkdirs();
TMP_STORAGE.mkdirs();
}
private static File getFolder(String hash) {
return new File(new File(BIN_STORAGE, hash.substring(0, 2)), hash.substring(0, 4));
}
private static File getFile(File folder, String hash){
return new File(folder, hash);
}
public static File getFile(String hash){
return new File(getFolder(hash), hash);
}
public BinaryBuilder (InputStream stream, String path) throws IOException, AnimoException {
String txID = UUID.randomUUID().toString();
File tmp = new File(TMP_STORAGE, txID);
tmp.createNewFile();
OutputStream out = new FileOutputStream(tmp);
byte buf[] = new byte[1024 * 4];
int len;
MessageDigest md = MessageDigester.md();
while((len=stream.read(buf))>0) {
out.write(buf,0,len);
md.update(buf,0,len);
}
out.close();
stream.close();
String hash = MessageDigester.byteArrayToHex(md.digest());
File dir = getFolder(hash);
File bin = getFile(dir, hash);
if (bin.exists()) {
tmp.delete();
System.out.println("File \"" + bin.getPath() + "\" already stored");
} else {
dir.mkdirs();
if (!tmp.renameTo(bin)) {
tmp.delete();
throw new IOException("transaction can not be finished");
} else {
startGraph();
start(IS._, "file");
end();
String[] parts = path.split(Pattern.quote(File.separator));
Expression prev = null;
for (String part : parts) {
if (!part.isEmpty()) {
start(IS._, part);
end();
}
}
// Expression prev = null;
// for (String part : parts) {
// if (!part.isEmpty()) {
// if (prev == null) {
// prev = new Expression(
// _(IS._, part)
// } else {
// prev = new Expression(
// _(IS._, THE._.name(prev)),
// _(IS._, part)
// if (prev != null) {
// start(IS._, THE._.name(prev));
// end();
endGraph(new SetBinHash(this, hash));
if (!successful()) {
tmp.delete();
}
}
System.out.println("Store the file \"" + bin.getPath() + "\"");
}
}
private class SetBinHash implements GraphOperation<Void> {
private Relationship r;
private String hash;
public SetBinHash(Relationship r, String hash){
this.hash = hash;
this.r = r;
}
@Override
public Void execute() {
Properties.BIN.set(r.getEndNode(), hash);
return null;
}
}
} |
package org.asciidoc.intellij.ui;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.ValidationInfo;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.BufferedReader;
import java.io.CharArrayReader;
import java.io.IOException;
public class PasteTableDialog extends DialogWrapper {
private com.intellij.openapi.diagnostic.Logger log =
com.intellij.openapi.diagnostic.Logger.getInstance(PasteTableDialog.class);
private ComboBox separatorSelector = new ComboBox<>(new String[]{"tab", ",", ";", "space"});
@Nullable
private String data;
private String separator;
private JLabel expectedTableSizeLabel = new JLabel();
private JCheckBox firstLineHeaderCheckbox = new JCheckBox();
public PasteTableDialog() {
super(false);
setTitle("Paste Table");
setResizable(false);
separatorSelector.setEditable(true);
init();
}
@Nullable
@Override
protected JComponent createCenterPanel() {
JPanel panel = new JPanel(new GridLayout(4, 0));
JLabel explanation = new JLabel("<html><body>Use this dialog to parse data from your clipboard<br>and paste it as a table in the document.<body><html>");
panel.add(explanation);
JPanel firstLineHeaderPanel = new JPanel(new BorderLayout());
firstLineHeaderPanel.add(new JLabel("First line in the clipboard are headers:"), BorderLayout.LINE_START);
firstLineHeaderPanel.add(new JPanel(), BorderLayout.CENTER);
firstLineHeaderPanel.add(firstLineHeaderCheckbox, BorderLayout.LINE_END);
panel.add(firstLineHeaderPanel);
JPanel pasteTableSeparator = new JPanel(new BorderLayout());
pasteTableSeparator.add(new JLabel("Separator:"), BorderLayout.LINE_START);
pasteTableSeparator.add(new JPanel(), BorderLayout.CENTER);
pasteTableSeparator.add(separatorSelector, BorderLayout.LINE_END);
panel.add(pasteTableSeparator);
JPanel result = new JPanel(new BorderLayout());
result.add(new JLabel("Expected Table size:"), BorderLayout.LINE_START);
result.add(new JPanel(), BorderLayout.CENTER);
result.add(expectedTableSizeLabel, BorderLayout.LINE_END);
panel.add(result);
return panel;
}
@Override
protected boolean postponeValidation() {
return false;
}
@Nullable
@Override
protected ValidationInfo doValidate() {
// reset data first in case the result can't be parsed or no separator given
data = null;
String sep = (String) separatorSelector.getSelectedItem();
if (sep == null) {
sep = "";
}
if (sep.equals("tab")) {
separator = "\t";
} else if (sep.equals("space")) {
separator = " ";
} else {
separator = sep;
}
if (separator.length() > 0) {
try {
data = (String) Toolkit.getDefaultToolkit()
.getSystemClipboard().getData(DataFlavor.stringFlavor);
BufferedReader br = new BufferedReader(new CharArrayReader(data.toCharArray()));
long lines = br.lines().count();
br = new BufferedReader(new CharArrayReader(data.toCharArray()));
int max = br.lines().mapToInt(line -> StringUtils.countMatches(line, separator)).max().orElse(0);
expectedTableSizeLabel.setText(max + 1 + " x " + lines);
} catch (UnsupportedFlavorException | IOException e) {
log.info("unable to parse clipboard (no text found)", e);
expectedTableSizeLabel.setText("");
return new ValidationInfo("Unable to parse clipboard (no text found)");
}
} else {
expectedTableSizeLabel.setText("");
return new ValidationInfo("Please select separator", separatorSelector);
}
return super.doValidate();
}
@Nullable
public String getData() {
return data;
}
public String getSeparator() {
return separator;
}
public boolean isFirstLineHeader() {
return firstLineHeaderCheckbox.isSelected();
}
} |
package com.bitdubai.fermat_bch_plugin.layer.asset_vault.developer.bitdubai.version_1.structure;
import com.bitdubai.fermat_api.layer.dmp_world.Agent;
import com.bitdubai.fermat_api.layer.dmp_world.wallet.exceptions.CantStartAgentException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.PluginDatabaseSystem;
import com.bitdubai.fermat_bch_api.layer.crypto_network.bitcoin.interfaces.BitcoinNetworkManager;
class VaultKeyHierarchyMaintainer implements Agent {
/**
* controller of the agent execution thread
*/
boolean isSupposedToRun;
/**
* The vault complete key hierarchy
*/
private VaultKeyHierarchy vaultKeyHierarchy;
/**
* platform services variables
*/
PluginDatabaseSystem pluginDatabaseSystem;
BitcoinNetworkManager bitcoinNetworkManager;
/**
* Constructor
* @param vaultKeyHierarchy
* @param pluginDatabaseSystem
*/
public VaultKeyHierarchyMaintainer(VaultKeyHierarchy vaultKeyHierarchy, PluginDatabaseSystem pluginDatabaseSystem, BitcoinNetworkManager bitcoinNetworkManager) {
this.vaultKeyHierarchy = vaultKeyHierarchy;
this.pluginDatabaseSystem = pluginDatabaseSystem;
this.bitcoinNetworkManager = bitcoinNetworkManager;
}
@Override
public void start() throws CantStartAgentException {
isSupposedToRun = true;
Thread agentThread = new Thread(new VaultKeyHierarchyMaintainerAgent());
agentThread.start();
}
@Override
public void stop() {
isSupposedToRun = false;
}
private class VaultKeyHierarchyMaintainerAgent implements Runnable{
/**
* Sleep time of the agent between iterations
*/
final long AGENT_SLEEP_TIME = 10000;
@Override
public void run() {
while (isSupposedToRun){
doTheMainTask();
try {
Thread.sleep(AGENT_SLEEP_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void doTheMainTask(){
}
}
} |
package org.bibliome.util.pubmed;
import java.io.StringWriter;
import java.util.Collections;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.KeywordAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Field;
import org.bibliome.util.xml.XMLUtils;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public enum PubMedIndexField {
PMID("pmid", "/PubmedArticle/MedlineCitation/PMID") {
@Override
protected void addFields(org.apache.lucene.document.Document luceneDoc, Document doc, String source, Map<String,String> meshPaths) throws XPathExpressionException {
String pmid = XMLUtils.evaluateString(xPath, doc);
addField(luceneDoc, pmid);
}
@Override
protected Analyzer getAnalyzer() {
return new KeywordAnalyzer();
}
@Override
public boolean isIndexed() {
return true;
}
@Override
public boolean isStored() {
return true;
}
},
DOI("doi", "/PubmedArticle/PubmedData/ArticleIdList/ArticleId[@IdType = 'doi']") {
@Override
protected void addFields(org.apache.lucene.document.Document luceneDoc, Document doc, String source, Map<String, String> meshPaths) throws XPathExpressionException, TransformerException {
String doi = XMLUtils.evaluateString(xPath, doc);
addField(luceneDoc, doi);
}
@Override
protected Analyzer getAnalyzer() {
return new KeywordAnalyzer();
}
@Override
public boolean isIndexed() {
return true;
}
@Override
public boolean isStored() {
return true;
}
},
MESH_ID("mesh-id", "/PubmedArticle/MedlineCitation/MeshHeadingList/MeshHeading/DescriptorName") {
@Override
protected void addFields(org.apache.lucene.document.Document luceneDoc, Document doc, String source, Map<String,String> meshPaths) throws XPathExpressionException {
for (Element mesh : XMLUtils.evaluateElements(xPath, doc)) {
String meshId = mesh.getAttribute(ATTRIBUTE_MESH_ID);
addField(luceneDoc, meshId);
}
}
@Override
protected Analyzer getAnalyzer() {
return new KeywordAnalyzer();
}
@Override
public boolean isIndexed() {
return true;
}
@Override
public boolean isStored() {
return false;
}
},
MESH_PATH("mesh-path", "/PubmedArticle/MedlineCitation/MeshHeadingList/MeshHeading/DescriptorName") {
@Override
protected void addFields(org.apache.lucene.document.Document luceneDoc, Document doc, String source, Map<String,String> meshPaths) throws XPathExpressionException {
for (Element mesh : XMLUtils.evaluateElements(xPath, doc)) {
String meshId = mesh.getAttribute(ATTRIBUTE_MESH_ID);
if (meshPaths.containsKey(meshId)) {
String meshPath = meshPaths.get(meshId);
addField(luceneDoc, meshPath);
}
}
}
@Override
protected Analyzer getAnalyzer() {
return new KeywordAnalyzer();
}
@Override
public boolean isIndexed() {
return true;
}
@Override
public boolean isStored() {
return false;
}
},
TITLE("title", "/PubmedArticle/MedlineCitation/Article/ArticleTitle") {
@Override
protected void addFields(org.apache.lucene.document.Document luceneDoc, Document doc, String source, Map<String,String> meshPaths) throws XPathExpressionException {
String title = XMLUtils.evaluateString(xPath, doc);
addField(luceneDoc, title);
}
@Override
protected Analyzer getAnalyzer() {
return new StandardAnalyzer(PubMedIndexUtils.LUCENE_VERSION);
}
@Override
public boolean isIndexed() {
return true;
}
@Override
public boolean isStored() {
return false;
}
},
ABSTRACT("abstract", "/PubmedArticle/MedlineCitation/Article/Abstract/AbstractText") {
@Override
protected void addFields(org.apache.lucene.document.Document luceneDoc, Document doc, String source, Map<String,String> meshPaths) throws XPathExpressionException, DOMException {
for (Element abs : XMLUtils.evaluateElements(xPath, doc)) {
String absText = abs.getTextContent();
addField(luceneDoc, absText);
}
}
@Override
protected Analyzer getAnalyzer() {
return new StandardAnalyzer(PubMedIndexUtils.LUCENE_VERSION);
}
@Override
public boolean isIndexed() {
return true;
}
@Override
public boolean isStored() {
return false;
}
}, |
package org.bouncycastle.crypto.digests;
import org.bouncycastle.crypto.*;
/**
* implementation of MD2
* as outlined in RFC1319 by B.Kaliski from RSA Laboratories April 1992
*/
public class MD2Digest
implements ExtendedDigest
{
private static final int DIGEST_LENGTH = 16;
/* X buffer */
private byte[] X = new byte[48];
private int xOff;
/* M buffer */
private byte[] M = new byte[16];
private int mOff;
/* check sum */
private byte[] C = new byte[16];
private int COff;
public MD2Digest()
{
reset();
}
public MD2Digest(MD2Digest t)
{
System.arraycopy(t.X, 0, X, 0, t.X.length);
xOff = t.xOff;
System.arraycopy(t.M, 0, M, 0, t.M.length);
mOff = t.mOff;
System.arraycopy(t.C, 0, C, 0, t.C.length);
COff = t.COff;
}
/**
* return the algorithm name
*
* @return the algorithm name
*/
public String getAlgorithmName()
{
return "MD2";
}
/**
* return the size, in bytes, of the digest produced by this message digest.
*
* @return the size, in bytes, of the digest produced by this message digest.
*/
public int getDigestSize()
{
return DIGEST_LENGTH;
}
/**
* close the digest, producing the final digest value. The doFinal
* call leaves the digest reset.
*
* @param out the array the digest is to be copied into.
* @param outOff the offset into the out array the digest is to start at.
*/
public int doFinal(byte[] out, int outOff)
{
// add padding
byte paddingByte = (byte)(M.length-mOff);
for (int i=mOff;i<M.length;i++)
{
M[i] = paddingByte;
}
//do final check sum
processCheckSum(M);
// do final block process
processBlock(M);
processBlock(C);
System.arraycopy(X,xOff,out,outOff,16);
reset();
return DIGEST_LENGTH;
}
/**
* reset the digest back to it's initial state.
*/
public void reset()
{
xOff = 0;
for (int i = 0; i != X.length; i++)
{
X[i] = 0;
}
mOff = 0;
for (int i = 0; i != M.length; i++)
{
M[i] = 0;
}
COff = 0;
for (int i = 0; i != C.length; i++)
{
C[i] = 0;
}
}
/**
* update the message digest with a single byte.
*
* @param in the input byte to be entered.
*/
public void update(byte in)
{
M[mOff++] = in;
if (mOff == 16)
{
processCheckSum(M);
processBlock(M);
mOff = 0;
}
}
/**
* update the message digest with a block of bytes.
*
* @param in the byte array containing the data.
* @param inOff the offset into the byte array where the data starts.
* @param len the length of the data.
*/
public void update(byte[] in, int inOff, int len)
{
// fill the current word
while ((mOff != 0) && (len > 0))
{
update(in[inOff]);
inOff++;
len
}
// process whole words.
while (len > 16)
{
System.arraycopy(in,inOff,M,0,16);
processCheckSum(M);
processBlock(M);
len -= 16;
inOff += 16;
}
// load in the remainder.
while (len > 0)
{
update(in[inOff]);
inOff++;
len
}
}
protected void processCheckSum(byte[] m)
{
int L = C[15];
for (int i=0;i<16;i++)
{
C[i] ^= S[(m[i] ^ L) & 0xff];
L = C[i];
}
}
protected void processBlock(byte[] m)
{
for (int i=0;i<16;i++)
{
X[i+16] = m[i];
X[i+32] = (byte)(m[i] ^ X[i]);
}
// encrypt block
int t = 0;
for (int j=0;j<18;j++)
{
for (int k=0;k<48;k++)
{
t = X[k] ^= S[t];
t = t & 0xff;
}
t = (t + j)%256;
}
}
// 256-byte random permutation constructed from the digits of PI
private static final byte[] S = {
(byte)41,(byte)46,(byte)67,(byte)201,(byte)162,(byte)216,(byte)124,
(byte)1,(byte)61,(byte)54,(byte)84,(byte)161,(byte)236,(byte)240,
(byte)6,(byte)19,(byte)98,(byte)167,(byte)5,(byte)243,(byte)192,
(byte)199,(byte)115,(byte)140,(byte)152,(byte)147,(byte)43,(byte)217,
(byte)188,(byte)76,(byte)130,(byte)202,(byte)30,(byte)155,(byte)87,
(byte)60,(byte)253,(byte)212,(byte)224,(byte)22,(byte)103,(byte)66,
(byte)111,(byte)24,(byte)138,(byte)23,(byte)229,(byte)18,(byte)190,
(byte)78,(byte)196,(byte)214,(byte)218,(byte)158,(byte)222,(byte)73,
(byte)160,(byte)251,(byte)245,(byte)142,(byte)187,(byte)47,(byte)238,
(byte)122,(byte)169,(byte)104,(byte)121,(byte)145,(byte)21,(byte)178,
(byte)7,(byte)63,(byte)148,(byte)194,(byte)16,(byte)137,(byte)11,
(byte)34,(byte)95,(byte)33,(byte)128,(byte)127,(byte)93,(byte)154,
(byte)90,(byte)144,(byte)50,(byte)39,(byte)53,(byte)62,(byte)204,
(byte)231,(byte)191,(byte)247,(byte)151,(byte)3,(byte)255,(byte)25,
(byte)48,(byte)179,(byte)72,(byte)165,(byte)181,(byte)209,(byte)215,
(byte)94,(byte)146,(byte)42,(byte)172,(byte)86,(byte)170,(byte)198,
(byte)79,(byte)184,(byte)56,(byte)210,(byte)150,(byte)164,(byte)125,
(byte)182,(byte)118,(byte)252,(byte)107,(byte)226,(byte)156,(byte)116,
(byte)4,(byte)241,(byte)69,(byte)157,(byte)112,(byte)89,(byte)100,
(byte)113,(byte)135,(byte)32,(byte)134,(byte)91,(byte)207,(byte)101,
(byte)230,(byte)45,(byte)168,(byte)2,(byte)27,(byte)96,(byte)37,
(byte)173,(byte)174,(byte)176,(byte)185,(byte)246,(byte)28,(byte)70,
(byte)97,(byte)105,(byte)52,(byte)64,(byte)126,(byte)15,(byte)85,
(byte)71,(byte)163,(byte)35,(byte)221,(byte)81,(byte)175,(byte)58,
(byte)195,(byte)92,(byte)249,(byte)206,(byte)186,(byte)197,(byte)234,
(byte)38,(byte)44,(byte)83,(byte)13,(byte)110,(byte)133,(byte)40,
(byte)132, 9,(byte)211,(byte)223,(byte)205,(byte)244,(byte)65,
(byte)129,(byte)77,(byte)82,(byte)106,(byte)220,(byte)55,(byte)200,
(byte)108,(byte)193,(byte)171,(byte)250,(byte)36,(byte)225,(byte)123,
(byte)8,(byte)12,(byte)189,(byte)177,(byte)74,(byte)120,(byte)136,
(byte)149,(byte)139,(byte)227,(byte)99,(byte)232,(byte)109,(byte)233,
(byte)203,(byte)213,(byte)254,(byte)59,(byte)0,(byte)29,(byte)57,
(byte)242,(byte)239,(byte)183,(byte)14,(byte)102,(byte)88,(byte)208,
(byte)228,(byte)166,(byte)119,(byte)114,(byte)248,(byte)235,(byte)117,
(byte)75,(byte)10,(byte)49,(byte)68,(byte)80,(byte)180,(byte)143,
(byte)237,(byte)31,(byte)26,(byte)219,(byte)153,(byte)141,(byte)51,
(byte)159,(byte)17,(byte)131,(byte)20
};
public int getByteLength()
{
return 16;
}
} |
package com.bitdubai.fermat_dmp_plugin.layer.middleware.wallet_factory.developer.bitdubai.version_1;
import com.bitdubai.fermat_api.CantStartPluginException;
import com.bitdubai.fermat_api.FermatException;
import com.bitdubai.fermat_api.Plugin;
import com.bitdubai.fermat_api.Service;
import com.bitdubai.fermat_api.layer.all_definition.crypto.asymmetric.interfaces.PublicKey;
import com.bitdubai.fermat_api.layer.all_definition.developer.DatabaseManagerForDevelopers;
import com.bitdubai.fermat_api.layer.all_definition.developer.DeveloperDatabase;
import com.bitdubai.fermat_api.layer.all_definition.developer.DeveloperDatabaseTable;
import com.bitdubai.fermat_api.layer.all_definition.developer.DeveloperDatabaseTableRecord;
import com.bitdubai.fermat_api.layer.all_definition.developer.DeveloperObjectFactory;
import com.bitdubai.fermat_api.layer.all_definition.developer.LogManagerForDevelopers;
import com.bitdubai.fermat_api.layer.all_definition.enums.Languages;
import com.bitdubai.fermat_api.layer.all_definition.enums.Plugins;
import com.bitdubai.fermat_api.layer.all_definition.enums.ServiceStatus;
import com.bitdubai.fermat_api.layer.all_definition.enums.WalletCategory;
import com.bitdubai.fermat_api.layer.all_definition.enums.WalletType;
import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.WalletNavigationStructure;
import com.bitdubai.fermat_api.layer.all_definition.resources_structure.Skin;
import com.bitdubai.fermat_api.layer.all_definition.resources_structure.enums.ScreenSize;
import com.bitdubai.fermat_api.layer.all_definition.util.Version;
import com.bitdubai.fermat_api.layer.dmp_identity.designer.exceptions.CantSingMessageException;
import com.bitdubai.fermat_api.layer.dmp_identity.designer.interfaces.DesignerIdentity;
import com.bitdubai.fermat_api.layer.dmp_identity.translator.interfaces.TranslatorIdentity;
import com.bitdubai.fermat_api.layer.dmp_middleware.wallet_factory.enums.FactoryProjectType;
import com.bitdubai.fermat_api.layer.dmp_middleware.wallet_factory.enums.WalletFactoryProjectState;
import com.bitdubai.fermat_api.layer.dmp_middleware.wallet_factory.exceptions.CantChangeProjectStateException;
import com.bitdubai.fermat_api.layer.dmp_middleware.wallet_factory.exceptions.CantCreateWalletFactoryProjectException;
import com.bitdubai.fermat_api.layer.dmp_middleware.wallet_factory.exceptions.CantDeleteWalletFactoryProjectException;
import com.bitdubai.fermat_api.layer.dmp_middleware.wallet_factory.exceptions.CantExportWalletFactoryProjectException;
import com.bitdubai.fermat_api.layer.dmp_middleware.wallet_factory.exceptions.CantGetWalletFactoryProjectException;
import com.bitdubai.fermat_api.layer.dmp_middleware.wallet_factory.exceptions.CantImportWalletFactoryProjectException;
import com.bitdubai.fermat_api.layer.dmp_middleware.wallet_factory.exceptions.CantSaveWalletFactoryProyect;
import com.bitdubai.fermat_api.layer.dmp_middleware.wallet_factory.interfaces.WalletFactoryProject;
import com.bitdubai.fermat_api.layer.dmp_middleware.wallet_factory.interfaces.WalletFactoryProjectManager;
import com.bitdubai.fermat_api.layer.dmp_network_service.wallet_store.interfaces.Language;
import com.bitdubai.fermat_api.layer.osa_android.database_system.Database;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DealsWithPluginDatabaseSystem;
import com.bitdubai.fermat_api.layer.osa_android.database_system.PluginDatabaseSystem;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantCreateDatabaseException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException;
import com.bitdubai.fermat_api.layer.osa_android.file_system.DealsWithPluginFileSystem;
import com.bitdubai.fermat_api.layer.osa_android.file_system.PluginFileSystem;
import com.bitdubai.fermat_api.layer.osa_android.logger_system.DealsWithLogger;
import com.bitdubai.fermat_api.layer.osa_android.logger_system.LogLevel;
import com.bitdubai.fermat_api.layer.osa_android.logger_system.LogManager;
import com.bitdubai.fermat_dmp_plugin.layer.middleware.wallet_factory.developer.bitdubai.version_1.database.WalletFactoryMiddlewareDatabaseConstants;
import com.bitdubai.fermat_dmp_plugin.layer.middleware.wallet_factory.developer.bitdubai.version_1.database.WalletFactoryMiddlewareDatabaseFactory;
import com.bitdubai.fermat_dmp_plugin.layer.middleware.wallet_factory.developer.bitdubai.version_1.database.WalletFactoryMiddlewareDeveloperDatabaseFactory;
import com.bitdubai.fermat_dmp_plugin.layer.middleware.wallet_factory.developer.bitdubai.version_1.structure.WalletFactoryProjectMiddlewareManager;
import com.bitdubai.fermat_dmp_plugin.layer.middleware.wallet_factory.developer.bitdubai.version_1.structure.myDesignerIdentity;
import com.bitdubai.fermat_dmp_plugin.layer.middleware.wallet_factory.developer.bitdubai.version_1.structure.myTranslatorIdentity;
import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.DealsWithErrors;
import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.ErrorManager;
import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.UnexpectedPluginExceptionSeverity;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class WalletFactoryProjectMiddlewarePluginRoot implements DatabaseManagerForDevelopers, DealsWithErrors, DealsWithLogger, DealsWithPluginDatabaseSystem, DealsWithPluginFileSystem, LogManagerForDevelopers, Plugin, Service, WalletFactoryProjectManager {
WalletFactoryProjectMiddlewareManager walletFactoryProjectMiddlewareManager;
/**
* DealsWithErrors Interface member variables.
*/
ErrorManager errorManager;
/**
* DealsWithLogger interface member variable
*/
LogManager logManager;
static Map<String, LogLevel> newLoggingLevel = new HashMap<>();
/**
* DealsWithPluginFileSystem Interface member variables.
*/
PluginDatabaseSystem pluginDatabaseSystem;
/**
* DealsWithPluginDatabaseSystem Interface member variables.
*/
PluginFileSystem pluginFileSystem;
/**
* Plugin Interface member variables.
*/
UUID pluginId;
/**
* Service Interface member variables.
*/
ServiceStatus serviceStatus = ServiceStatus.CREATED;
/**
* WalletFactoryProjectMiddlewareManager Interfaces member variables.
*/
@Override
public void start() throws CantStartPluginException {
// I created the WalletFactoryProjectMiddlewareManager object
walletFactoryProjectMiddlewareManager = new WalletFactoryProjectMiddlewareManager(this.pluginId, pluginDatabaseSystem, pluginFileSystem);
// I will create the database
try {
Database database = pluginDatabaseSystem.openDatabase(pluginId, WalletFactoryMiddlewareDatabaseConstants.DATABASE_NAME);
database.closeDatabase();
} catch (CantOpenDatabaseException | DatabaseNotFoundException e) {
try {
WalletFactoryMiddlewareDatabaseFactory databaseFactory = new WalletFactoryMiddlewareDatabaseFactory(this.pluginDatabaseSystem);
databaseFactory.createDatabase(this.pluginId, WalletFactoryMiddlewareDatabaseConstants.DATABASE_NAME);
} catch (CantCreateDatabaseException cantCreateDatabaseException) {
errorManager.reportUnexpectedPluginException(Plugins.BITDUBAI_WALLET_FACTORY_MIDDLEWARE, UnexpectedPluginExceptionSeverity.DISABLES_THIS_PLUGIN, cantCreateDatabaseException);
throw new CantStartPluginException();
} catch (Exception exception) {
throw new CantStartPluginException("Cannot start WalletFactoryMiddleware plugin.", FermatException.wrapException(exception), null, null);
}
}
this.serviceStatus = ServiceStatus.STARTED;
}
@Override
public void pause(){
this.serviceStatus = ServiceStatus.PAUSED;
}
@Override
public void resume(){
this.serviceStatus = ServiceStatus.STARTED;
}
@Override
public void stop(){
this.serviceStatus = ServiceStatus.STOPPED;
}
@Override
public ServiceStatus getStatus() {
return this.serviceStatus;
}
/**
* DatabaseManagerForDevelopers Interface Implementation
*/
/**
* DatabaseManagerForDevelopers interface implementation
* Returns the list of databases implemented on this plug in.
*/
@Override
public List<DeveloperDatabase> getDatabaseList(DeveloperObjectFactory developerObjectFactory) {
WalletFactoryMiddlewareDeveloperDatabaseFactory dbFactory = new WalletFactoryMiddlewareDeveloperDatabaseFactory(pluginDatabaseSystem, pluginId);
return dbFactory.getDatabaseList(developerObjectFactory);
}
/**
* returns the list of tables for the given database
*
* @param developerObjectFactory
* @param developerDatabase
* @return
*/
@Override
public List<DeveloperDatabaseTable> getDatabaseTableList(DeveloperObjectFactory developerObjectFactory, DeveloperDatabase developerDatabase) {
WalletFactoryMiddlewareDeveloperDatabaseFactory dbFactory = new WalletFactoryMiddlewareDeveloperDatabaseFactory(pluginDatabaseSystem, pluginId);
return dbFactory.getDatabaseTableList(developerObjectFactory);
}
/**
* returns the list of records for the passed table
*
* @param developerObjectFactory
* @param developerDatabase
* @param developerDatabaseTable
* @return
*/
@Override
public List<DeveloperDatabaseTableRecord> getDatabaseTableContent(DeveloperObjectFactory developerObjectFactory, DeveloperDatabase developerDatabase, DeveloperDatabaseTable developerDatabaseTable) {
WalletFactoryMiddlewareDeveloperDatabaseFactory dbFactory = new WalletFactoryMiddlewareDeveloperDatabaseFactory(pluginDatabaseSystem, pluginId);
List<DeveloperDatabaseTableRecord> developerDatabaseTableRecordList = null;
try {
dbFactory.initializeDatabase();
developerDatabaseTableRecordList = dbFactory.getDatabaseTableContent(developerObjectFactory, developerDatabaseTable);
} catch (Exception e) {
System.out.println("******* Error trying to get database table list for plugin Wallet Factory");
}
return developerDatabaseTableRecordList;
}
/**
* DealsWithLogger Interface implementation.
*/
@Override
public void setLogManager(LogManager logManager) {
this.logManager = logManager;
}
/**
* LogManagerForDevelopers Interface implementation.
*/
@Override
public List<String> getClassesFullPath() {
List<String> returnedClasses = new ArrayList<>();
returnedClasses.add("com.bitdubai.fermat_dmp_plugin.layer.middleware.wallet_factory.developer.bitdubai.version_1.WalletFactoryProjectMiddlewarePluginRoot");
/**
* I return the values.
*/
return returnedClasses;
}
@Override
public void setLoggingLevelPerClass(Map<String, LogLevel> newLoggingLevel) {
/**
* I will check the current values and update the LogLevel in those which is different
*/
for (Map.Entry<String, LogLevel> pluginPair : newLoggingLevel.entrySet()) {
/**
* if this path already exists in the Root.bewLoggingLevel I'll update the value, else, I will put as new
*/
if (WalletFactoryProjectMiddlewarePluginRoot.newLoggingLevel.containsKey(pluginPair.getKey())) {
WalletFactoryProjectMiddlewarePluginRoot.newLoggingLevel.remove(pluginPair.getKey());
WalletFactoryProjectMiddlewarePluginRoot.newLoggingLevel.put(pluginPair.getKey(), pluginPair.getValue());
} else {
WalletFactoryProjectMiddlewarePluginRoot.newLoggingLevel.put(pluginPair.getKey(), pluginPair.getValue());
}
}
}
/**
* DealWithErrors Interface implementation.
*/
@Override
public void setErrorManager(ErrorManager errorManager) {
this.errorManager = errorManager;
}
/**
* DealWithPluginDatabaseSystem Interface implementation.
*/
@Override
public void setPluginDatabaseSystem(PluginDatabaseSystem pluginDatabaseSystem) {
this.pluginDatabaseSystem = pluginDatabaseSystem;
}
/**
* DealWithPluginFileSystem Interface implementation.
*/
@Override
public void setPluginFileSystem(PluginFileSystem pluginFileSystem) {
this.pluginFileSystem = pluginFileSystem;
}
/**
* Plugin methods implementation.
*/
@Override
public void setId(UUID pluginId) {
this.pluginId = pluginId;
}
@Override
public WalletFactoryProject getWalletFactoryProjectByPublicKey(String publicKey) throws CantGetWalletFactoryProjectException {
return walletFactoryProjectMiddlewareManager.getWalletFactoryProject(publicKey);
}
@Override
public List<WalletFactoryProject> getWalletFactoryProjectByState(WalletFactoryProjectState walletFactoryProjectState) throws CantGetWalletFactoryProjectException {
test();
List<WalletFactoryProject> projects = walletFactoryProjectMiddlewareManager.getWalletFactoryProjectsByState(walletFactoryProjectState);
return projects;
}
@Override
public List<WalletFactoryProject> getAllWalletFactoryProjects() throws CantGetWalletFactoryProjectException {
return walletFactoryProjectMiddlewareManager.getAllFactoryProjects();
}
/**
* Creates and (almost) empty project and persists it.
* @return
* @throws CantCreateWalletFactoryProjectException
*/
@Override
public WalletFactoryProject createEmptyWalletFactoryProject() throws CantCreateWalletFactoryProjectException {
return walletFactoryProjectMiddlewareManager.getNewWalletFactoryProject();
}
/**
* Persists in disk and database all changes in the project
* @param walletFactoryProject
* @throws CantSaveWalletFactoryProyect
*/
@Override
public void saveWalletFactoryProjectChanges(WalletFactoryProject walletFactoryProject) throws CantSaveWalletFactoryProyect {
try {
walletFactoryProjectMiddlewareManager.saveWalletFactoryProject(walletFactoryProject);
} catch (Exception exception) {
throw new CantSaveWalletFactoryProyect(CantSaveWalletFactoryProyect.DEFAULT_MESSAGE, exception, "there was an error saving the Project information.", null);
}
}
@Override
public void deleteWalletProjectFactory(WalletFactoryProject walletFactoryProject) throws CantDeleteWalletFactoryProjectException {
}
@Override
public void uploadWalletFactoryProjectToRepository(WalletFactoryProject walletFactoryProject) throws CantSaveWalletFactoryProyect {
walletFactoryProjectMiddlewareManager.uploadWalletFactoryProjectToRepository((walletFactoryProject));
}
@Override
public void exportProjectToRepository(WalletFactoryProject walletFactoryProject, String githubRepository, String userName, String password) throws CantExportWalletFactoryProjectException {
try {
walletFactoryProjectMiddlewareManager.exportProjectToRepository(walletFactoryProject, githubRepository, userName, password);
} catch (Exception e) {
throw new CantExportWalletFactoryProjectException(CantExportWalletFactoryProjectException.DEFAULT_MESSAGE, e, null, null);
}
}
@Override
public void markProkectAsPublished(WalletFactoryProject walletFactoryProject) throws CantChangeProjectStateException {
walletFactoryProject.setProjectState(WalletFactoryProjectState.PUBLISHED);
try {
this.saveWalletFactoryProjectChanges(walletFactoryProject);
} catch (Exception e) {
throw new CantChangeProjectStateException(CantChangeProjectStateException.DEFAULT_MESSAGE, e, null, null);
}
}
private void test(){
try {
WalletFactoryProject walletFactoryProject = createEmptyWalletFactoryProject();
walletFactoryProject.setName("ProyectoPrueba");
walletFactoryProject.setWalletCategory(WalletCategory.BRANDED_REFERENCE_WALLET);
walletFactoryProject.setDescription("WFP de prueba");
walletFactoryProject.setProjectState(WalletFactoryProjectState.CLOSED);
walletFactoryProject.setFactoryProjectType(FactoryProjectType.WALLET);
walletFactoryProject.setCreationTimestamp(new Timestamp(System.currentTimeMillis()));
walletFactoryProject.setSize(300);
walletFactoryProject.setProjectPublickKey(UUID.randomUUID().toString());
walletFactoryProject.setWalletType(WalletType.REFERENCE);
Skin skin = new Skin();
skin.setId(UUID.randomUUID());
skin.setName("SkinTest");
myDesignerIdentity designerIdentity = new myDesignerIdentity();
designerIdentity.setAlias("Alias");
designerIdentity.setPublicKey(UUID.randomUUID().toString());
skin.setDesigner(designerIdentity);
skin.setScreenSize(ScreenSize.MEDIUM);
skin.setSize(100);
skin.setVersion(new Version("1.0.0"));
walletFactoryProject.setDefaultSkin(skin);
List<Skin> skins = new ArrayList<>();
skins.add(skin);
walletFactoryProject.setSkins(skins);
com.bitdubai.fermat_api.layer.all_definition.resources_structure.Language language = new com.bitdubai.fermat_api.layer.all_definition.resources_structure.Language();
language.setName("TestLanguage");
myTranslatorIdentity translatorIdentity = new myTranslatorIdentity();
translatorIdentity.setPublicKey(UUID.randomUUID().toString());
translatorIdentity.setAlias("Alias");
language.setTranslator(translatorIdentity);
language.setId(UUID.randomUUID());
language.setType(Languages.AMERICAN_ENGLISH);
language.setVersion(new Version(1, 0, 0));
language.setSize(100);
walletFactoryProject.setDefaultLanguage(language);
List<com.bitdubai.fermat_api.layer.all_definition.resources_structure.Language> languages = new ArrayList<>();
languages.add(language);
walletFactoryProject.setLanguages(languages);
walletFactoryProject.setLastModificationTimeststamp(new Timestamp(System.currentTimeMillis()));
WalletNavigationStructure navigationStructure = new WalletNavigationStructure();
navigationStructure.setPublicKey(UUID.randomUUID().toString());
navigationStructure.setSize(100);
navigationStructure.setWalletCategory("Sssd");
walletFactoryProject.setNavigationStructure(navigationStructure);
this.saveWalletFactoryProjectChanges(walletFactoryProject);
} catch (Exception e) {
e.printStackTrace();
}
}
} |
package org.broad.igv.feature.sprite;
import org.broad.igv.Globals;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.track.*;
import org.broad.igv.ui.IGV;
import org.broad.igv.ui.panel.IGVPopupMenu;
import org.broad.igv.ui.panel.ReferenceFrame;
import org.broad.igv.ui.util.MessageUtils;
import org.broad.igv.util.ResourceLocator;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import java.util.List;
public class ClusterTrack extends AbstractTrack {
int binSize;
ClusterParser.ClusterSet clusterSet;
List<Cluster> binnedClusters;
List<Cluster> wgClusters;
int rowHeight = 2;
Genome genome;
public ClusterTrack(ResourceLocator locator, ClusterParser.ClusterSet clusterSet, Genome genome) {
super(locator);
this.clusterSet = clusterSet;
this.binSize = clusterSet.binSize;
this.genome = genome;
this.binnedClusters = computeBinnedClusters(clusterSet.binSize, clusterSet.clusters, genome);
computeWGScores(this.binnedClusters, genome);
}
private List<Cluster> computeBinnedClusters(int binSize, List<Cluster> clusters, Genome genome) {
List<Cluster> binnedClusters = new ArrayList<>();
for (Cluster c : clusters) {
String name = c.name;
Map<String, List<Integer>> posMap = new HashMap<>();
for (Map.Entry<String, List<Integer>> entry : c.posMap.entrySet()) {
String chr = genome.getCanonicalChrName(entry.getKey());
Set<Integer> bins = new HashSet<>();
for (Integer pos : entry.getValue()) {
bins.add((pos / binSize) * binSize);
}
List<Integer> binList = new ArrayList<>(bins);
Collections.sort(binList);
posMap.put(chr, binList);
}
binnedClusters.add(new Cluster(name, posMap));
}
return binnedClusters;
}
public void setBinSize(int binSize) {
this.binSize = binSize;
this.binnedClusters = computeBinnedClusters(this.binSize, clusterSet.clusters, this.genome);
computeWGScores(this.binnedClusters, genome);
}
@Override
public int getHeight() {
return binnedClusters.size() * rowHeight;
}
@Override
public boolean isReadyToPaint(ReferenceFrame frame) {
return true;
}
@Override
public void load(ReferenceFrame frame) {
// Nothing to do, this track is pre-loaded
}
@Override
public void render(RenderContext context, Rectangle rect) {
String chr = context.getReferenceFrame().getChrName();
double origin = context.getOrigin();
double locScale = context.getScale();
double binSize = chr.equals(Globals.CHR_ALL) ? this.binSize / 1000 : this.binSize;
int y = 0;
for (Cluster c : binnedClusters) {
List<Integer> loci = c.posMap.get(chr);
if (loci != null) {
for (Integer position : loci) {
double pixelStart = ((position - origin) / locScale);
double pixelEnd = ((position + binSize - origin) / locScale);
// If the any part of the feature fits in the Track rectangle draw it
if (pixelEnd >= rect.getX() && pixelStart <= rect.getMaxX()) {
Color color = this.getColor();
Graphics2D g = context.getGraphic2DForColor(color);
int w = (int) (pixelEnd - pixelStart);
if (w < 3) {
w = 3;
pixelStart
}
g.fillRect((int) pixelStart, y, w, rowHeight);
}
}
y += rowHeight;
}
}
}
private void computeWGScores(List<Cluster> clusters, Genome genome) {
// Bin whole genome
int nBins = 1000;
double binSize = (genome.getTotalLength() / 1000.0) / nBins;
Set<String> wgChrNames = new HashSet<>(genome.getLongChromosomeNames());
for (Cluster cluster : clusters) {
int[] bins = new int[nBins];
List<Integer> occupiedBins = new ArrayList<>();
for (Map.Entry<String, List<Integer>> entry : cluster.posMap.entrySet()) {
String chr = entry.getKey();
if (!wgChrNames.contains(chr)) continue;
List<Integer> posList = entry.getValue();
for (Integer pos : posList) {
int genomeCoordinate = genome.getGenomeCoordinate(chr, pos);
int b = (int) (genomeCoordinate / binSize);
bins[b]++;
}
}
for (int i = 0; i < bins.length; i++) {
if (bins[i] > 0) {
occupiedBins.add((int) (i * binSize));
}
}
cluster.posMap.put(Globals.CHR_ALL, occupiedBins);
}
}
@Override
public IGVPopupMenu getPopupMenu(TrackClickEvent te) {
IGVPopupMenu menu = new IGVPopupMenu();
menu.add(TrackMenuUtils.getTrackRenameItem(Collections.singleton(ClusterTrack.this)));
final JMenuItem binSizeItem = new JMenuItem("Set Bin Size...");
binSizeItem.addActionListener(e -> {
String t = MessageUtils.showInputDialog("Bin Size", String.valueOf(ClusterTrack.this.binSize));
if (t != null) {
try {
int bs = Integer.parseInt(t);
ClusterTrack.this.setBinSize(bs);
IGV.getInstance().repaint();
} catch (NumberFormatException e1) {
MessageUtils.showErrorMessage("Bin size must be an integer", e1);
}
}
});
menu.add(binSizeItem);
final JMenuItem rowHeightItem = new JMenuItem("Set Row Height...");
rowHeightItem.addActionListener(e -> {
String t = MessageUtils.showInputDialog("Row height", String.valueOf(rowHeight));
if (t != null) {
try {
int h = Integer.parseInt(t);
rowHeight = h;
IGV.getInstance().repaint();
} catch (NumberFormatException e1) {
MessageUtils.showErrorMessage("Row height must be a number", e1);
}
}
});
menu.add(rowHeightItem);
JMenuItem item = new JMenuItem("Set Track Color...");
item.addActionListener(evt -> TrackMenuUtils.changeTrackColor(Collections.singleton(ClusterTrack.this)));
menu.add(item);
return menu;
}
@Override
public String getValueStringAt(String chr, double position, int mouseX, int mouseY, ReferenceFrame frame) {
int row = mouseY / rowHeight;
if (row < binnedClusters.size()) {
return binnedClusters.get(row).name;
} else {
return "";
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.