answer
stringlengths 17
10.2M
|
|---|
package seedu.gtd.logic.parser;
import static seedu.gtd.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.gtd.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import seedu.gtd.commons.exceptions.IllegalValueException;
import seedu.gtd.commons.util.StringUtil;
import seedu.gtd.logic.commands.*;
/**
* Parses user input.
*/
public class Parser {
//@@author addressbook-level4
/**
* Used for initial separation of command word and args.
*/
private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)");
private static final Pattern TASK_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)");
private static final Pattern KEYWORDS_ARGS_FORMAT =
Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace
// private static final Pattern TASK_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes
// Pattern.compile("(?<name>[^/]+)"
// + " d/(?<dueDate>[^/]+)"
// + " a/(?<address>[^/]+)"
// + " p/(?<priority>[^/]+)"
// + "(?<tagArguments>(?: t/[^/]+)*)"); // variable number of tags
private static final Pattern NAME_TASK_DATA_ARGS_FORMAT =
Pattern.compile("(?<name>[^/]+) (t|p|a|d|z)/.*");
private static final Pattern PRIORITY_TASK_DATA_ARGS_FORMAT =
Pattern.compile(".* p/(?<priority>[^/]+) (t|a|d|z)/.*");
private static final Pattern ADDRESS_TASK_DATA_ARGS_FORMAT =
Pattern.compile(".* a/(?<address>[^/]+) (t|p|d|z)/.*");
private static final Pattern DUEDATE_TASK_DATA_ARGS_FORMAT =
Pattern.compile(".* d/(?<dueDate>[^/]+) (t|a|p|z)/.*");
private static final Pattern TAGS_TASK_DATA_ARGS_FORMAT =
Pattern.compile(".* t/(?<tagArguments>[^/]+) (d|a|p|z)/.*");
private static final Pattern EDIT_DATA_ARGS_FORMAT =
Pattern.compile("(?<targetIndex>\\S+)"
+ " (?<newDetails>\\S+(?:\\s+\\S+)*)");
public Parser() {}
/**
* Parses user input into command for execution.
*
* @param userInput full user input string
* @return the command based on the user input
*/
public Command parseCommand(String userInput) {
final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
final String commandWord = matcher.group("commandWord");
final String arguments = matcher.group("arguments");
switch (commandWord) {
case AddCommand.COMMAND_WORD:
return prepareAdd(arguments);
case EditCommand.COMMAND_WORD:
return prepareEdit(arguments);
case SelectCommand.COMMAND_WORD:
return prepareSelect(arguments);
case DeleteCommand.COMMAND_WORD:
return prepareDelete(arguments);
case DoneCommand.COMMAND_WORD:
return prepareDone(arguments);
case ClearCommand.COMMAND_WORD:
return new ClearCommand();
case FindCommand.COMMAND_WORD:
return prepareFind(arguments);
case ListCommand.COMMAND_WORD:
return prepareList(arguments);
case ExitCommand.COMMAND_WORD:
return new ExitCommand();
case HelpCommand.COMMAND_WORD:
return prepareHelp(arguments);
case UndoCommand.COMMAND_WORD:
return new UndoCommand();
default:
return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND);
}
}
/**
* Parses arguments in the context of the add task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareAdd(String args){
String preprocessedArg = appendEnd(args.trim());
final Matcher nameMatcher = NAME_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArg);
final Matcher dueDateMatcher = DUEDATE_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArg);
final Matcher addressMatcher = ADDRESS_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArg);
final Matcher priorityMatcher = PRIORITY_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArg);
final Matcher tagsMatcher = TAGS_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArg);
String nameToAdd = checkEmptyAndAddDefault(nameMatcher, "name", "none");
String dueDateToAdd = checkEmptyAndAddDefault(dueDateMatcher, "dueDate", "none");
String addressToAdd = checkEmptyAndAddDefault(addressMatcher, "address", "none");
String priorityToAdd = checkEmptyAndAddDefault(priorityMatcher, "priority", "1");
// String tagsToAdd = checkEmptyAndAddDefault(tagsMatcher, "tagsArgument", "");
// format date if due date is specified
if (dueDateMatcher.matches()) {
dueDateToAdd = parseDueDate(dueDateToAdd);
}
Set<String> tagsProcessed = Collections.emptySet();
if (tagsMatcher.matches()) {
tagsProcessed = getTagsFromArgs(tagsMatcher.group("tagArguments"));
}
// Validate arg string format
if (!nameMatcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
try {
return new AddCommand(
nameToAdd,
dueDateToAdd,
addressToAdd,
priorityToAdd,
tagsProcessed
);
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
}
private String appendEnd(String args) {
return args + " z/";
}
private String checkEmptyAndAddDefault(Matcher matcher, String groupName, String defaultValue) {
if (matcher.matches()) {
return matcher.group(groupName);
} else {
return defaultValue;
}
}
//@@author A0146130W
private String parseDueDate(String dueDateRaw) {
NaturalLanguageProcessor nlp = new DateNaturalLanguageProcessor();
return nlp.formatString(dueDateRaw);
}
// remove time on date parsed to improve search results
private String removeTimeOnDate(String dueDateRaw) {
String[] dateTime = dueDateRaw.split(" ");
return dateTime[0];
}
//@@author addressbook-level4
/**
* Extracts the new task's tags from the add command's tag arguments string.
* Merges duplicate tag strings.
*/
private static Set<String> getTagsFromArgs(String tagArguments) {
// no tags
if (tagArguments.isEmpty()) {
return Collections.emptySet();
}
// replace first delimiter prefix, then split
final Collection<String> tagStrings = Arrays.asList(tagArguments.split(" "));
return new HashSet<>(tagStrings);
}
//@@author A0146130W
/**
* Parses arguments in the context of the edit task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareEdit(String args) {
final Matcher matcher = EDIT_DATA_ARGS_FORMAT.matcher(args.trim());
// Validate arg string format
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
Optional<Integer> index = Optional.of(Integer.parseInt(matcher.group("targetIndex")));
final String[] splitNewDetails = matcher.group("newDetails").split("\\s+");
ArrayList<String> preparedNewDetails = combineNameWords(splitNewDetails);
Hashtable<String, String> newDetailsSet = new Hashtable<String, String>();
for (String newDetail : preparedNewDetails) {
String detailType = extractDetailType(newDetail);
String preparedNewDetail = prepareNewDetail(detailType, newDetail);
newDetailsSet.put(detailType, preparedNewDetail);
}
return new EditCommand(
index.get()-1,
newDetailsSet
);
}
private ArrayList<String> combineNameWords(String[] details) {
ArrayList<String> alDetails = new ArrayList<String>(Arrays.asList(details));
System.out.println(alDetails.toString());
String name = new String();
if(alDetails.size() == 1) {
return alDetails;
}
for (String detail: alDetails) {
System.out.println("detail: " + detail);
if(extractDetailType(detail).equals("name")) {
System.out.println("detected name " + detail);
if(name.isEmpty()) name = detail;
else name = name + " " + detail;
}
}
//does not remove the separate name-words from the list, they will be overwritten by the final combined string
if(!name.isEmpty()) alDetails.add(name);
return alDetails;
}
private String removeDetailPrefix(String detailWithPrefix) {
return detailWithPrefix.substring(detailWithPrefix.indexOf('/') + 1);
}
private String prepareNewDetail(String detailType, String detailWithPrefix) {
String detail = removeDetailPrefix(detailWithPrefix);
if(detailType.equals("dueDate")) detail = parseDueDate(detail);
return detail;
}
//@@author A0146130W-reused
private String extractDetailType(String args) {
String preprocessedArgs = " " + appendEnd(args.trim());
final Matcher dueDateMatcher = DUEDATE_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArgs);
final Matcher addressMatcher = ADDRESS_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArgs);
final Matcher priorityMatcher = PRIORITY_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArgs);
if(addressMatcher.matches()) {
return "address";
}
else if(dueDateMatcher.matches()) {
return "dueDate";
}
else if(priorityMatcher.matches()) {
return "priority";
}
return "name";
}
//@@author addressbook-level4
/**
* Parses arguments in the context of the delete task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareDelete(String args) {
Optional<Integer> index = parseIndex(args);
if(!index.isPresent()){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
return new DeleteCommand(index.get());
}
private Command prepareDone(String args) {
Optional<Integer> index = parseIndex(args);
System.out.println("index at preparedone:" + index.get());
if(!index.isPresent()){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DoneCommand.MESSAGE_USAGE));
}
return new DoneCommand(index.get());
}
/**
* Parses arguments in the context of the select task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareSelect(String args) {
Optional<Integer> index = parseIndex(args);
if(!index.isPresent()){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE));
}
return new SelectCommand(index.get());
}
/**
* Returns the specified index in the {@code command} IF a positive unsigned integer is given as the index.
* Returns an {@code Optional.empty()} otherwise.
*/
private Optional<Integer> parseIndex(String command) {
final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(command.trim());
if (!matcher.matches()) {
return Optional.empty();
}
String index = matcher.group("targetIndex");
if(!StringUtil.isUnsignedInteger(index)){
return Optional.empty();
}
return Optional.of(Integer.parseInt(index));
}
/**
* Parses arguments in the context of the find task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareFind(String args) {
// check if parameters are specified and pass specified field to FindCommand
String preprocessedArgs = " " + appendEnd(args.trim());
final Matcher addressMatcher = ADDRESS_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArgs);
final Matcher priorityMatcher = PRIORITY_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArgs);
final Matcher dueDateMatcher = DUEDATE_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArgs);
final Matcher tagsMatcher = TAGS_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArgs);
Set<String> defaultSet = new HashSet<String>();
if (addressMatcher.matches()) {
String addressToBeFound = addressMatcher.group("address");
return new FindCommand(addressToBeFound, defaultSet,"address");
}
if (priorityMatcher.matches()) {
String priorityToBeFound = priorityMatcher.group("priority");
return new FindCommand(priorityToBeFound, defaultSet, "priority");
}
if (dueDateMatcher.matches()) {
String dueDateToBeFound = dueDateMatcher.group("dueDate");
String parsedDueDateToBeFound = removeTimeOnDate(parseDueDate(dueDateToBeFound));
return new FindCommand(parsedDueDateToBeFound, defaultSet, "dueDate");
}
if (tagsMatcher.matches()) {
String tagsToBeFound = tagsMatcher.group("tagArguments");
return new FindCommand(tagsToBeFound, defaultSet,"tagArguments");
}
// free-form search by keywords
final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
FindCommand.MESSAGE_USAGE));
}
// keywords delimited by whitespace
final String[] splitKeywords = matcher.group("keywords").split("\\s+");
final Set<String> keywordSet = new HashSet<>(Arrays.asList(splitKeywords));
final String keywords = matcher.group("keywords");
return new FindCommand(keywords, keywordSet, "nil");
}
private Command prepareList(String args) {
// check if parameters are specified and pass specified field to FindCommand
//String preprocessedArgs = " " + appendEnd(args.trim());
return new ListCommand(args);
}
/**
* Parses arguments in the context of the help command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareHelp(String args) {
//if no argument
if (args.equals("")) {
args="help";
}
final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
final String commandWord = matcher.group("commandWord");
return new HelpCommand(commandWord);
}
}
|
/** @@author A0142130A **/
package seedu.taskell.ui;
import javafx.scene.Node;
import javafx.scene.control.TextArea;
import javafx.scene.layout.AnchorPane;
import jfxtras.scene.control.agenda.Agenda;
import seedu.taskell.commons.core.LogsCenter;
import seedu.taskell.commons.util.FxViewUtil;
import seedu.taskell.logic.commands.AddCommand;
import seedu.taskell.logic.commands.HelpCommand;
import seedu.taskell.logic.commands.ViewCalendarCommand;
import seedu.taskell.logic.commands.ViewHistoryCommand;
import java.util.ArrayList;
import java.util.logging.Logger;
/**
* The Display Panel of the App.
*/
public class DisplayPanel extends UiPart {
public static final String MESSAGE_NO_HISTORY = "No commands available for undo.";
public static final String MESSAGE_DISPLAY_HISTORY = "List of command history available for undo:\n";
private static final String WELCOME_MESSAGE = "Welcome to Taskell!\n"
+ "Enter '" + AddCommand.COMMAND_WORD + "' in command box to add a task.\n"
+ "Enter '" + ViewHistoryCommand.COMMAND_WORD_1 + "' for a list of commands to undo.\n"
+ "Enter '" + ViewCalendarCommand.COMMAND_WORD_1 + "' to view calendar.\n"
+ "Enter '" + HelpCommand.COMMAND_WORD + "' for more information about commands.";
private static Logger logger = LogsCenter.getLogger(DisplayPanel.class);
public static final String DISPLAY_PANEL_ID = "displayPanel";
private static final String STATUS_BAR_STYLE_SHEET = "result-display";
private TextArea displayTextArea;
private CalendarView calendarView;
private Agenda agenda;
/**
* Constructor is kept private as {@link #load(AnchorPane)} is the only way to create a DisplayPanel.
*/
private DisplayPanel() {
calendarView = new CalendarView();
displayTextArea = new TextArea();
agenda = calendarView.getAgenda();
}
@Override
public void setNode(Node node) {
//not applicable
}
@Override
public String getFxmlPath() {
return null; //not applicable
}
/**
* This method should be called after the FX runtime is initialized and in FX application thread.
* @param placeholder The AnchorPane where the DisplayPanel must be inserted
*/
public static DisplayPanel load(AnchorPane placeholder){
logger.info("Initializing displayTextArea panel");
DisplayPanel displayPanel = new DisplayPanel();
displayPanel.displayTextArea.setEditable(false);
displayPanel.displayTextArea.setId(DISPLAY_PANEL_ID);
displayPanel.displayTextArea.getStyleClass().removeAll();
displayPanel.displayTextArea.getStyleClass().add(STATUS_BAR_STYLE_SHEET);
FxViewUtil.applyAnchorBoundaryParameters(displayPanel.displayTextArea, 0.0, 0.0, 0.0, 0.0);
placeholder.getChildren().add(displayPanel.displayTextArea);
displayPanel.displayTextArea.setText(WELCOME_MESSAGE);
return displayPanel;
}
public void loadList(AnchorPane placeholder, ArrayList<String> list) {
placeholder.getChildren().clear();
placeholder.getChildren().add(displayTextArea);
displayTextArea.setText("");
if (list.isEmpty()) {
displayTextArea.setText(MESSAGE_NO_HISTORY);
}
else {
displayTextArea.setText(MESSAGE_DISPLAY_HISTORY);
for (int i=0; i<list.size(); i++) {
int index = i+1;
displayTextArea.appendText(index + ". " + list.get(i) + "\n");
}
}
}
public void loadCalendar(AnchorPane placeholder) {
placeholder.getChildren().remove(displayTextArea);
agenda = calendarView.getAgenda();
FxViewUtil.applyAnchorBoundaryParameters(agenda, 0.0, 0.0, 0.0, 0.0);
placeholder.getChildren().add(agenda);
}
/** @@author **/
}
|
package uw.task.conf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Binding.DestinationType;
import org.springframework.amqp.core.ExchangeBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.context.ApplicationContext;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import uw.task.TaskCroner;
import uw.task.TaskRunner;
import uw.task.api.TaskAPI;
import uw.task.container.TaskCronerContainer;
import uw.task.container.TaskRunnerContainer;
import uw.task.entity.TaskContact;
import uw.task.entity.TaskCronerConfig;
import uw.task.entity.TaskRunnerConfig;
import uw.task.util.TaskMessageConverter;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
/**
*
*
* @author axeon
* @param
*/
public class TaskServerConfig {
private static final Logger log = LoggerFactory.getLogger(TaskServerConfig.class);
private ApplicationContext context;
private ConnectionFactory taskConnectionFactory;
private TaskRunnerContainer taskRunnerContainer;
private TaskCronerContainer taskCronerContainer;
private TaskProperties taskProperties;
private TaskAPI taskAPI;
private RabbitAdmin rabbitAdmin;
/**
* containerkey=,value=container
*/
private ConcurrentHashMap<String, SimpleMessageListenerContainer> runnerContainerMap = new ConcurrentHashMap<>();
private long startTime = System.currentTimeMillis();
private long lastUpdateTime = 0;
private long queueUpdateTime = 0;
private boolean updateFlag = true;
private boolean isFirstRun = true;
/**
*
*
* @param taskProperties
* @param taskRabbitConnectionFactory
* @param taskRunnerContainer
* @param taskCronerContainer
* @param taskAPI
* @param rabbitAdmin
*/
public TaskServerConfig(ApplicationContext context, TaskProperties taskProperties,
ConnectionFactory taskRabbitConnectionFactory, TaskRunnerContainer taskRunnerContainer,
TaskCronerContainer taskCronerContainer, TaskAPI taskAPI, RabbitAdmin rabbitAdmin) {
this.context = context;
this.taskProperties = taskProperties;
this.taskConnectionFactory = taskRabbitConnectionFactory;
this.taskRunnerContainer = taskRunnerContainer;
this.taskCronerContainer = taskCronerContainer;
this.taskAPI = taskAPI;
this.rabbitAdmin = rabbitAdmin;
}
public void init() {
initCronerMap();
initRunnerMap();
// RPC
if (!taskProperties.isEnableTaskRegistry()) {
if (log.isDebugEnabled()) {
log.debug("...");
}
TaskMetaInfoManager.targetConfig = taskAPI.getServerTargetConfig();
}
}
public void updateStatus() {
if (taskProperties.isEnableTaskRegistry()) {
if (log.isDebugEnabled()) {
log.debug("...");
}
taskAPI.updateHostStatus();
}
}
public void loadSysQueue() {
List<TaskRunnerConfig> list = taskAPI.getTaskRunnerQueueList(queueUpdateTime);
if (list != null) {
for (TaskRunnerConfig config : list) {
TaskMetaInfoManager.updateSysQueue(config);
}
queueUpdateTime = System.currentTimeMillis();
}
}
public void updateConfig() {
if (!taskProperties.isEnableTaskRegistry()) {
return;
}
long startUpdateTimeMilles = System.currentTimeMillis();
// taskScheduler
if (log.isDebugEnabled()) {
log.debug("...");
}
List<String> newTargetConfig = taskAPI.getServerTargetConfig();
// croner
ConcurrentHashMap<String, TaskCronerConfig> updatedCronerConfigMap = updateCronerConfig();
if (!updateFlag) {
log.error("Cronerfail-fast!");
updateFlag = true;
return;
}
if (log.isDebugEnabled()) {
log.debug("[{}]TaskCroner...", updatedCronerConfigMap.size());
}
// runner
ConcurrentHashMap<String, TaskRunnerConfig> updatedRunnerConfigMap = updateRunnerConfig();
if (!updateFlag) {
log.error("Runnerfail-fast!");
updateFlag = true;
return;
}
if (log.isDebugEnabled()) {
log.debug("[{}]TaskRunner...", updatedRunnerConfigMap.size());
}
if (TaskMetaInfoManager.targetConfig != null) {
for (String config : TaskMetaInfoManager.targetConfig) {
if (!newTargetConfig.contains(config)) {
if (log.isDebugEnabled()) {
log.debug("[{}]...", config);
}
try {
for (Entry<String, SimpleMessageListenerContainer> kv : runnerContainerMap.entrySet()) {
if (kv.getKey().endsWith("$" + config)) {
kv.getValue().stop();
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
}
for (String host : newTargetConfig) {
if (TaskMetaInfoManager.targetConfig != null && !TaskMetaInfoManager.targetConfig.contains(host)) {
if (log.isDebugEnabled()) {
log.debug("[{}]...", host);
}
// croner&runner
updatedCronerConfigMap = TaskMetaInfoManager.cronerConfigMap;
updatedRunnerConfigMap = TaskMetaInfoManager.runnerConfigMap;
}
}
TaskMetaInfoManager.targetConfig = newTargetConfig;
if (isFirstRun) {
isFirstRun = false;
// cronerrunner
for (Entry<String, TaskCroner> kv : TaskMetaInfoManager.cronerMap.entrySet()) {
try {
TaskCroner tc = kv.getValue();
String taskClass = tc.getClass().getName();
if (log.isDebugEnabled()) {
log.debug("croner:{}", taskClass);
}
TaskCronerConfig localConfig = tc.initConfig();
TaskContact contact = tc.initContact();
if (localConfig == null || contact == null) {
log.error("TaskCroner:[{}]", taskClass);
continue;
}
localConfig.setTaskParam("");
localConfig.setTaskClass(taskClass);
contact.setTaskClass(taskClass);
String configKey = TaskMetaInfoManager.getCronerConfigKey(localConfig);
TaskCronerConfig serverConfig = updatedCronerConfigMap.get(configKey);
if (serverConfig == null) {
if (log.isDebugEnabled()) {
log.debug("TaskCroner:[{}]...", taskClass);
}
serverConfig = uploadCronerInfo(localConfig, contact);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
// TaskRunner
for (Entry<String, TaskRunner> kv : TaskMetaInfoManager.runnerMap.entrySet()) {
try {
TaskRunner<?, ?> tr = kv.getValue();
String taskClass = kv.getKey();
TaskRunnerConfig localConfig = tr.initConfig();
TaskContact contact = tr.initContact();
if (localConfig == null || contact == null) {
log.error("TaskRunner:[{}]", taskClass);
continue;
}
localConfig.setTaskClass(taskClass);
contact.setTaskClass(taskClass);
String configKey = TaskMetaInfoManager.getRunnerConfigKey(localConfig);
TaskRunnerConfig serverConfig = updatedRunnerConfigMap.get(configKey);
if (serverConfig == null) {
if (log.isDebugEnabled()) {
log.debug("TaskRunner:[{}]...", taskClass);
}
serverConfig = uploadRunnerInfo(localConfig, contact);
}
TaskMessageConverter.constructTaskDataType(taskClass, kv.getValue());
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
// configMap
updatedCronerConfigMap = TaskMetaInfoManager.cronerConfigMap;
updatedRunnerConfigMap = TaskMetaInfoManager.runnerConfigMap;
}
if (updatedCronerConfigMap != null) {
for (TaskCronerConfig tcc : updatedCronerConfigMap.values()) {
if (log.isDebugEnabled()) {
log.debug("ID:{},CRONER:{},CRON:{},", tcc.getId(), tcc.getTaskClass(), tcc.getTaskCron());
}
TaskCroner tc = TaskMetaInfoManager.cronerMap.get(tcc.getTaskClass());
if (tc != null) {
try {
if (!TaskMetaInfoManager.targetConfig.contains(tcc.getRunTarget())) {
tcc.setState(0);
}
taskCronerContainer.configureTask(tc, tcc);
if (log.isDebugEnabled()) {
log.debug("TaskCroner:[{}]...", TaskMetaInfoManager.getCronerConfigKey(tcc));
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
} else {
log.warn("TaskCroner:[{}]!", tcc.getTaskClass());
}
}
}
// Runner
if (updatedRunnerConfigMap != null) {
for (TaskRunnerConfig trc : updatedRunnerConfigMap.values()) {
if (TaskMetaInfoManager.runnerMap.containsKey(trc.getTaskClass())) {
if (TaskMetaInfoManager.targetConfig.contains(trc.getRunTarget())) {
registerRunner(trc);
}
} else {
log.warn("TaskRunner:[{}]!", trc.getTaskClass());
}
}
}
if (updateFlag) {
// ms5000
lastUpdateTime = startUpdateTimeMilles - 5000;
}
updateFlag = true;
}
/**
* conerMap getBeansOfTypekey
*/
private void initCronerMap() {
// TaskCroner
Map<String, TaskCroner> cronerInstanceMap = context.getBeansOfType(TaskCroner.class);
for (Entry<String, TaskCroner> kv : cronerInstanceMap.entrySet()) {
TaskCroner tc = kv.getValue();
String taskClass = tc.getClass().getName();
TaskMetaInfoManager.cronerMap.put(taskClass, tc);
}
}
/**
* conerMap getBeansOfTypekey
*/
private void initRunnerMap() {
// TaskCroner
Map<String, TaskRunner> runnerInstanceMap = context.getBeansOfType(TaskRunner.class);
for (Entry<String, TaskRunner> kv : runnerInstanceMap.entrySet()) {
TaskRunner tr = kv.getValue();
String taskClass = tr.getClass().getName();
TaskMetaInfoManager.runnerMap.put(taskClass, tr);
}
}
/**
* Croner
*
* @return
*/
private ConcurrentHashMap<String, TaskCronerConfig> updateCronerConfig() {
ConcurrentHashMap<String, TaskCronerConfig> map = new ConcurrentHashMap<>();
List<TaskCronerConfig> list = taskAPI.getTaskCronerConfigList(taskProperties.getProject(), lastUpdateTime);
if (list != null) {
for (TaskCronerConfig config : list) {
String key = TaskMetaInfoManager.getCronerConfigKey(config);
map.put(key, config);
TaskMetaInfoManager.cronerConfigMap.put(key, config);
}
} else {
updateFlag = false;
}
return map;
}
/**
* Runner
*
* @return
*/
private ConcurrentHashMap<String, TaskRunnerConfig> updateRunnerConfig() {
ConcurrentHashMap<String, TaskRunnerConfig> map = new ConcurrentHashMap<>();
List<TaskRunnerConfig> list = taskAPI.getTaskRunnerConfigList(taskProperties.getProject(), lastUpdateTime);
if (list != null) {
for (TaskRunnerConfig config : list) {
String key = TaskMetaInfoManager.getRunnerConfigKey(config);
map.put(key, config);
TaskMetaInfoManager.runnerConfigMap.put(key, config);
}
} else {
updateFlag = false;
}
return map;
}
/**
* Runner
*
* @param config
* @param contact
*/
private TaskRunnerConfig uploadRunnerInfo(TaskRunnerConfig config, TaskContact contact) {
config = taskAPI.initTaskRunnerConfig(config);
taskAPI.initTaskContact(contact);
TaskMetaInfoManager.runnerConfigMap.put(TaskMetaInfoManager.getRunnerConfigKey(config), config);
return config;
}
/**
* Croner
*
* @param config
* @param contact
*/
private TaskCronerConfig uploadCronerInfo(TaskCronerConfig config, TaskContact contact) {
config = taskAPI.initTaskCronerConfig(config);
taskAPI.initTaskContact(contact);
TaskMetaInfoManager.cronerConfigMap.put(TaskMetaInfoManager.getCronerConfigKey(config), config);
return config;
}
/**
*
*
* @param runnerConfig
*/
private void registerRunner(TaskRunnerConfig runnerConfig) {
String queueName = TaskMetaInfoManager.getRunnerConfigKey(runnerConfig);
SimpleMessageListenerContainer container = runnerContainerMap.get(queueName);
if (container == null) {
if (runnerConfig.getState() != 1) {
log.warn("TaskRunner:[{}]", queueName);
return;
}
if (log.isDebugEnabled()) {
log.debug("TaskRunner:[{}]...", queueName);
}
try {
synchronized (runnerContainerMap) {
rabbitAdmin.declareQueue(new Queue(queueName, true));
rabbitAdmin.declareExchange(ExchangeBuilder.directExchange(queueName).durable(true).build());
rabbitAdmin
.declareBinding(new Binding(queueName, DestinationType.QUEUE, queueName, queueName, null));
container = new SimpleMessageListenerContainer();
container.setAutoStartup(false);
container.setTaskExecutor(new SimpleAsyncTaskExecutor(queueName));
// consumer
container.setConsecutiveActiveTrigger(3);
container.setStartConsumerMinInterval(1000);
container.setMaxConcurrentConsumers(runnerConfig.getConsumerNum());
container.setConcurrentConsumers((int) Math.ceil(runnerConfig.getConsumerNum() * 0.2f));
container.setPrefetchCount(runnerConfig.getPrefetchNum());
container.setConnectionFactory(taskConnectionFactory);
container.setAcknowledgeMode(AcknowledgeMode.AUTO);
container.setQueueNames(queueName);
MessageListenerAdapter listenerAdapter = new MessageListenerAdapter(taskRunnerContainer, "process");
// listenerAdapter.setReplyPostProcessor(new
// GZipPostProcessor());
listenerAdapter.setMessageConverter(new TaskMessageConverter());
container.setMessageListener(listenerAdapter);
container.setMessageConverter(new TaskMessageConverter());
// container.setAfterReceivePostProcessors(new
// GUnzipPostProcessor());
container.setAutoStartup(true);
container.afterPropertiesSet();
container.start();
runnerContainerMap.putIfAbsent(queueName, container);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
} else {
if (runnerConfig.getState() == 1) {
try {
container.setMaxConcurrentConsumers(runnerConfig.getConsumerNum());
container.setConcurrentConsumers((int) Math.ceil(runnerConfig.getConsumerNum() * 0.2f));
container.setPrefetchCount(runnerConfig.getPrefetchNum());
} catch (Exception e) {
log.error(e.getMessage(), e);
}
} else {
runnerContainerMap.remove(queueName);
container.shutdown();
container.stop();
}
}
}
public void stopAllTaskRunner() {
for (SimpleMessageListenerContainer container : runnerContainerMap.values()) {
container.shutdown();
container.stop();
}
}
}
|
package org.deidentifier.arx;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.deidentifier.arx.algorithm.AbstractAlgorithm;
import org.deidentifier.arx.algorithm.FLASHAlgorithm;
import org.deidentifier.arx.algorithm.FLASHStrategy;
import org.deidentifier.arx.criteria.KAnonymity;
import org.deidentifier.arx.criteria.LDiversity;
import org.deidentifier.arx.criteria.TCloseness;
import org.deidentifier.arx.framework.check.INodeChecker;
import org.deidentifier.arx.framework.check.NodeChecker;
import org.deidentifier.arx.framework.data.DataManager;
import org.deidentifier.arx.framework.data.Dictionary;
import org.deidentifier.arx.framework.data.GeneralizationHierarchy;
import org.deidentifier.arx.framework.lattice.Lattice;
import org.deidentifier.arx.framework.lattice.LatticeBuilder;
import org.deidentifier.arx.metric.Metric;
/**
* This class offers several methods to define parameters and execute the ARX
* algorithm.
*
* @author Fabian Prasser
* @author Florian Kohlmayer
*/
public class ARXAnonymizer {
/**
* Temporary result of the ARX algorithm.
*
* @author Fabian Prasser
* @author Florian Kohlmayer
*/
class Result {
/** The algorithm */
final AbstractAlgorithm algorithm;
/** The checker. */
final INodeChecker checker;
/** The lattice. */
final Lattice lattice;
/** The data manager */
final DataManager manager;
/** The metric. */
final Metric<?> metric;
/**
* Creates a new instance.
*
* @param metric the metric
* @param checker the checker
* @param lattice the lattice
* @param manager the manager
*/
Result(final Metric<?> metric,
final INodeChecker checker,
final Lattice lattice,
final DataManager manager,
final AbstractAlgorithm algorithm) {
this.metric = metric;
this.checker = checker;
this.lattice = lattice;
this.manager = manager;
this.algorithm = algorithm;
}
/**
* Creates a final result from this temporary result
* @param anonymizer
* @param handle
* @param time
* @return
*/
public ARXResult asResult(ARXConfiguration config, DataHandle handle, long time) {
// Create lattice
final ARXLattice flattice = new ARXLattice(lattice,
manager.getDataQI().getHeader(),
config);
// Create output handle
((DataHandleInput)handle).setLocked(true);
return new ARXResult(handle.getRegistry(),
this.manager,
this.checker,
handle.getDefinition(),
config,
flattice,
System.currentTimeMillis() - time,
suppressionString,
removeOutliers);
}
}
/** History size. */
private int historySize = 200;
/** The listener, if any. */
private ARXListener listener = null;
/** Remove outliers? */
private boolean removeOutliers = true;
/** Snapshot size. */
private double snapshotSizeDataset = 0.2d;
/** Snapshot size snapshot */
private double snapshotSizeSnapshot = 0.8d;
/** The string to insert for outliers. */
private String suppressionString = "*";
/**
* Creates a new anonymizer with the default configuration
*/
public ARXAnonymizer() {
// Empty by design
}
/**
* Creates a new anonymizer with the given configuration.
*
* @param historySize The maximum number of snapshots stored in the buffer [default=200]
* @param snapshotSizeDataset The maximum relative size of a snapshot compared to the dataset [default=0.2]
* @param snapshotSizeSnapshot The maximum relative size of a snapshot compared to its predecessor [default=0.8]
*/
public ARXAnonymizer(final int historySize, final double snapshotSizeDataset, final double snapshotSizeSnapshot) {
if (historySize<0)
throw new RuntimeException("History size must be >=0");
this.historySize = historySize;
if (snapshotSizeDataset<=0 || snapshotSizeDataset>=1)
throw new RuntimeException("SnapshotSizeDataset must be >0 and <1");
this.snapshotSizeDataset = snapshotSizeDataset;
if (snapshotSizeSnapshot<=0 || snapshotSizeSnapshot>=1)
throw new RuntimeException("snapshotSizeSnapshot must be >0 and <1");
this.snapshotSizeSnapshot = snapshotSizeSnapshot;
}
/**
* Creates a new anonymizer with the given configuration.
*
* @param suppressionString The string inserted for suppressed values
*/
public ARXAnonymizer(final String suppressionString) {
this.suppressionString = suppressionString;
}
/**
* Creates a new anonymizer with the given configuration.
*
* @param suppressionString The string inserted for suppressed values
* @param historySize The maximum number of snapshots stored in the buffer [default=200]
* @param snapshotSizeDataset The maximum relative size of a snapshot compared to the dataset [default=0.2]
* @param snapshotSizeSnapshot The maximum relative size of a snapshot compared to its predecessor [default=0.8]
*/
public ARXAnonymizer(final String suppressionString, final int historySize, final double snapshotSizeDataset, final double snapshotSizeSnapshot) {
this.suppressionString = suppressionString;
if (historySize<0)
throw new RuntimeException("History size must be >=0");
this.historySize = historySize;
if (snapshotSizeDataset<=0 || snapshotSizeDataset>=1)
throw new RuntimeException("SnapshotSizeDataset must be >0 and <1");
this.snapshotSizeDataset = snapshotSizeDataset;
if (snapshotSizeSnapshot<=0 || snapshotSizeSnapshot>=1)
throw new RuntimeException("snapshotSizeSnapshot must be >0 and <1");
this.snapshotSizeSnapshot = snapshotSizeSnapshot;
}
/**
* Performs data anonymization
* @param data The data
* @param config The privacy config
* @return ARXResult
* @throws IOException
*/
public ARXResult anonymize(final Data data, ARXConfiguration config) throws IOException {
if (((DataHandleInput)data.getHandle()).isLocked()){
throw new RuntimeException("This data handle is locked. Please release it first");
}
if (data.getDefinition().getSensitiveAttributes().size() > 1 && config.isProtectSensitiveAssociations()) {
throw new UnsupportedOperationException("Currently not supported!");
}
DataHandle handle = data.getHandle();
final long time = System.currentTimeMillis();
checkBeforeEncoding(handle, config);
handle.getRegistry().reset();
handle.getRegistry().createInputSubset(config);
// Execute
return anonymizeInternal(handle, handle.getDefinition(), config).asResult(config, handle, time);
}
/**
* Returns the maximum number of snapshots allowed to store in the history.
*
* @return The size
*/
public int getHistorySize() {
return historySize;
}
/**
* Gets the snapshot size.
*
* @return The maximum size of a snapshot relative to the dataset size
*/
public double getMaximumSnapshotSizeDataset() {
return snapshotSizeDataset;
}
/**
* Gets the snapshot size.
*
* @return The maximum size of a snapshot relative to the previous snapshot
* size
*/
public double getMaximumSnapshotSizeSnapshot() {
return snapshotSizeSnapshot;
}
/**
* Returns the string with which outliers are replaced.
*
* @return the relativeMaxOutliers string
*/
public String getSuppressionString() {
return suppressionString;
}
/**
* Does the anonymizer remove outliers from the dataset?
*
* @return
*/
public boolean isRemoveOutliers() {
return removeOutliers;
}
/**
* Sets the maximum number of snapshots allowed to store in the history.
*
* @param historySize
* The size
*/
public void setHistorySize(final int historySize) {
if (historySize < 1) { throw new IllegalArgumentException("history size must be positive and not 0"); }
this.historySize = historySize;
}
/**
* Sets a listener.
*
* @param listener
* the new listener, if any
*/
public void setListener(final ARXListener listener) {
this.listener = listener;
}
/**
* Sets the maximum size of a snapshot relative to the dataset size.
*
* @param snapshotSizeDataset
* The size
*/
public void setMaximumSnapshotSizeDataset(final double snapshotSize) {
// Perform sanity checks
if ((snapshotSize <= 0d) || (snapshotSize > 1d)) { throw new IllegalArgumentException("Snapshot size " + snapshotSize + "must be in [0,1]"); }
snapshotSizeDataset = snapshotSize;
}
/**
* Sets the maximum size of a snapshot relative to the previous snapshot
*
* @param snapshotSizeSnapshot
* The size
*/
public void setMaximumSnapshotSizeSnapshot(final double snapshotSizeSnapshot) {
// Perform sanity checks
if ((snapshotSizeSnapshot <= 0d) || (snapshotSizeSnapshot > 1d)) { throw new IllegalArgumentException("Snapshot size " + snapshotSizeSnapshot + "must be in [0,1]"); }
this.snapshotSizeSnapshot = snapshotSizeSnapshot;
}
/**
* Set whether the anonymizer should remove outliers
*
* @param value
*/
public void setRemoveOutliers(final boolean value) {
removeOutliers = value;
}
/**
* Sets the string with which suppressed values are to be replaced.
*
* @param suppressionString
* The relativeMaxOutliers string
*/
public void setSuppressionString(final String suppressionString) {
if (suppressionString == null) { throw new NullPointerException("suppressionString must not be null"); }
this.suppressionString = suppressionString;
}
/**
* Performs some sanity checks.
*
* @param manager
* the manager
*/
private void checkAfterEncoding(final ARXConfiguration config, final DataManager manager) {
if (config.containsCriterion(KAnonymity.class)){
KAnonymity c = config.getCriterion(KAnonymity.class);
if ((c.getK() > manager.getDataQI().getDataLength()) || (c.getK() < 1)) {
throw new IllegalArgumentException("Parameter k (" + c.getK() + ") musst be positive and less or equal than the number of rows (" + manager.getDataQI().getDataLength()+")");
}
}
if (config.containsCriterion(LDiversity.class)){
for (LDiversity c : config.getCriteria(LDiversity.class)){
if ((c.getL() > manager.getDataQI().getDataLength()) || (c.getL() < 1)) {
throw new IllegalArgumentException("Parameter l (" + c.getL() + ") musst be positive and less or equal than the number of rows (" + manager.getDataQI().getDataLength()+")");
}
}
}
// Check whether all hierarchies are monotonic
for (final GeneralizationHierarchy hierarchy : manager.getHierarchies()) {
hierarchy.checkMonotonicity(manager);
}
// check min and max sizes
final int[] hierarchyHeights = manager.getHierachyHeights();
final int[] minLevels = manager.getMinLevels();
final int[] maxLevels = manager.getMaxLevels();
for (int i = 0; i < hierarchyHeights.length; i++) {
if (minLevels[i] > (hierarchyHeights[i] - 1)) { throw new IllegalArgumentException("Invalid minimum generalization for attribute '" + manager.getHierarchies()[i].getName() + "': " +
minLevels[i] + " > " + (hierarchyHeights[i] - 1)); }
if (minLevels[i] < 0) { throw new IllegalArgumentException("The minimum generalization for attribute '" + manager.getHierarchies()[i].getName() + "' has to be positive!"); }
if (maxLevels[i] > (hierarchyHeights[i] - 1)) { throw new IllegalArgumentException("Invalid maximum generalization for attribute '" + manager.getHierarchies()[i].getName() + "': " +
maxLevels[i] + " > " + (hierarchyHeights[i] - 1)); }
if (maxLevels[i] < minLevels[i]) { throw new IllegalArgumentException("The minimum generalization for attribute '" + manager.getHierarchies()[i].getName() +
"' has to be lower than or requal to the defined maximum!"); }
}
}
/**
* Performs some sanity checks.
*
* @param handle
* the data handle
* @param config
* the configuration
*/
private void checkBeforeEncoding(final DataHandle handle, final ARXConfiguration config) {
// Lots of checks
if (handle == null) { throw new NullPointerException("Data cannot be null!"); }
if (config.containsCriterion(LDiversity.class) ||
config.containsCriterion(TCloseness.class)){
if (handle.getDefinition().getSensitiveAttributes().size() == 0) { throw new IllegalArgumentException("You need to specify a sensitive attribute!"); }
}
for (String attr : handle.getDefinition().getSensitiveAttributes()){
boolean found = false;
for (LDiversity c : config.getCriteria(LDiversity.class)) {
if (c.getAttribute().equals(attr)) {
found = true;
break;
}
}
if (!found) {
for (TCloseness c : config.getCriteria(TCloseness.class)) {
if (c.getAttribute().equals(attr)) {
found = true;
break;
}
}
}
if (!found) {
throw new IllegalArgumentException("No criterion defined for sensitive attribute: '"+attr+"'!");
}
}
for (LDiversity c : config.getCriteria(LDiversity.class)) {
if (handle.getDefinition().getAttributeType(c.getAttribute()) != AttributeType.SENSITIVE_ATTRIBUTE) {
throw new RuntimeException("L-Diversity criterion defined for non-sensitive attribute '"+c.getAttribute()+"'!");
}
}
for (TCloseness c : config.getCriteria(TCloseness.class)) {
if (handle.getDefinition().getAttributeType(c.getAttribute()) != AttributeType.SENSITIVE_ATTRIBUTE) {
throw new RuntimeException("T-Closeness criterion defined for non-sensitive attribute '"+c.getAttribute()+"'!");
}
}
// Check handle
if (!(handle instanceof DataHandleInput)) { throw new IllegalArgumentException("Invalid data handle provided!"); }
// Check if all defines are correct
Set<String> attributes = new HashSet<String>();
for (int i=0; i<handle.getNumColumns(); i++){
attributes.add(handle.getAttributeName(i));
}
for (String attribute : handle.getDefinition().getSensitiveAttributes()){
if (!attributes.contains(attribute)) {
throw new IllegalArgumentException("Sensitive attribute '"+attribute+"' is not contained in the dataset");
}
}
for (String attribute : handle.getDefinition().getInsensitiveAttributes()){
if (!attributes.contains(attribute)) {
throw new IllegalArgumentException("Insensitive attribute '"+attribute+"' is not contained in the dataset");
}
}
for (String attribute : handle.getDefinition().getIdentifyingAttributes()){
if (!attributes.contains(attribute)) {
throw new IllegalArgumentException("Identifying attribute '"+attribute+"' is not contained in the dataset");
}
}
for (String attribute : handle.getDefinition().getQuasiIdentifyingAttributes()){
if (!attributes.contains(attribute)) {
throw new IllegalArgumentException("Quasi-identifying attribute '"+attribute+"' is not contained in the dataset");
}
}
// Perform sanity checks
Map<String, String[][]> hierarchies = handle.getDefinition().getHierarchies();
if ((config.getMaxOutliers() < 0d) || (config.getMaxOutliers() > 1d)) { throw new IllegalArgumentException("Suppression rate " + config.getMaxOutliers() + "must be in [0, 1]"); }
if (hierarchies.size() > 15) { throw new IllegalArgumentException("The curse of dimensionality strikes. Too many quasi-identifiers: " + hierarchies.size()); }
if (hierarchies.size() == 0) { throw new IllegalArgumentException("You need to specify at least one quasi-identifier"); }
}
/**
* Prepares the data manager.
*
* @param handle
* the handle
* @param config
* the config
* @param definition
* the definition
* @return the data manager
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private DataManager prepareDataManager(final DataHandle handle, final DataDefinition definition, final ARXConfiguration config) throws IOException {
// Extract data
final String[] header = ((DataHandleInput) handle).header;
final int[][] dataArray = ((DataHandleInput) handle).data;
final Dictionary dictionary = ((DataHandleInput) handle).dictionary;
final DataManager manager = new DataManager(header, dataArray, dictionary, definition, config.getCriteria());
return manager;
}
/**
* Reset a previous lattice and run the algorithm
* @param handle
* @param definition
* @param config
* @param lattice
* @param algorithm
* @return
* @throws IOException
*/
protected Result anonymizeInternal(final DataHandle handle,
final DataDefinition definition,
final ARXConfiguration config) throws IOException {
// Encode
final DataManager manager = prepareDataManager(handle, definition, config);
// Attach arrays to data handle
((DataHandleInput)handle).update(manager.getDataQI().getArray(),
manager.getDataSE().getArray(),
manager.getDataIS().getArray());
// Initialize
config.initialize(manager);
// Check
checkAfterEncoding(config, manager);
// Build or clean the lattice
Lattice lattice = new LatticeBuilder(manager.getMaxLevels(), manager.getMinLevels(), manager.getHierachyHeights()).build();
lattice.setListener(listener);
// Build a node checker
final INodeChecker checker = new NodeChecker(manager, config.getMetric(), config, historySize, snapshotSizeDataset, snapshotSizeSnapshot);
// Initialize the metric
config.getMetric().initialize(manager.getDataQI(), manager.getHierarchies(), config);
// Create an algorithm instance
AbstractAlgorithm algorithm = FLASHAlgorithm.create(lattice, checker,
new FLASHStrategy(lattice, manager.getHierarchies()));
// Execute
algorithm.traverse();
// Deactivate history to prevent bugs when sorting data
checker.getHistory().reset();
checker.getHistory().setSize(0);
// Return the result
return new Result(config.getMetric(), checker, lattice, manager, algorithm);
}
}
|
package com.afollestad.silk.cache;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
/**
* Handles writing/reading images to and from the external disk cache.
*
* @author Aidan Follestad
*/
public class DiskCache {
public DiskCache(Context context) {
this.context = context;
setCacheDirectory(null);
}
private final Context context;
private static File CACHE_DIR;
public void put(String key, Bitmap image) throws Exception {
File fi = getFile(key);
Log.d("SilkImageManager.DiskCache", "Writing image to " + fi.getAbsolutePath());
FileOutputStream os = new FileOutputStream(fi);
image.compress(Bitmap.CompressFormat.JPEG, 100, os);
}
public Bitmap get(String key) {
File fi = getFile(key);
if (!fi.exists()) return null;
return BitmapFactory.decodeFile(fi.getAbsolutePath());
}
public File getFile(String key) {
return new File(CACHE_DIR, key + ".jpeg");
}
public void setCacheDirectory(File dir) {
if (dir == null) {
CACHE_DIR = context.getExternalCacheDir();
if (CACHE_DIR == null) CACHE_DIR = context.getCacheDir();
} else CACHE_DIR = dir;
CACHE_DIR.mkdirs();
}
}
|
package com.cube.storm;
import android.content.Context;
import android.net.Uri;
import android.support.annotation.NonNull;
import com.cube.storm.ui.controller.adapter.StormListAdapter;
import com.cube.storm.ui.controller.downloader.StormSchemeHandler;
import com.cube.storm.ui.data.ContentSize;
import com.cube.storm.ui.lib.EventHook;
import com.cube.storm.ui.lib.factory.FileFactory;
import com.cube.storm.ui.lib.factory.IntentFactory;
import com.cube.storm.ui.lib.handler.LinkHandler;
import com.cube.storm.ui.lib.helper.ViewHelper;
import com.cube.storm.ui.lib.parser.ViewBuilder;
import com.cube.storm.ui.lib.parser.ViewProcessor;
import com.cube.storm.ui.lib.processor.TextProcessor;
import com.cube.storm.ui.lib.provider.DefaultIntentProvider;
import com.cube.storm.ui.lib.provider.IntentProvider;
import com.cube.storm.ui.lib.resolver.AppResolver;
import com.cube.storm.ui.lib.resolver.IntentResolver;
import com.cube.storm.ui.lib.resolver.IntentResolverMap;
import com.cube.storm.ui.lib.resolver.ViewResolver;
import com.cube.storm.ui.lib.spec.DividerSpec;
import com.cube.storm.ui.lib.spec.ListDividerSpec;
import com.cube.storm.ui.model.App;
import com.cube.storm.ui.model.Model;
import com.cube.storm.ui.model.descriptor.PageDescriptor;
import com.cube.storm.ui.model.list.ListItem;
import com.cube.storm.ui.model.list.collection.CollectionItem;
import com.cube.storm.ui.model.page.Page;
import com.cube.storm.ui.model.property.LinkProperty;
import com.cube.storm.ui.model.property.TextProperty;
import com.cube.storm.util.lib.processor.Processor;
import com.cube.storm.util.lib.resolver.AssetsResolver;
import com.cube.storm.util.lib.resolver.FileResolver;
import com.cube.storm.util.lib.resolver.Resolver;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.download.handlers.SchemeHandler;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import lombok.Getter;
import lombok.Setter;
/**
* This is the entry point class of the library. To enable the use of the library, you must instantiate
* a new {@link UiSettings.Builder} object in your {@link android.app.Application} singleton class.
*
* This class should not be directly instantiated.
*
* @author Callum Taylor
* @project LightningUi
*/
public class UiSettings
{
/**
* The singleton instance of the settings
*/
private static UiSettings instance;
public static UiSettings getInstance()
{
if (instance == null)
{
throw new IllegalAccessError("You must build the Ui settings object first using UiSettings$Builder");
}
return instance;
}
/**
* Default private constructor
*/
private UiSettings(){}
/**
* App data for the content
*/
@Getter private App app;
/**
* The central point of the library to work out how to link between pages based on page descriptors or Uris.
* ALWAYS call this to deal with resolving intents/fragments over {@link #intentProviders} as this implementation
* calls {@link #intentProviders}
*/
@Getter @Setter private IntentFactory intentFactory = new IntentFactory();
/**
* List of providers for dealing with intents. Intent provider should return null in each method it doesnt consume.
* Intent providers are executed in order or list with user-overridden providers to be prioritised.
*/
@Getter @Setter private List<IntentProvider> intentProviders = new ArrayList<>();
/**
* Intent resolver used to resolving specific pages to an fragment/intent using either a page ID/Uri/descriptor.
* Intents registered here are prioritised over default resolutions from {@link #intentFactory}
*/
@Getter @Setter private IntentResolverMap intentResolver = new IntentResolverMap();
/**
* Factory class responsible for loading a file from disk based on its Uri
*/
@Getter @Setter private FileFactory fileFactory;
/**
* The view processor map used by {@link com.cube.storm.ui.lib.parser.ViewBuilder}. Use {@link com.cube.storm.UiSettings.Builder#registerType(Type, com.cube.storm.ui.lib.parser.ViewProcessor)} to
* override the processor used to match models with json class names
*/
@Getter @Setter private Map<Type, ViewProcessor> viewProcessors = new LinkedHashMap<Type, ViewProcessor>(0);
/**
* Image loader which is used when displaying images in the list
*/
@Getter @Setter private ImageLoader imageLoader = ImageLoader.getInstance();
/**
* The density to use when loading images
*/
@Getter @Setter private ContentSize contentSize;
/**
* The handler used when a link is triggered
*/
@Getter @Setter private LinkHandler linkHandler;
/**
* The gson builder class used to build all of the storm objects from json/string/binary
*/
@Getter @Setter private ViewBuilder viewBuilder;
/**
* Processor class used to process strings as part of {@link com.cube.storm.ui.model.property.TextProperty}
*/
@Getter @Setter private Processor<TextProperty, String> textProcessor;
/**
* Uri resolver used to load a file based on it's protocol. You should not need to use this instance
* directly to load a file, instead use {@link com.cube.storm.ui.lib.factory.FileFactory} which uses this
* to resolve a file and load it. Only use this if you want to load a specific scheme
*/
@Getter @Setter private Map<String, Resolver> uriResolvers = new HashMap<String, Resolver>(2);
/**
* Maps class names with a view resolver object to resolve models/viewholders.
*/
@Getter @Setter private Map<String, ViewResolver> viewResolvers = new HashMap<String, ViewResolver>(2);
/**
* Default divider spec to use in {@link com.cube.storm.ui.controller.adapter.StormListAdapter}
*/
@Getter @Setter private DividerSpec dividerSpec;
/**
* Registered hook classes for various events
*/
@Getter @Setter private ArrayList<EventHook> eventHooks = new ArrayList<>();
/**
* Registered hook classes for various events
*/
@Getter @Setter private Class<? extends StormListAdapter> viewAdapter = StormListAdapter.class;
/**
* Default language Uri
*/
@Getter @Setter private String defaultLanguageUri = "";
/**
* Sets the app model of the content
*
* @param app The new app model
*/
public void setApp(@NonNull App app)
{
this.app = app;
}
/**
* The builder class for {@link com.cube.storm.UiSettings}. Use this to create a new {@link com.cube.storm.UiSettings} instance
* with the customised properties specific for your project.
*
* Call {@link #build()} to build the settings object.
*/
public static class Builder
{
/**
* The temporary instance of the {@link UiSettings} object.
*/
private UiSettings construct;
private Context context;
/**
* Default constructor
*/
public Builder(Context context)
{
this.construct = new UiSettings();
this.context = context.getApplicationContext();
fileFactory(new FileFactory(){});
imageLoaderConfiguration(new ImageLoaderConfiguration.Builder(this.context));
linkHandler(new LinkHandler());
textProcessor(new TextProcessor());
contentSize(ContentSize.AUTO);
// Register views and models
registerViewResolver(ViewHelper.getViewResolvers());
// Register view resolvers for Gson adapters
ViewProcessor<? extends Model> baseProcessor = new ViewProcessor<Model>()
{
@Override public Class<? extends Model> getClassFromName(String name)
{
ViewResolver resolver = UiSettings.getInstance().getViewResolvers().get(name);
if (resolver != null)
{
return resolver.resolveModel();
}
return null;
}
};
registerType(Page.class, baseProcessor);
registerType(ListItem.class, baseProcessor);
registerType(CollectionItem.class, baseProcessor);
registerType(LinkProperty.class, baseProcessor);
registerUriResolver("file", new FileResolver());
registerUriResolver("assets", new AssetsResolver(this.context));
registerUriResolver("app", new AppResolver(this.context));
viewBuilder(new ViewBuilder(){});
dividerSpec(new ListDividerSpec());
}
/**
* Sets the default {@link com.cube.storm.ui.lib.spec.DividerSpec} for the list adapter to use when layout out its children
*
* @param spec The new divider spec to use by default
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder dividerSpec(DividerSpec spec)
{
construct.dividerSpec = spec;
return this;
}
/**
* Registers a page id/name to resolve to a specific intent resolver.
*
* @param pageId The id of the page. This will also match on a page's `name`
* @param resolver The intent resolver class
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder registerIntentResolver(String pageId, IntentResolver resolver)
{
construct.getIntentResolver().registerPageId(pageId, resolver);
return this;
}
/**
* Registers a page URI to resolve to a specific intent resolver.
*
* @param pageUri The URI of the page.
* @param resolver The intent resolver class
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder registerIntentResolver(Uri pageUri, IntentResolver resolver)
{
construct.getIntentResolver().registerPageUri(pageUri, resolver);
return this;
}
/**
* Registers a page descriptor to resolve to a specific intent resolver.
*
* @param pageDescriptor The descriptor of the page.
* @param resolver The intent resolver class
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder registerIntentResolver(PageDescriptor pageDescriptor, IntentResolver resolver)
{
construct.getIntentResolver().registerPageDescriptor(pageDescriptor, resolver);
return this;
}
/**
* Adds an intent provider to the bottom of the provider list (lowest priority)
* @param provider
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder registerIntentProvider(IntentProvider provider)
{
construct.intentProviders.add(provider);
return this;
}
/**
* Adds an intent provider to the start of the provider list (top-most priority)
* @param provider
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder registerIntentProviderStart(IntentProvider provider)
{
construct.intentProviders.add(0, provider);
return this;
}
/**
* Sets the intent provider list
* @param provider The providers to set (in order)
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder setIntentProvider(IntentProvider... provider)
{
construct.intentProviders.clear();
construct.intentProviders.addAll(Arrays.asList(provider));
return this;
}
/**
* Sets the default {@link com.cube.storm.ui.lib.factory.FileFactory} for the module
*
* @param fileFactory The new {@link com.cube.storm.ui.lib.factory.FileFactory}
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder fileFactory(FileFactory fileFactory)
{
construct.fileFactory = fileFactory;
return this;
}
/**
* Sets the default image loader configuration.
*
* Note: The ImageDownloader set in the builder is overriden by this method to allow the use
* of {@link #getUriResolvers()} to resolve the uris for loading images. Use {@link #registerUriResolver(String, com.cube.storm.util.lib.resolver.Resolver)}
* to register any additional custom uris you wish to override.
*
* @param configuration The new configuration for the image loader
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder imageLoaderConfiguration(ImageLoaderConfiguration.Builder configuration)
{
// Retain existing handlers if any exist
Map<String, SchemeHandler> handlers = null;
if (construct.imageLoader.isInited())
{
handlers = construct.imageLoader.getRegisteredSchemeHandlers();
construct.imageLoader.destroy();
}
construct.imageLoader.init(configuration.build());
if (handlers != null && handlers.size() > 0)
{
for (String key : handlers.keySet())
{
construct.imageLoader.registerSchemeHandler(key, handlers.get(key));
}
}
return this;
}
/**
* Sets the default {@link com.cube.storm.ui.data.ContentSize} for the module
*
* @param contentSize The new {@link com.cube.storm.ui.data.ContentSize}
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder contentSize(ContentSize contentSize)
{
construct.contentSize = contentSize;
return this;
}
/**
* Sets the default language srcUri
*
* @param languageUri The language uri of the default language
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder setDefaultLanguageUri(String languageUri)
{
construct.defaultLanguageUri = languageUri;
return this;
}
/**
* Sets the default {@link com.cube.storm.ui.lib.handler.LinkHandler} for the module
*
* @param linkHandler The new {@link com.cube.storm.ui.lib.handler.LinkHandler}
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder linkHandler(LinkHandler linkHandler)
{
construct.linkHandler = linkHandler;
return this;
}
/**
* Sets the default {@link com.cube.storm.ui.lib.parser.ViewBuilder} for the module
*
* @param viewBuilder The new {@link com.cube.storm.ui.lib.parser.ViewBuilder}
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder viewBuilder(ViewBuilder viewBuilder)
{
construct.viewBuilder = viewBuilder;
return this;
}
/**
* Sets the default {@link com.cube.storm.util.lib.processor.Processor} for the module
*
* @param textProcessor The new {@link com.cube.storm.util.lib.processor.Processor}
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder textProcessor(Processor<TextProperty, String> textProcessor)
{
construct.textProcessor = textProcessor;
return this;
}
/**
* Registers a view resolver for matching class name with model and viewholder. Use this method to set what class
* gets used for a specific view/model.
*
* @param viewName The name of the view to register
* @param resolver The view resolver class
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder registerViewResolver(String viewName, ViewResolver resolver)
{
construct.viewResolvers.put(viewName, resolver);
return this;
}
/**
* Registers a view resolver for matching class name with model and viewholder. Use this method to set what class
* gets used for a specific view/model.
*
* @param resolvers The map of view resolver classes
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder registerViewResolver(Map<String, ViewResolver> resolvers)
{
construct.viewResolvers.putAll(resolvers);
return this;
}
/**
* Registers a deserializer type for a class instance. Use this method to override what processor
* gets used for a specific view type.
*
* @param instanceClass The class to register for deserialization
* @param deserializer The processor class
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder registerType(Type instanceClass, ViewProcessor deserializer)
{
construct.viewProcessors.put(instanceClass, deserializer);
return this;
}
/**
* Registers a uri resolver to use in the {@link com.cube.storm.ui.lib.factory.FileFactory}
*
* @param protocol The string protocol to register
* @param resolver The resolver to use for the registered protocol
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder registerUriResolver(String protocol, Resolver resolver)
{
construct.uriResolvers.put(protocol, resolver);
if (!ImageLoader.getInstance().getRegisteredSchemeHandlers().containsKey(protocol))
{
ImageLoader.getInstance().registerSchemeHandler(protocol, new StormSchemeHandler());
}
return this;
}
/**
* Registers a uri resolvers
*
* @param resolvers The map of resolvers to register
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder registerUriResolver(Map<String, Resolver> resolvers)
{
construct.uriResolvers.putAll(resolvers);
for (String protocol : resolvers.keySet())
{
if (!ImageLoader.getInstance().getRegisteredSchemeHandlers().containsKey(protocol))
{
ImageLoader.getInstance().registerSchemeHandler(protocol, new StormSchemeHandler());
}
}
return this;
}
/**
* Registers an event hook class for various events
*
* @param hook The hook to register
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder registerEventHook(@NonNull EventHook hook)
{
construct.getEventHooks().add(hook);
return this;
}
/**
* Sets the default class to use for storm list adapter
*
* @param adapterClass The class to use for list adapters
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder viewAdapter(@NonNull Class<? extends StormListAdapter> adapterClass)
{
construct.viewAdapter = adapterClass;
return this;
}
/**
* Builds the final settings object and sets its instance. Use {@link #getInstance()} to retrieve the settings
* instance.
*
* @return The newly set {@link com.cube.storm.UiSettings} instance
*/
public UiSettings build()
{
if (construct.getIntentProviders().size() == 0)
{
registerIntentProvider(new DefaultIntentProvider());
}
return (UiSettings.instance = construct);
}
}
}
|
package ceylon.language;
import com.redhat.ceylon.compiler.java.metadata.Ceylon;
import com.redhat.ceylon.compiler.java.metadata.Object;
@Ceylon(major = 6)
@Object
public final class operatingSystem_ {
private static final operatingSystem_ value = new operatingSystem_();
public static operatingSystem_ get_() {
return value;
}
private final java.lang.String newline = System.lineSeparator();
private final java.lang.String fileSeparator = System.getProperty("file.separator");
private final java.lang.String pathSeparator = System.getProperty("path.separator");
private operatingSystem_() {
}
public java.lang.String getName() {
java.lang.String os = System.getProperty("os.name").toLowerCase();
if (os.indexOf("win") >= 0) {
return "windows";
} else if (os.indexOf("mac") >= 0) {
return "mac";
} else if (os.indexOf("linux") >= 0) {
return "linux";
} else if (os.indexOf("nix") >= 0 || os.indexOf("sunos") >= 0) {
return "unix";
} else {
return "other";
}
}
public java.lang.String getVersion() {
return System.getProperty("os.version");
}
public java.lang.String getNewline() {
return newline;
}
public java.lang.String getFileSeparator() {
return fileSeparator;
}
public java.lang.String getPathSeparator() {
return pathSeparator;
}
@Override
public java.lang.String toString() {
return "operating system [" + getName() + " / " + getVersion() + "]";
}
}
|
import java.io.*;
import java.net.*;
import java.util.*;
public class districtServerThread extends Thread {
private long FIVE_SECONDS = 5000;
protected DatagramSocket socket = null;
protected BufferedReader in = null;
protected boolean moreQuotes = true;
public districtServerThread() throws IOException {
this("MulticastServerThread");
}
public districtServerThread(String name) throws IOException {
super(name);
socket = new DatagramSocket(4445);
}
public void run() {
while (moreQuotes) {
// construct quote
String dString = null;
dString = new Date().toString();
enviarU(dString, "230.0.0.1", socket);
// sleep for a while
try {
sleep((long)(Math.random() * FIVE_SECONDS));
} catch (InterruptedException e) { }
}
socket.close();
}
public void enviarU(String mensaje, String ip_destino, DatagramSocket socket){
try{
byte[] buf = new byte[256];
InetAddress address = InetAddress.getByName(ip_destino);
buf = mensaje.getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4446); //viene con puerto de defecto
socket.send(packet);
}catch(IOException e) {
System.out.println("ilprob");
e.printStackTrace();
}
}
}
|
package com.orbekk.same;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class is thread-safe.
*/
public class State {
private Logger logger = LoggerFactory.getLogger(getClass());
private Map<String, Component> state = new HashMap<String, Component>();
private ObjectMapper mapper = new ObjectMapper();
private Set<String> updatedComponents = new TreeSet<String>();
public static final String PARTICIPANTS = ".participants0";
public State(String networkName) {
update(".networkName", networkName, 1);
updateFromObject(".participants", new ArrayList<String>(), 1);
updateFromObject(PARTICIPANTS, new ArrayList<String>(), 1);
}
public State(State other) {
state.putAll(other.state);
}
public synchronized void clear() {
updatedComponents.clear();
state.clear();
}
public synchronized void forceUpdate(String componentName,
String data, long revision) {
Component oldComponent = state.get(componentName);
Component newComponent = new Component(componentName, revision, data);
state.put(componentName, newComponent);
updatedComponents.add(componentName);
}
public synchronized boolean update(String componentName, String data,
long revision) {
Component component = null;
if (!state.containsKey(componentName)) {
component = new Component("", 0, "");
} else {
component = state.get(componentName);
}
if (revision > component.getRevision()) {
Component oldComponent = new Component(component);
component.setName(componentName);
component.setRevision(revision);
component.setData(data);
state.put(componentName, component);
updatedComponents.add(componentName);
return true;
} else {
return false;
}
}
/**
* Get a copy of a component.
*/
public Component getComponent(String name) {
Component component = state.get(name);
if (component != null) {
return new Component(component);
} else {
return null;
}
}
public String getDataOf(String componentName) {
Component component = state.get(componentName);
if (component != null) {
return component.getData();
} else {
return null;
}
}
public long getRevision(String componentName) {
Component component = state.get(componentName);
if (component != null) {
return component.getRevision();
} else {
logger.warn("getRevision: Unknown component {}. Returning 0",
componentName);
return 0;
}
}
/**
* Parses a JSON value using Jackson ObjectMapper.
*/
public <T> T getParsedData(String componentName, TypeReference<T> type) {
String data = getDataOf(componentName);
if (data != null) {
try {
return mapper.readValue(data, type);
} catch (JsonParseException e) {
logger.warn("Failed to parse value {} ", data);
logger.warn("Parse exception: {}", e);
} catch (JsonMappingException e) {
logger.warn("Failed to parse value {} ", data);
logger.warn("Parse exception: {}", e);
} catch (IOException e) {
logger.warn("Failed to parse value {} ", data);
logger.warn("Parse exception: {}", e);
}
}
return null;
}
public List<String> getList(String componentName) {
return getParsedData(componentName,
new TypeReference<List<String>>(){});
}
public boolean updateFromObject(String componentName, Object data, long revision) {
String dataS;
try {
dataS = mapper.writeValueAsString(data);
return update(componentName, dataS, revision);
} catch (JsonGenerationException e) {
logger.warn("Failed to convert to JSON: {} ", data);
logger.warn("Parse exception: {}", e);
return false;
} catch (JsonMappingException e) {
logger.warn("Failed to convert to JSON: {} ", data);
logger.warn("Parse exception: {}", e);
return false;
} catch (IOException e) {
logger.warn("Failed to convert to JSON: {} ", data);
logger.warn("Parse exception: {}", e);
return false;
}
}
/**
* Pretty print a component.
*/
public String show(String componentName) {
return componentName + ": " + state.get(componentName);
}
/**
* Returns a list of all the components in this State.
*
* This method is thread-safe, and returns a deep copy.
*/
public synchronized List<Component> getComponents() {
ArrayList<Component> list = new ArrayList<Component>();
for (Component component : state.values()) {
list.add(new Component(component));
}
return list;
}
public synchronized List<Component> getAndClearUpdatedComponents() {
List<Component> components = new ArrayList<Component>();
for (String name : updatedComponents) {
components.add(state.get(name));
}
updatedComponents.clear();
return components;
}
public static class Component {
private String name;
private long revision;
private String data;
/**
* Copy constructor.
*/
public Component(Component other) {
this.name = other.name;
this.revision = other.revision;
this.data = other.data;
}
public Component(String name, long revision, String data) {
this.name = name;
this.revision = revision;
this.data = data;
}
public long getRevision() {
return revision;
}
public void setRevision(long revision) {
this.revision = revision;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override public String toString() {
return "[" + this.name + ": " + this.data + "@" + revision + "]";
}
@Override public boolean equals(Object other) {
if (!(other instanceof Component)) {
return false;
}
Component o = (Component)other;
return name.equals(o.name) && data.equals(o.data) &&
revision == o.revision;
}
}
@Override public String toString() {
StringBuilder output = new StringBuilder();
output.append("State(\n");
for (Component c : getComponents()) {
output.append(" " + c.toString() + "\n");
}
output.append(")");
return output.toString();
}
@Override public boolean equals(Object other) {
if (!(other instanceof State)) {
return false;
}
State o = (State)other;
return state.equals(o.state);
}
}
|
import com.goironbox.client.*;
import java.io.*;
import java.util.List;
public class IronBoxDownloadReadyFilesCmdLine {
private static ApiVersion API_VERSION = ApiVersion.LATEST;
private static boolean verifySSLCert = true;
private static boolean verbose = true;
// These will be picked up as command lines parameters
private static String email = "<your_email>";
private static String password = "<your_password>";
private static long containerID = 100000;
public static void main(String args[]) throws Exception {
try {
// Verify that parameters were specified correctly
if (args.length < 3) {
throw new Exception("Usage: IronBoxDownloadReadyFilesCmdLine <containerID> <email> <password>");
}
containerID = Long.valueOf(args[0]).longValue();
email = args[1];
password = args[2];
// Create a new IronBox client object and set
// any optional parameters
IronBoxClient ibc = new IronBoxClient(
email, password, EntityType.EMAIL_ADDRESS,
API_VERSION, ContentFormat.JSON,
verbose, verifySSLCert
);
// Optional, you can check to see that the API server is
// responding before execution
if (!ibc.ping()) {
throw new Exception("API server not responding");
}
else {
System.out.println("+ API server is responding");
}
// Server is responding, read the contents of the container and then
// download the contents of it locally
System.out.println("+ Reading container");
List<BlobInfo> ReadyFiles = ibc.getContainerBlobInfoListByState(containerID, BlobState.READY);
for (BlobInfo blobInfo : ReadyFiles) {
File f = new File(blobInfo.getBlobName());
ibc.downloadBlobFromContainer(containerID, blobInfo.getBlobID(), f);
}
}
catch (Exception e) {
// Error encountered
System.out.println("- " + e.getMessage());
}
}
}
|
package cgeo.geocaching.files;
import cgeo.geocaching.Intents;
import cgeo.geocaching.R;
import cgeo.geocaching.activity.AbstractListActivity;
import cgeo.geocaching.activity.ActivityMixin;
import org.apache.commons.lang3.StringUtils;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Dialog for choosing a file or directory.
*/
public class SimpleDirChooser extends AbstractListActivity {
public static final String EXTRA_CHOOSE_FOR_WRITING = "chooseForWriting";
private static final String PARENT_DIR = ".. ";
private File currentDir;
private FileArrayAdapter adapter;
private Button okButton = null;
private int lastPosition = -1;
private boolean chooseForWriting = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Bundle extras = getIntent().getExtras();
currentDir = dirContaining(extras.getString(Intents.EXTRA_START_DIR));
chooseForWriting = extras.getBoolean(SimpleDirChooser.EXTRA_CHOOSE_FOR_WRITING, false);
ActivityMixin.setTheme(this);
setContentView(R.layout.simple_dir_chooser);
fill(currentDir);
okButton = (Button) findViewById(R.id.simple_dir_chooser_ok);
okButton.setEnabled(false);
okButton.setVisibility(View.INVISIBLE);
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setResult(RESULT_OK, new Intent()
.setData(Uri.fromFile(new File(currentDir, adapter.getItem(lastPosition).getName()))));
finish();
}
});
Button cancelButton = (Button) findViewById(R.id.simple_dir_chooser_cancel);
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
setResult(RESULT_CANCELED, intent);
finish();
}
});
}
/**
* Return the directory containing a given path, or a sensible default.
*
* @param path the path to get the enclosing directory from, can be null or empty
* @return the directory containing <code>path</code>, or a sensible default if none
*/
private static File dirContaining(final String path) {
return StringUtils.contains(path, File.separatorChar) ?
new File(StringUtils.substringBeforeLast(path, Character.toString(File.separatorChar))) :
Environment.getExternalStorageDirectory();
}
private void fill(File dir) {
lastPosition = -1;
EditText path = (EditText) findViewById(R.id.simple_dir_chooser_path);
path.setText(this.getResources().getString(R.string.simple_dir_chooser_current_path) + " " + dir.getAbsolutePath());
final File[] dirs = dir.listFiles(new DirOnlyFilenameFilter());
List<Option> listDirs = new ArrayList<Option>();
try {
for (File currentDir : dirs) {
listDirs.add(new Option(currentDir.getName(), currentDir.getAbsolutePath(), currentDir.canWrite()));
}
} catch (RuntimeException e) {
}
Collections.sort(listDirs);
if (dir.getParent() != null) {
listDirs.add(0, new Option(PARENT_DIR, dir.getParent(), false));
}
this.adapter = new FileArrayAdapter(this, R.layout.simple_dir_item, listDirs);
this.setListAdapter(adapter);
}
public class FileArrayAdapter extends ArrayAdapter<Option> {
private Context context;
private int id;
private List<Option> items;
public FileArrayAdapter(Context context, int simpleDirItemResId, List<Option> objects) {
super(context, simpleDirItemResId, objects);
this.context = context;
this.id = simpleDirItemResId;
this.items = objects;
}
@Override
public Option getItem(int index) {
return items.get(index);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(id, null);
}
final Option option = items.get(position);
if (option != null) {
TextView t1 = (TextView) v.findViewById(R.id.TextView01);
if (t1 != null) {
t1.setOnClickListener(new OnTextViewClickListener(position));
t1.setText(option.getName());
}
CheckBox check = (CheckBox) v.findViewById(R.id.CheckBox);
if (check != null) {
if (!chooseForWriting || option.isWriteable()) {
check.setOnClickListener(new OnCheckBoxClickListener(position));
check.setChecked(option.isChecked());
check.setEnabled(true);
} else {
check.setEnabled(false);
}
}
}
return v;
}
}
public class OnTextViewClickListener implements OnClickListener {
private int position;
OnTextViewClickListener(int position) {
this.position = position;
}
@Override
public void onClick(View arg0) {
Option option = adapter.getItem(position);
if (option.getName().equals(PARENT_DIR)) {
currentDir = new File(option.getPath());
fill(currentDir);
} else {
File dir = new File(option.getPath());
if (dir.list(new DirOnlyFilenameFilter()).length > 0) {
currentDir = dir;
fill(currentDir);
}
}
}
}
public class OnCheckBoxClickListener implements OnClickListener {
private int position;
OnCheckBoxClickListener(int position) {
this.position = position;
}
@Override
public void onClick(View arg0) {
Option lastOption = (lastPosition > -1) ? adapter.getItem(lastPosition) : null;
Option currentOption = adapter.getItem(position);
if (lastOption != null) {
lastOption.setChecked(false);
}
if (currentOption != lastOption) {
currentOption.setChecked(true);
lastPosition = position;
} else {
lastPosition = -1;
}
final boolean enabled = currentOption.isChecked() && !currentOption.getName().equals(PARENT_DIR);
okButton.setEnabled(enabled);
okButton.setVisibility(enabled ? View.VISIBLE : View.INVISIBLE);
adapter.notifyDataSetChanged();
}
}
/**
* Note: this class has a natural ordering that is inconsistent with equals.
*/
public static class Option implements Comparable<Option> {
private final String name;
private final String path;
private boolean checked = false;
private boolean writeable = false;
public Option(String name, String path, boolean writeable) {
this.name = name;
this.path = path;
this.writeable = writeable;
}
public String getName() {
return name;
}
public String getPath() {
return path;
}
public boolean isChecked() {
return this.checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public boolean isWriteable() {
return writeable;
}
@Override
public int compareTo(Option other) {
if (other != null && this.name != null) {
return String.CASE_INSENSITIVE_ORDER.compare(this.name, other.getName());
}
throw new IllegalArgumentException("");
}
}
public static class DirOnlyFilenameFilter implements FilenameFilter {
@Override
public boolean accept(File dir, String filename) {
File file = new File(dir, filename);
return file.isDirectory() && file.canRead();
}
}
}
|
package net.coobird.thumbnailator;
import static org.junit.Assert.*;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.imageio.ImageIO;
import net.coobird.thumbnailator.builders.BufferedImageBuilder;
import net.coobird.thumbnailator.builders.ThumbnailParameterBuilder;
import net.coobird.thumbnailator.name.Rename;
import net.coobird.thumbnailator.resizers.DefaultResizerFactory;
import net.coobird.thumbnailator.resizers.ResizerFactory;
import net.coobird.thumbnailator.tasks.SourceSinkThumbnailTask;
import net.coobird.thumbnailator.tasks.UnsupportedFormatException;
import net.coobird.thumbnailator.tasks.io.BufferedImageSink;
import net.coobird.thumbnailator.tasks.io.BufferedImageSource;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
/**
* Unit tests for the {@link Thumbnailator} class.
*
* @author coobird
*
*/
@SuppressWarnings("deprecation")
public class ThumbnailatorTest
{
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnailCollections_negativeWidth() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png")
);
Thumbnailator.createThumbnailsAsCollection(
files,
Rename.PREFIX_DOT_THUMBNAIL,
-42,
50
);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnailCollections_negativeHeight() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png")
);
Thumbnailator.createThumbnailsAsCollection(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
-42
);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnailCollections_negativeWidthAndHeight() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png")
);
Thumbnailator.createThumbnailsAsCollection(
files,
Rename.PREFIX_DOT_THUMBNAIL,
-42,
-42
);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct, except
* a) The Collection is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnailCollections_nullCollection() throws IOException
{
try
{
Thumbnailator.createThumbnailsAsCollection(
null,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
fail();
}
catch (NullPointerException e)
{
assertEquals("Collection of Files is null.", e.getMessage());
throw e;
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct, except
* a) The Rename is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnailCollections_nullRename() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png"),
new File("test-resources/Thumbnailator/grid.bmp")
);
try
{
Thumbnailator.createThumbnailsAsCollection(
files,
null,
50,
50
);
fail();
}
catch (NullPointerException e)
{
assertEquals("Rename is null.", e.getMessage());
throw e;
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* a) The Collection is an empty List.
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnailCollections_NoErrors_EmptyList() throws IOException
{
/*
* The files to make thumbnails of -- nothing!
*/
List<File> files = Collections.emptyList();
Collection<File> resultingFiles =
Thumbnailator.createThumbnailsAsCollection(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
assertTrue(resultingFiles.isEmpty());
}
/**
* Test for
* {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* a) The Collection is an empty Set.
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnailCollections_NoErrors_EmptySet() throws IOException
{
/*
* The files to make thumbnails of -- nothing!
*/
Set<File> files = Collections.emptySet();
Thumbnailator.createThumbnailsAsCollection(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
}
/**
* Test for
* {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* 2) All data can be processed correctly.
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnailCollections_NoErrors() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png")
);
/*
* Used to perform clean up.
*/
for (File f : files)
{
String fileName = f.getName();
String newFileName =
Rename.PREFIX_DOT_THUMBNAIL.apply(fileName, null);
new File(f.getParent(), newFileName).deleteOnExit();
}
Collection<File> resultingFiles =
Thumbnailator.createThumbnailsAsCollection(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
/*
* Perform post-execution checks.
*/
Iterator<File> iter = resultingFiles.iterator();
BufferedImage img0 = ImageIO.read(iter.next());
assertEquals(50, img0.getWidth());
assertEquals(50, img0.getHeight());
BufferedImage img1 = ImageIO.read(iter.next());
assertEquals(50, img1.getWidth());
assertEquals(50, img1.getHeight());
assertTrue(!iter.hasNext());
}
/**
* Test for
* {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* 2) A file that was specified does not exist
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
*
* @throws IOException
*/
@Test(expected=IOException.class)
public void testCreateThumbnailCollections_ErrorDuringProcessing_FileNotFound() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png"),
new File("test-resources/Thumbnailator/grid.bmp"),
new File("test-resources/Thumbnailator/filenotfound.gif")
);
/*
* Used to perform clean up.
*/
for (File f : files)
{
String fileName = f.getName();
String newFileName =
Rename.PREFIX_DOT_THUMBNAIL.apply(fileName, null);
new File(f.getParent(), newFileName).deleteOnExit();
}
Thumbnailator.createThumbnailsAsCollection(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* 2) The thumbnail cannot be written. (unsupported format)
*
* Expected outcome is,
*
* 1) Processing will stop with an UnsupportedFormatException.
*
* @throws IOException
*/
@Test(expected=UnsupportedFormatException.class)
public void testCreateThumbnailCollections_ErrorDuringProcessing_CantWriteThumbnail() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png"),
new File("test-resources/Thumbnailator/grid.bmp"),
new File("test-resources/Thumbnailator/grid.gif")
);
// This will force a UnsupportedFormatException when trying to output
// a thumbnail whose source was a gif file.
Rename brokenRenamer = new Rename() {
@Override
public String apply(String name, ThumbnailParameter param)
{
if (name.endsWith(".gif"))
{
return "thumbnail." + name + ".foobar";
}
return "thumbnail." + name;
}
};
/*
* Used to perform clean up.
*/
for (File f : files)
{
String fileName = f.getName();
String newFileName =
brokenRenamer.apply(fileName, null);
new File(f.getParent(), newFileName).deleteOnExit();
}
Thumbnailator.createThumbnailsAsCollection(
files,
brokenRenamer,
50,
50
);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* 2) All data can be processed correctly.
* 3) The Collection is a List of a class extending File.
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnailCollections_NoErrors_CollectionExtendsFile() throws IOException
{
class File2 extends File
{
private static final long serialVersionUID = 1L;
public File2(String pathname)
{
super(pathname);
}
}
/*
* The files to make thumbnails of.
*/
List<File2> files = Arrays.asList(
new File2("test-resources/Thumbnailator/grid.jpg"),
new File2("test-resources/Thumbnailator/grid.png")
);
/*
* Used to perform clean up.
*/
for (File f : files)
{
String fileName = f.getName();
String newFileName =
Rename.PREFIX_DOT_THUMBNAIL.apply(fileName, null);
new File(f.getParent(), newFileName).deleteOnExit();
}
Collection<File> resultingFiles =
Thumbnailator.createThumbnailsAsCollection(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
/*
* Perform post-execution checks.
*/
Iterator<File> iter = resultingFiles.iterator();
BufferedImage img0 = ImageIO.read(iter.next());
assertEquals(50, img0.getWidth());
assertEquals(50, img0.getHeight());
BufferedImage img1 = ImageIO.read(iter.next());
assertEquals(50, img1.getWidth());
assertEquals(50, img1.getHeight());
assertTrue(!iter.hasNext());
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnails_negativeWidth() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png")
);
Thumbnailator.createThumbnails(
files,
Rename.PREFIX_DOT_THUMBNAIL,
-42,
50
);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnails_negativeHeight() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png")
);
Thumbnailator.createThumbnails(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
-42
);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnails_negativeWidthAndHeight() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png")
);
Thumbnailator.createThumbnails(
files,
Rename.PREFIX_DOT_THUMBNAIL,
-42,
-42
);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnails(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct, except
* a) The Collection is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnails_nullCollection() throws IOException
{
try
{
Thumbnailator.createThumbnails(
null,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
fail();
}
catch (NullPointerException e)
{
assertEquals("Collection of Files is null.", e.getMessage());
throw e;
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnails(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct, except
* a) The Rename is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnails_nullRename() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png"),
new File("test-resources/Thumbnailator/grid.bmp")
);
try
{
Thumbnailator.createThumbnails(
files,
null,
50,
50
);
fail();
}
catch (NullPointerException e)
{
assertEquals("Rename is null.", e.getMessage());
throw e;
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnails(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* a) The Collection is an empty List.
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnails_NoErrors_EmptyList() throws IOException
{
/*
* The files to make thumbnails of -- nothing!
*/
List<File> files = Collections.emptyList();
Thumbnailator.createThumbnails(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
}
/**
* Test for
* {@link Thumbnailator#createThumbnails(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* a) The Collection is an empty Set.
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnails_NoErrors_EmptySet() throws IOException
{
/*
* The files to make thumbnails of -- nothing!
*/
Set<File> files = Collections.emptySet();
Thumbnailator.createThumbnails(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
}
/**
* Test for
* {@link Thumbnailator#createThumbnails(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* 2) All data can be processed correctly.
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnails_NoErrors() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png")
);
/*
* Used to perform clean up.
*/
for (File f : files)
{
String fileName = f.getName();
String newFileName =
Rename.PREFIX_DOT_THUMBNAIL.apply(fileName, null);
new File(f.getParent(), newFileName).deleteOnExit();
}
Thumbnailator.createThumbnails(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
/*
* Perform post-execution checks.
*/
BufferedImage img0 =
ImageIO.read(new File("test-resources/Thumbnailator/thumbnail.grid.jpg"));
assertEquals(50, img0.getWidth());
assertEquals(50, img0.getHeight());
BufferedImage img1 =
ImageIO.read(new File("test-resources/Thumbnailator/thumbnail.grid.png"));
assertEquals(50, img1.getWidth());
assertEquals(50, img1.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnails(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* 2) A file that was specified does not exist
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
*
* @throws IOException
*/
@Test(expected=IOException.class)
public void testCreateThumbnails_ErrorDuringProcessing_FileNotFound() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png"),
new File("test-resources/Thumbnailator/grid.bmp"),
new File("test-resources/Thumbnailator/filenotfound.gif")
);
/*
* Used to perform clean up.
*/
for (File f : files)
{
String fileName = f.getName();
String newFileName =
Rename.PREFIX_DOT_THUMBNAIL.apply(fileName, null);
new File(f.getParent(), newFileName).deleteOnExit();
}
Thumbnailator.createThumbnails(
files,
Rename.PREFIX_DOT_THUMBNAIL,
50,
50
);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnails(Collection, Rename, int, int)}
* where,
*
* 1) All parameters are correct
* 2) The thumbnail cannot be written. (unsupported format)
*
* Expected outcome is,
*
* 1) Processing will stop with an UnsupportedFormatException.
*
* @throws IOException
*/
@Test(expected=UnsupportedFormatException.class)
public void testCreateThumbnails_ErrorDuringProcessing_CantWriteThumbnail() throws IOException
{
/*
* The files to make thumbnails of.
*/
List<File> files = Arrays.asList(
new File("test-resources/Thumbnailator/grid.jpg"),
new File("test-resources/Thumbnailator/grid.png"),
new File("test-resources/Thumbnailator/grid.bmp"),
new File("test-resources/Thumbnailator/grid.gif")
);
// This will force a UnsupportedFormatException when trying to output
// a thumbnail whose source was a gif file.
Rename brokenRenamer = new Rename() {
@Override
public String apply(String name, ThumbnailParameter param)
{
if (name.endsWith(".gif"))
{
return "thumbnail." + name + ".foobar";
}
return "thumbnail." + name;
}
};
/*
* Used to perform clean up.
*/
for (File f : files)
{
String fileName = f.getName();
String newFileName =
brokenRenamer.apply(fileName, null);
new File(f.getParent(), newFileName).deleteOnExit();
}
Thumbnailator.createThumbnails(
files,
brokenRenamer,
50,
50
);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)}
* where,
*
* 1) InputStream is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnail_IOII_nullIS() throws IOException
{
/*
* Actual test
*/
InputStream is = null;
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, 50, 50);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)}
* where,
*
* 1) OutputStream is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnail_IOII_nullOS() throws IOException
{
/*
* Actual test
*/
byte[] bytes = makeImageData("jpg", 200, 200);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = null;
Thumbnailator.createThumbnail(is, os, 50, 50);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)}
* where,
*
* 1) InputStream is null
* 2) OutputStream is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnail_IOII_nullISnullOS() throws IOException
{
Thumbnailator.createThumbnail((InputStream)null, null, 50, 50);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_IOII_negativeWidth() throws IOException
{
/*
* Actual test
*/
byte[] bytes = makeImageData("jpg", 200, 200);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, -42, 50);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_IOII_negativeHeight() throws IOException
{
/*
* Actual test
*/
byte[] bytes = makeImageData("jpg", 200, 200);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, 50, -42);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_IOII_negativeWidthAndHeight() throws IOException
{
/*
* Actual test
*/
byte[] bytes = makeImageData("jpg", 200, 200);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, -42, -42);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input data is a JPEG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOII_Jpg() throws IOException
{
/*
* Actual test
*/
byte[] bytes = makeImageData("jpg", 200, 200);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage thumb = ImageIO.read(thumbIs);
assertEquals(50, thumb.getWidth());
assertEquals(50, thumb.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input data is a PNG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOII_Png() throws IOException
{
/*
* Actual test
*/
byte[] bytes = makeImageData("png", 200, 200);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage thumb = ImageIO.read(thumbIs);
assertEquals(50, thumb.getWidth());
assertEquals(50, thumb.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input data is a BMP image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOII_Bmp() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[40054];
new FileInputStream("test-resources/Thumbnailator/grid.bmp").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage thumb = ImageIO.read(thumbIs);
assertEquals(50, thumb.getWidth());
assertEquals(50, thumb.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input data is a BMP image
* -> writing to a BMP is not supported by default.
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
* On Java 6 and later, this should pass, as it contains a GIF writer.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOII_Gif() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[492];
new FileInputStream("test-resources/Thumbnailator/grid.gif").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try
{
Thumbnailator.createThumbnail(is, os, 50, 50);
// This case should pass on Java 6 and later, as those JREs have a
// GIF writer.
if (System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
}
catch (UnsupportedFormatException e)
{
// This case should pass on Java 6 and later.
if (!System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
assertEquals("No suitable ImageWriter found for gif.", e.getMessage());
assertEquals("gif", e.getFormatName());
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)}
* where,
*
* 1) InputStream throws an IOException during read.
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
*
* @throws IOException
*/
@Test(expected=IOException.class)
public void testCreateThumbnail_IOII_IOExceptionFromIS() throws IOException
{
/*
* Actual test
*/
InputStream is = mock(InputStream.class);
doThrow(new IOException("read error!")).when(is).read();
doThrow(new IOException("read error!")).when(is).read((byte[])any());
doThrow(new IOException("read error!")).when(is).read((byte[])any(), anyInt(), anyInt());
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, 50, 50);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)}
* where,
*
* 1) OutputStream throws an IOException during read.
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
*
* @throws IOException
*/
@Test(expected=IOException.class)
public void testCreateThumbnail_IOII_IOExceptionFromOS() throws IOException
{
/*
* Actual test
*/
byte[] bytes = makeImageData("png", 200, 200);
InputStream is = new ByteArrayInputStream(bytes);
OutputStream os = mock(OutputStream.class);
doThrow(new IOException("write error!")).when(os).write(anyInt());
doThrow(new IOException("write error!")).when(os).write((byte[])any());
doThrow(new IOException("write error!")).when(os).write((byte[])any(), anyInt(), anyInt());
Thumbnailator.createThumbnail(is, os, 50, 50);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a JPEG image
* b) Output file is a PNG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOSII_Transcoding_Jpeg_Png() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[4602];
new FileInputStream("test-resources/Thumbnailator/grid.jpg").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, "png", 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage img = ImageIO.read(thumbIs);
assertEquals(
"png",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(
new ByteArrayInputStream(os.toByteArray()))
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a JPEG image
* b) Output file is a BMP image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOSII_Transcoding_Jpeg_Bmp() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[4602];
new FileInputStream("test-resources/Thumbnailator/grid.jpg").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, "bmp", 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage img = ImageIO.read(thumbIs);
assertEquals(
"bmp",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(
new ByteArrayInputStream(os.toByteArray()))
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
@Test
public void testCreateThumbnail_IOSII_Transcoding_Jpeg_Gif() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[4602];
new FileInputStream("test-resources/Thumbnailator/grid.jpg").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try
{
Thumbnailator.createThumbnail(is, os, "gif", 50, 50);
// This case should pass on Java 6 and later, as those JREs have a
// GIF writer.
if (System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
}
catch (IllegalArgumentException e)
{
// This case should pass on Java 6 and later.
if (!System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
assertTrue(e.getMessage().contains("gif"));
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a PNG image
* b) Output file is a JPEG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOSII_Transcoding_Png_Jpeg() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[287];
new FileInputStream("test-resources/Thumbnailator/grid.png").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, "jpg", 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage img = ImageIO.read(thumbIs);
assertEquals(
"JPEG",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(
new ByteArrayInputStream(os.toByteArray()))
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a PNG image
* b) Output file is a BMP image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOSII_Transcoding_Png_Bmp() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[287];
new FileInputStream("test-resources/Thumbnailator/grid.png").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, "bmp", 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage img = ImageIO.read(thumbIs);
assertEquals(
"bmp",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(
new ByteArrayInputStream(os.toByteArray()))
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
@Test
public void testCreateThumbnail_IOSII_Transcoding_Png_Gif() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[287];
new FileInputStream("test-resources/Thumbnailator/grid.png").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try
{
Thumbnailator.createThumbnail(is, os, "gif", 50, 50);
// This case should pass on Java 6 and later, as those JREs have a
// GIF writer.
if (System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
}
catch (IllegalArgumentException e)
{
// This case should pass on Java 6 and later.
if (!System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
assertTrue(e.getMessage().contains("gif"));
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a BMP image
* b) Output file is a PNG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOSII_Transcoding_Bmp_Png() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[40054];
new FileInputStream("test-resources/Thumbnailator/grid.bmp").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, "png", 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage img = ImageIO.read(thumbIs);
assertEquals(
"png",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(
new ByteArrayInputStream(os.toByteArray()))
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a BMP image
* b) Output file is a JPEG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOSII_Transcoding_Bmp_Jpeg() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[40054];
new FileInputStream("test-resources/Thumbnailator/grid.bmp").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, "jpg", 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage img = ImageIO.read(thumbIs);
assertEquals(
"JPEG",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(
new ByteArrayInputStream(os.toByteArray()))
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
@Test
public void testCreateThumbnail_IOSII_Transcoding_Bmp_Gif() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[40054];
new FileInputStream("test-resources/Thumbnailator/grid.bmp").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try
{
Thumbnailator.createThumbnail(is, os, "gif", 50, 50);
// This case should pass on Java 6 and later, as those JREs have a
// GIF writer.
if (System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
}
catch (IllegalArgumentException e)
{
// This case should pass on Java 6 and later.
if (!System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
assertTrue(e.getMessage().contains("gif"));
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a GIF image
* b) Output file is a PNG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOSII_Transcoding_Gif_Png() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[492];
new FileInputStream("test-resources/Thumbnailator/grid.gif").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, "png", 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage img = ImageIO.read(thumbIs);
assertEquals(
"png",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(
new ByteArrayInputStream(os.toByteArray()))
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a GIF image
* b) Output file is a JPEG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOSII_Transcoding_Gif_Jpeg() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[492];
new FileInputStream("test-resources/Thumbnailator/grid.gif").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, "jpg", 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage img = ImageIO.read(thumbIs);
assertEquals(
"JPEG",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(
new ByteArrayInputStream(os.toByteArray()))
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a GIF image
* b) Output file is a BMP image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_IOSII_Transcoding_Gif_Bmp() throws IOException
{
/*
* Actual test
*/
byte[] bytes = new byte[492];
new FileInputStream("test-resources/Thumbnailator/grid.gif").read(bytes);
InputStream is = new ByteArrayInputStream(bytes);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, "bmp", 50, 50);
/*
* Post-test checks
*/
InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage img = ImageIO.read(thumbIs);
assertEquals(
"bmp",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(
new ByteArrayInputStream(os.toByteArray()))
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) InputStream throws an IOException during read.
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
*
* @throws IOException
*/
@Test(expected=IOException.class)
public void testCreateThumbnail_IOSII_IOExceptionFromIS() throws IOException
{
/*
* Actual test
*/
InputStream is = mock(InputStream.class);
doThrow(new IOException("read error!")).when(is).read();
doThrow(new IOException("read error!")).when(is).read((byte[])any());
doThrow(new IOException("read error!")).when(is).read((byte[])any(), anyInt(), anyInt());
ByteArrayOutputStream os = new ByteArrayOutputStream();
Thumbnailator.createThumbnail(is, os, "png", 50, 50);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)}
* where,
*
* 1) OutputStream throws an IOException during read.
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
*
* @throws IOException
*/
@Test(expected=IOException.class)
public void testCreateThumbnail_IOSII_IOExceptionFromOS() throws IOException
{
/*
* Actual test
*/
byte[] bytes = makeImageData("png", 200, 200);
InputStream is = new ByteArrayInputStream(bytes);
OutputStream os = mock(OutputStream.class);
doThrow(new IOException("write error!")).when(os).write(anyInt());
doThrow(new IOException("write error!")).when(os).write((byte[])any());
doThrow(new IOException("write error!")).when(os).write((byte[])any(), anyInt(), anyInt());
Thumbnailator.createThumbnail(is, os, "png", 50, 50);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Input File is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnail_FFII_nullInputFile() throws IOException
{
/*
* Actual test
*/
File inputFile = null;
File outputFile = new File("bar.jpg");
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Output File is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnail_FFII_nullOutputFile() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("foo.jpg");
File outputFile = null;
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Input File is null
* 2) Output File is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnail_FFII_nullInputAndOutputFiles() throws IOException
{
Thumbnailator.createThumbnail((File)null, null, 50, 50);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_FFII_negativeWidth() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("foo.jpg");
File outputFile = new File("bar.jpg");
Thumbnailator.createThumbnail(inputFile, outputFile, -42, 50);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_FFII_negativeHeight() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("foo.jpg");
File outputFile = new File("bar.jpg");
Thumbnailator.createThumbnail(inputFile, outputFile, 50, -42);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_FFII_negativeWidthAndHeight() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("foo.jpg");
File outputFile = new File("bar.jpg");
Thumbnailator.createThumbnail(inputFile, outputFile, -42, -42);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input file is a JPEG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Jpg() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.jpg");
File outputFile = new File("test-resources/Thumbnailator/tmp.jpg");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input file is a PNG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Png() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.png");
File outputFile = new File("test-resources/Thumbnailator/tmp.png");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input data is a BMP image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Bmp() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.bmp");
File outputFile = new File("test-resources/Thumbnailator/tmp.bmp");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input data is a GIF image
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
* On Java 6 and later, this should pass, as it contains a GIF writer.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Gif() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.gif");
File outputFile = new File("test-resources/Thumbnailator/tmp.gif");
outputFile.deleteOnExit();
try
{
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
// This case should pass on Java 6 and later, as those JREs have a
// GIF writer.
if (System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
}
catch (UnsupportedFormatException e)
{
// This case should pass on Java 6 and later.
if (!System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
assertEquals("No suitable ImageWriter found for gif.", e.getMessage());
assertEquals("gif", e.getFormatName());
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a JPEG image
* b) Output file is a PNG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Jpeg_Png() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.jpg");
File outputFile = File.createTempFile("thumbnailator-testing-", ".png");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(
"png",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(outputFile)
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a JPEG image
* b) Output file is a BMP image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Jpeg_Bmp() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.jpg");
File outputFile = File.createTempFile("thumbnailator-testing-", ".bmp");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(
"bmp",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(outputFile)
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a JPEG image
* b) Output file is a GIF image
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
* On Java 6 and later, this should pass, as it contains a GIF writer.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Jpeg_Gif() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.jpg");
File outputFile = File.createTempFile("thumbnailator-testing-", ".gif");
outputFile.deleteOnExit();
try
{
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
// This case should pass on Java 6 and later, as those JREs have a
// GIF writer.
if (System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
}
catch (UnsupportedFormatException e)
{
// This case should pass on Java 6 and later.
if (!System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
assertEquals("No suitable ImageWriter found for gif.", e.getMessage());
assertEquals("gif", e.getFormatName());
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a PNG image
* b) Output file is a JPEG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Png_Jpeg() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.png");
File outputFile = File.createTempFile("thumbnailator-testing-", ".jpg");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(
"JPEG",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(outputFile)
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a PNG image
* b) Output file is a BMP image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Png_Bmp() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.png");
File outputFile = File.createTempFile("thumbnailator-testing-", ".bmp");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(
"bmp",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(outputFile)
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a PNG image
* b) Output file is a GIF image
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
* On Java 6 and later, this should pass, as it contains a GIF writer.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Png_Gif() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.png");
File outputFile = File.createTempFile("thumbnailator-testing-", ".gif");
outputFile.deleteOnExit();
try
{
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
// This case should pass on Java 6 and later, as those JREs have a
// GIF writer.
if (System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
}
catch (UnsupportedFormatException e)
{
// This case should pass on Java 6 and later.
if (!System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
assertEquals("No suitable ImageWriter found for gif.", e.getMessage());
assertEquals("gif", e.getFormatName());
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a BMP image
* b) Output file is a PNG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Bmp_Png() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.bmp");
File outputFile = File.createTempFile("thumbnailator-testing-", ".png");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(
"png",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(outputFile)
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a BMP image
* b) Output file is a JPEG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Bmp_Jpeg() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.bmp");
File outputFile = File.createTempFile("thumbnailator-testing-", ".jpg");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(
"JPEG",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(outputFile)
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a BMP image
* b) Output file is a GIF image
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
* On Java 6 and later, this should pass, as it contains a GIF writer.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Bmp_Gif() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.bmp");
File outputFile = File.createTempFile("thumbnailator-testing-", ".gif");
outputFile.deleteOnExit();
try
{
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
// This case should pass on Java 6 and later, as those JREs have a
// GIF writer.
if (System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
}
catch (UnsupportedFormatException e)
{
// This case should pass on Java 6 and later.
if (!System.getProperty("java.version").startsWith("1.5"))
{
fail();
}
assertEquals("No suitable ImageWriter found for gif.", e.getMessage());
assertEquals("gif", e.getFormatName());
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a GIF image
* b) Output file is a PNG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Gif_Png() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.gif");
File outputFile = File.createTempFile("thumbnailator-testing-", ".png");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(
"png",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(outputFile)
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a GIF image
* b) Output file is a JPEG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Gif_Jpeg() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.gif");
File outputFile = File.createTempFile("thumbnailator-testing-", ".jpg");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(
"JPEG",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(outputFile)
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) There is transcoding taking place:
* a) Input file is a GIF image
* b) Output file is a BMP image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_Transcoding_Gif_Bmp() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.gif");
File outputFile = File.createTempFile("thumbnailator-testing-", ".bmp");
outputFile.deleteOnExit();
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
assertTrue(outputFile.exists());
BufferedImage img = ImageIO.read(outputFile);
assertEquals(
"bmp",
ImageIO.getImageReaders(
ImageIO.createImageInputStream(outputFile)
).next().getFormatName()
);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) Input File does not exist.
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_nonExistentInputFile() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("foo.jpg");
File outputFile = new File("bar.jpg");
try
{
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
fail();
}
catch (IOException e)
{
assertEquals("Input file does not exist.", e.getMessage());
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) A filename that is invalid
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FFII_invalidOutputFile() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.jpg");
File outputFile = new File("@\\
try
{
Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50);
fail();
}
catch (IOException e)
{
// An IOException is expected. Likely a FileNotFoundException.
}
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, File, int, int)}
* where,
*
* 1) A problem occurs while writing to the file.
*
* Expected outcome is,
*
* 1) Processing will stop with an IOException.
*
* @throws IOException
*/
@Ignore
public void testCreateThumbnail_FFII_IOExceptionOnWrite() throws IOException
{
//Cannot craft a test case to test this condition.
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, int, int)}
* where,
*
* 1) Input File is null
*
* Expected outcome is,
*
* 1) Processing will stop with an NullPointerException.
*
* @throws IOException
*/
@Test(expected=NullPointerException.class)
public void testCreateThumbnail_FII_nullInputFile() throws IOException
{
Thumbnailator.createThumbnail((File)null, 50, 50);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_FII_negativeWidth() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("foo.jpg");
Thumbnailator.createThumbnail(inputFile, -42, 50);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_FII_negativeHeight() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("foo.jpg");
Thumbnailator.createThumbnail(inputFile, 50, -42);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_FII_negativeWidthAndHeight() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("foo.jpg");
Thumbnailator.createThumbnail(inputFile, -42, -42);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input file is a JPEG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FII_Jpg() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.jpg");
BufferedImage img = Thumbnailator.createThumbnail(inputFile, 50, 50);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input file is a PNG image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FII_Png() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.png");
BufferedImage img = Thumbnailator.createThumbnail(inputFile, 50, 50);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input data is a BMP image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FII_Bmp() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.bmp");
BufferedImage img = Thumbnailator.createThumbnail(inputFile, 50, 50);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(File, int, int)}
* where,
*
* 1) Method arguments are correct
* 2) Input data is a GIF image
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_FII_Gif() throws IOException
{
/*
* Actual test
*/
File inputFile = new File("test-resources/Thumbnailator/grid.gif");
BufferedImage img = Thumbnailator.createThumbnail(inputFile, 50, 50);
assertEquals(50, img.getWidth());
assertEquals(50, img.getHeight());
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_BII_negativeWidth()
{
/*
* Actual test
*/
BufferedImage img = new BufferedImageBuilder(200, 200).build();
Thumbnailator.createThumbnail(img, -42, 50);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_BII_negativeHeight()
{
/*
* Actual test
*/
BufferedImage img = new BufferedImageBuilder(200, 200).build();
Thumbnailator.createThumbnail(img, 50, -42);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_BII_negativeWidthAndHeight()
{
/*
* Actual test
*/
BufferedImage img = new BufferedImageBuilder(200, 200).build();
Thumbnailator.createThumbnail(img, -42, -42);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(BufferedImage, int, int)}
* where,
*
* 1) Method arguments are correct
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
*/
@Test
public void testCreateThumbnail_BII_CorrectUsage()
{
/*
* Actual test
*/
BufferedImage img =
new BufferedImageBuilder(200, 200, BufferedImage.TYPE_INT_ARGB).build();
BufferedImage thumbnail = Thumbnailator.createThumbnail(img, 50, 50);
assertEquals(50, thumbnail.getWidth());
assertEquals(50, thumbnail.getHeight());
assertEquals(BufferedImage.TYPE_INT_ARGB, thumbnail.getType());
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_III_negativeWidth()
{
/*
* Actual test
*/
BufferedImage img = new BufferedImageBuilder(200, 200).build();
Thumbnailator.createThumbnail((Image)img, -42, 50);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_III_negativeHeight()
{
/*
* Actual test
*/
BufferedImage img = new BufferedImageBuilder(200, 200).build();
Thumbnailator.createThumbnail((Image)img, 50, -42);
fail();
}
@Test(expected=IllegalArgumentException.class)
public void testCreateThumbnail_III_negativeWidthAndHeight()
{
/*
* Actual test
*/
BufferedImage img = new BufferedImageBuilder(200, 200).build();
Thumbnailator.createThumbnail((Image)img, -42, -42);
fail();
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(Image, int, int)}
* where,
*
* 1) Method arguments are correct
*
* Expected outcome is,
*
* 1) Processing will complete successfully.
*
*/
@Test
public void testCreateThumbnail_III_CorrectUsage()
{
/*
* Actual test
*/
BufferedImage img =
new BufferedImageBuilder(200, 200, BufferedImage.TYPE_INT_ARGB).build();
Image thumbnail = Thumbnailator.createThumbnail((Image)img, 50, 50);
assertEquals(50, thumbnail.getWidth(null));
assertEquals(50, thumbnail.getHeight(null));
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(net.coobird.thumbnailator.tasks.ThumbnailTask)}
* where,
*
* 1) The correct parameters are given.
* 2) The size is specified for the ThumbnailParameter.
*
* Expected outcome is,
*
* 1) The ResizerFactory is being used.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_ThumbnailTask_ResizerFactoryBeingUsed_UsingSize() throws IOException
{
// given
BufferedImageSource source = new BufferedImageSource(
new BufferedImageBuilder(200, 200, BufferedImage.TYPE_INT_ARGB).build()
);
BufferedImageSink sink = new BufferedImageSink();
ResizerFactory resizerFactory = spy(DefaultResizerFactory.getInstance());
ThumbnailParameter param =
new ThumbnailParameterBuilder()
.size(100, 100)
.resizerFactory(resizerFactory)
.build();
// when
Thumbnailator.createThumbnail(
new SourceSinkThumbnailTask<BufferedImage, BufferedImage>(
param, source, sink
)
);
// then
verify(resizerFactory)
.getResizer(new Dimension(200, 200), new Dimension(100, 100));
}
/**
* Test for
* {@link Thumbnailator#createThumbnail(net.coobird.thumbnailator.tasks.ThumbnailTask)}
* where,
*
* 1) The correct parameters are given.
* 2) The scale is specified for the ThumbnailParameter.
*
* Expected outcome is,
*
* 1) The ResizerFactory is being used.
*
* @throws IOException
*/
@Test
public void testCreateThumbnail_ThumbnailTask_ResizerFactoryBeingUsed_UsingScale() throws IOException
{
// given
BufferedImageSource source = new BufferedImageSource(
new BufferedImageBuilder(200, 200, BufferedImage.TYPE_INT_ARGB).build()
);
BufferedImageSink sink = new BufferedImageSink();
ResizerFactory resizerFactory = spy(DefaultResizerFactory.getInstance());
ThumbnailParameter param =
new ThumbnailParameterBuilder()
.scale(0.5)
.resizerFactory(resizerFactory)
.build();
// when
Thumbnailator.createThumbnail(
new SourceSinkThumbnailTask<BufferedImage, BufferedImage>(
param, source, sink
)
);
// then
verify(resizerFactory)
.getResizer(new Dimension(200, 200), new Dimension(100, 100));
}
@Test
public void renameGivenThumbnailParameter_createThumbnails() throws IOException
{
// given
Rename rename = mock(Rename.class);
when(rename.apply(anyString(), any(ThumbnailParameter.class)))
.thenReturn("thumbnail.grid.png");
File f = new File("test-resources/Thumbnailator/grid.png");
// when
Thumbnailator.createThumbnails(Arrays.asList(f), rename, 50, 50);
// then
ArgumentCaptor<ThumbnailParameter> ac =
ArgumentCaptor.forClass(ThumbnailParameter.class);
verify(rename).apply(eq(f.getName()), ac.capture());
assertEquals(new Dimension(50, 50), ac.getValue().getSize());
// clean up
new File("test-resources/Thumbnailator/thumbnail.grid.png").deleteOnExit();
}
@Test
public void renameGivenThumbnailParameter_createThumbnailsAsCollection() throws IOException
{
// given
Rename rename = mock(Rename.class);
when(rename.apply(anyString(), any(ThumbnailParameter.class)))
.thenReturn("thumbnail.grid.png");
File f = new File("test-resources/Thumbnailator/grid.png");
// when
Thumbnailator.createThumbnailsAsCollection(Arrays.asList(f), rename, 50, 50);
// then
ArgumentCaptor<ThumbnailParameter> ac =
ArgumentCaptor.forClass(ThumbnailParameter.class);
verify(rename).apply(eq(f.getName()), ac.capture());
assertEquals(new Dimension(50, 50), ac.getValue().getSize());
// clean up
new File("test-resources/Thumbnailator/thumbnail.grid.png").deleteOnExit();
}
/**
* Returns test image data as an array of {@code byte}s.
*
* @param format Image format.
* @param width Image width.
* @param height Image height.
* @return A {@code byte[]} of image data.
* @throws IOException When a problem occurs while making image data.
*/
private byte[] makeImageData(String format, int width, int height)
throws IOException
{
BufferedImage img = new BufferedImageBuilder(200, 200).build();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, format, baos);
return baos.toByteArray();
}
}
|
package net.fortuna.ical4j.data;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import net.fortuna.ical4j.FileOnlyFilter;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.ValidationException;
import net.fortuna.ical4j.model.property.Description;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Test case for iCalendarBuilder.
*
* @author benf
*/
public class CalendarBuilderTest extends TestCase {
private static Log log = LogFactory.getLog(CalendarBuilderTest.class);
private String filename;
private CalendarBuilder builder;
private boolean valid;
/**
* Constructor.
*
* @param method
* name of method to run in test case
* @param file
* an iCalendar filename
*/
public CalendarBuilderTest(final String method, final String file, final boolean valid) {
super(method);
this.filename = file;
this.valid = valid;
builder = new CalendarBuilder();
}
/**
* Class to test for Calendar build(InputStream).
*/
public final void testBuildInputStream() throws Exception {
System.setProperty("ical4j.unfolding.relaxed", "true");
FileInputStream fin = new FileInputStream(filename);
Calendar calendar = null;
try {
calendar = builder.build(fin);
assertNotNull("File [" + filename + "] invalid", calendar);
try {
calendar.validate();
assertTrue("File [" + filename + "] valid", valid);
} catch (ValidationException e) {
log.warn("Calendar file [" + filename + "] is invalid.", e);
assertFalse("File [" + filename + "] invalid", valid);
}
} catch (IOException e) {
log.warn("File: " + filename, e);
assertFalse("File [" + filename + "] invalid", valid);
} catch (ParserException e) {
log.warn("File: " + filename, e);
assertFalse("File [" + filename + "] invalid", valid);
}
if (log.isInfoEnabled()) {
log.info("File: " + filename);
if (log.isDebugEnabled()) {
log.debug("Calendar:\n=========\n" + calendar.toString());
for (Iterator i = calendar.getComponents().iterator(); i.hasNext();) {
Component c = (Component) i.next();
Description description = (Description) c.getProperty(Property.DESCRIPTION);
if (description != null) {
log.debug("Description [" + description.getValue() + "]");
}
}
}
}
}
/* (non-Javadoc)
* @see junit.framework.TestCase#getName()
*/
/**
* Overridden to return the current iCalendar file under test.
*/
public final String getName() {
return filename;
}
/**
* Test suite.
* @return test suite
*/
public static Test suite() {
TestSuite suite = new TestSuite();
File[] testFiles = null;
// valid tests..
testFiles = new File("etc/samples/valid").listFiles(new FileOnlyFilter());
for (int i = 0; i < testFiles.length; i++) {
log.info("Sample [" + testFiles[i] + "]");
suite.addTest(new CalendarBuilderTest("testBuildInputStream", testFiles[i].getPath(), true));
}
// invalid tests..
testFiles = new File("etc/samples/invalid").listFiles(new FileOnlyFilter());
for (int i = 0; i < testFiles.length; i++) {
log.info("Sample [" + testFiles[i] + "]");
suite.addTest(new CalendarBuilderTest("testBuildInputStream", testFiles[i].getPath(), false));
}
return suite;
}
}
|
package org.traccar.protocol;
import org.junit.Test;
import org.traccar.ProtocolTest;
public class H02ProtocolDecoderTest extends ProtocolTest {
@Test
public void testDecode() throws Exception {
H02ProtocolDecoder decoder = new H02ProtocolDecoder(new H02Protocol());
verifyNothing(decoder, buffer(
"*HQ,356803210091319,BS,,2d4,a,1b63,1969,26,1b63,10b2,31,0,0,25,,ffffffff,60
verifyAttributes(decoder, buffer(
"*HQ,1400046168,NBR,160169,460,0,1,4,9338,3692,150,9338,3691,145,9338,3690,140,9338,3692,139,180813,FFFFFBFF
verifyAttributes(decoder, buffer(
"*HQ,1600068860,NBR,120156,262,03,255,6,802,54702,46,802,5032,37,802,54782,30,802,5052,28,802,54712,12,802,5042,12,081116,FFFFFBFF
verifyAttributes(decoder, buffer(
"*HQ,1600068860,NBR,110326,262,03,255,6,802,23152,23,812,49449,14,802,35382,13,802,35402,11,812,56622,09,802,23132,04,081116,FFFFFBFF
verifyNothing(decoder, buffer(
"*HQ,1600068860,LINK,112137,20,8,67,0,0,081116,FFFFFBFF
verifyNothing(decoder, buffer(
"*HQ,355488020533263,V3,121536,65501,04,000152,014001,156,-64,000161,010642,138,,000152,014003,129,,000152,013973,126,,02E4,0,X,071116,FFFFFBFF
verifyPosition(decoder, buffer(
"*HQ,4209917484,V19,093043,V,5052.9749,N,00426.4322,E,000.00,000,130916,,0032475874141,8944538530000543700F,FFFFFBFF
verifyPosition(decoder, buffer(
"*HQ,353505220873067,V1,,V,4605.75732,N,01430.73863,E,0.00,0,,FFFFFFEF,125,194, 64,d3
verifyPosition(decoder, buffer(
"*HQ,4210051415,V1,164549,A,0956.3869,N,08406.7068,W,000.00,000,221215,FFFFFBFF,712,01,0,0,6
position("2015-12-22 16:45:49.000", true, 9.93978, -84.11178));
verifyAttributes(decoder, buffer(
"*HQ,1451316451,NBR,112315,724,10,2,2,215,2135,123,215,2131,121,011215,FFFFFFFF
verifyPosition(decoder, buffer(
"*HQ,1451316485,V1,121557,A,-23-3.3408,S,-48-2.8926,W,0.1,158,241115,FFFFFFFF
verifyPosition(decoder, buffer(
"*HQ,1451316485,V1,121557,A,-23-35.3408,S,-48-2.8926,W,0.1,158,241115,FFFFFFFF
verifyPosition(decoder, buffer(
"*HQ,355488020119695,V1,050418,,2827.61232,N,07703.84822,E,0.00,0,031015,FFFEFBFF
position("2015-10-03 05:04:18.000", false, 28.46021, 77.06414));
verifyPosition(decoder, buffer(
"*HQ,1451316409,V1,030149,A,-23-29.0095,S,-46-51.5852,W,2.4,065,070315,FFFFFFFF
position("2015-03-07 03:01:49.000", true, -23.48349, -46.85975));
verifyNothing(decoder, buffer(
"*HQ,353588020068342,V1,000000,V,0.0000,0,0.0000,0,0.00,0.00,000000,ffffffff,000106,000002,000203,004c87,16
verifyPosition(decoder, buffer(
"*HQ,3800008786,V1,062507,V,3048.2437,N,03058.5617,E,000.00,000,250413,FFFFFBFF
verifyPosition(decoder, buffer(
"*HQ,4300256455,V1,111817,A,1935.5128,N,04656.3243,E,0.00,100,170913,FFE7FBFF
verifyPosition(decoder, buffer(
"*HQ,123456789012345,V1,155850,A,5214.5346,N,2117.4683,E,0.00,270.90,131012,ffffffff,000000,000000,000000,000000
verifyPosition(decoder, buffer(
"*HQ,353588010001689,V1,221116,A,1548.8220,S,4753.1679,W,0.00,0.00,300413,ffffffff,0002d4,000004,0001cd,000047
verifyPosition(decoder, buffer(
"*HQ,354188045498669,V1,195200,A,701.8915,S,3450.3399,W,0.00,205.70,050213,ffffffff,000243,000000,000000
verifyPosition(decoder, buffer(
"*HQ,2705171109,V1,213324,A,5002.5849,N,01433.7822,E,0.00,000,140613,FFFFFFFF
verifyPosition(decoder, buffer(
"*TH,2020916012,V1,050316,A,2212.8745,N,11346.6574,E,14.28,028,220902,FFFFFBFF
verifyPosition(decoder, buffer(
"*TH,2020916012,V4,S17,130305,050316,A,2212.8745,N,11346.6574,E,14.28,028,220902,FFFFFBFF
verifyPosition(decoder, buffer(
"*TH,2020916012,V4,S14,100,10,1,3,130305,050316,A,2212.8745,N,11346.6574,E,14.28,028,220902,FFFFFBFF
verifyPosition(decoder, buffer(
"*TH,2020916012,V4,S20,ERROR,130305,050316,A,2212.8745,N,11346.6574,E,14.28,028,220902,FFFFFBFF
verifyPosition(decoder, buffer(
"*TH,2020916012,V4,S20,DONE,130305,050316,A,2212.8745,N,11346.6574,E,14.28,028,220902,F7FFFBFF
verifyPosition(decoder, buffer(
"*TH,2020916012,V4,R8,ERROR,130305,050316,A,2212.8745,N,11346.6574,E,14.28,028,220902,FFFFFBFF
verifyPosition(decoder, buffer(
"*TH,2020916012,V4,S23,165.165.33.250:8800,130305,050316,A,2212.8745,N,11346.6574,E,14.28,028,220902,FFFFFBFF
verifyPosition(decoder, buffer(
"*TH,2020916012,V4,S24,thit.gd,130305,050316,A,2212.8745,N,11346.6574,E,14.28,028,220902,FFFFFBFF
verifyPosition(decoder, buffer(
"*TH,2020916012,V4,S1,OK,pass_word,130305,050316,A,2212.8745,N,11346.6574,E,14.28,028,220902,FFFFFBFD
verifyPosition(decoder, buffer(
"*HQ,353588020068342,V1,062840,A,5241.1249,N,954.9490,E,0.00,0.00,231013,ffffffff,000106,000002,000203,004c87,24
verifyPosition(decoder, buffer(
"*HQ,353505220903211,V1,075228,A,5227.5039,N,01032.8443,E,0.00,0,231013,FFFBFFFF,106,14, 201,2173
verifyPosition(decoder, buffer(
"*HQ,353505220903211,V1,140817,A,5239.3538,N,01003.5292,E,21.03,312,221013,FFFBFFFF,106,14, 203,1cd
verifyPosition(decoder, buffer(
"*HQ,356823035368767,V1,083618,A,0955.6392,N,07809.0796,E,0.00,0,070414,FFFBFFFF,194,3b5, 71,c9a9
verifyNothing(decoder, buffer(
"*HQ,8401016597,BASE,152609,0,0,0,0,211014,FFFFFFFF
verifyPosition(decoder, binary(
"2441060116601245431311165035313006004318210e000000fffffbffff0024"));
verifyPosition(decoder, binary(
"24410600082621532131081504419390060740418306000000fffffbfdff0015060000002c02dc0c000000001f"),
position("2015-08-31 21:53:21.000", true, 4.69898, -74.06971));
verifyPosition(decoder, binary(
"2427051711092133391406135002584900014337822e000000ffffffffff0000"));
verifyPosition(decoder, binary(
"2427051711092134091406135002584900014337822e000000ffffffffff0000"));
verifyPosition(decoder, binary(
"2410307310010503162209022212874500113466574C014028fffffbffff0000"));
verifyPosition(decoder, binary(
"2441090013450831250401145047888000008554650e000000fffff9ffff001006000000000106020299109c01"));
verifyPosition(decoder, binary(
"24270517030820321418041423307879000463213792000056fffff9ffff0000"));
verifyPosition(decoder, binary(
"2441091144271222470112142233983006114026520E000000FFFFFBFFFF0014060000000001CC00262B0F170A"));
verifyPosition(decoder, binary(
"24971305007205201916101533335008000073206976000000effffbffff000252776566060000000000000000000049"));
}
}
|
package org.eclipse.che.ide.resources.impl;
import com.google.common.annotations.Beta;
import com.google.common.base.Optional;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import com.google.web.bindery.event.shared.EventBus;
import org.eclipse.che.api.core.model.project.NewProjectConfig;
import org.eclipse.che.api.core.model.project.ProjectConfig;
import org.eclipse.che.api.core.model.project.SourceStorage;
import org.eclipse.che.api.core.rest.shared.dto.Link;
import org.eclipse.che.api.project.shared.dto.ItemReference;
import org.eclipse.che.api.project.shared.dto.SourceEstimation;
import org.eclipse.che.api.project.shared.dto.TreeElement;
import org.eclipse.che.api.promises.client.Function;
import org.eclipse.che.api.promises.client.FunctionException;
import org.eclipse.che.api.promises.client.Promise;
import org.eclipse.che.api.promises.client.PromiseProvider;
import org.eclipse.che.api.workspace.shared.dto.NewProjectConfigDto;
import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto;
import org.eclipse.che.api.workspace.shared.dto.ProjectProblemDto;
import org.eclipse.che.api.workspace.shared.dto.SourceStorageDto;
import org.eclipse.che.ide.api.app.AppContext;
import org.eclipse.che.ide.api.editor.EditorAgent;
import org.eclipse.che.ide.api.editor.EditorPartPresenter;
import org.eclipse.che.ide.api.event.ng.DeletedFilesController;
import org.eclipse.che.ide.api.machine.DevMachine;
import org.eclipse.che.ide.api.machine.WsAgentURLModifier;
import org.eclipse.che.ide.api.project.MutableProjectConfig;
import org.eclipse.che.ide.api.project.ProjectServiceClient;
import org.eclipse.che.ide.api.project.QueryExpression;
import org.eclipse.che.ide.api.project.type.ProjectTypeRegistry;
import org.eclipse.che.ide.api.resources.Container;
import org.eclipse.che.ide.api.resources.File;
import org.eclipse.che.ide.api.resources.Folder;
import org.eclipse.che.ide.api.resources.Project;
import org.eclipse.che.ide.api.resources.Project.ProblemProjectMarker;
import org.eclipse.che.ide.api.resources.Project.ProjectRequest;
import org.eclipse.che.ide.api.resources.Resource;
import org.eclipse.che.ide.api.resources.ResourceChangedEvent;
import org.eclipse.che.ide.api.resources.ResourceDelta;
import org.eclipse.che.ide.api.resources.marker.Marker;
import org.eclipse.che.ide.api.resources.marker.MarkerChangedEvent;
import org.eclipse.che.ide.context.AppContextImpl;
import org.eclipse.che.ide.dto.DtoFactory;
import org.eclipse.che.ide.resource.Path;
import org.eclipse.che.ide.util.Arrays;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.google.common.base.Optional.absent;
import static com.google.common.base.Optional.fromNullable;
import static com.google.common.base.Optional.of;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.lang.System.arraycopy;
import static java.util.Arrays.copyOf;
import static org.eclipse.che.ide.api.event.ng.FileTrackingEvent.newFileTrackingResumeEvent;
import static org.eclipse.che.ide.api.event.ng.FileTrackingEvent.newFileTrackingSuspendEvent;
import static org.eclipse.che.ide.api.resources.Resource.FILE;
import static org.eclipse.che.ide.api.resources.ResourceDelta.ADDED;
import static org.eclipse.che.ide.api.resources.ResourceDelta.COPIED_FROM;
import static org.eclipse.che.ide.api.resources.ResourceDelta.DERIVED;
import static org.eclipse.che.ide.api.resources.ResourceDelta.MOVED_FROM;
import static org.eclipse.che.ide.api.resources.ResourceDelta.MOVED_TO;
import static org.eclipse.che.ide.api.resources.ResourceDelta.REMOVED;
import static org.eclipse.che.ide.api.resources.ResourceDelta.SYNCHRONIZED;
import static org.eclipse.che.ide.api.resources.ResourceDelta.UPDATED;
import static org.eclipse.che.ide.util.Arrays.add;
import static org.eclipse.che.ide.util.Arrays.removeAll;
import static org.eclipse.che.ide.util.NameUtils.checkFileName;
import static org.eclipse.che.ide.util.NameUtils.checkFolderName;
import static org.eclipse.che.ide.util.NameUtils.checkProjectName;
/**
* Acts as the service lay between the user interactions with resources and data transfer layer.
* Main necessity of this manager is to encapsulate business logic which serves resources from
* the interfaces.
* <p/>
* This manager is not intended to be operated with third-party components. Only resources can
* operate with it. To operate with resources use {@link AppContext#getWorkspaceRoot()} and
* {@link AppContext#getProjects()}.
*
* @author Vlad Zhukovskiy
* @see AppContext
* @see AppContextImpl
* @since 4.4.0
*/
@Beta
public final class ResourceManager {
/**
* Describes zero depth level for the descendants.
*/
private static final int DEPTH_ZERO = 0;
/**
* Describes first depth level for the descendants.
*/
private static final int DEPTH_ONE = 1;
/**
* Relative link for the content url.
*
* @see #newResourceFrom(ItemReference)
*/
private static final String GET_CONTENT_REL = "get content";
/**
* Empty projects container.
*
* @see #getWorkspaceProjects()
*/
private static final Project[] NO_PROJECTS = new Project[0];
private static final Resource[] NO_RESOURCES = new Resource[0];
private final ProjectServiceClient ps;
private final EventBus eventBus;
private final EditorAgent editorAgent;
private final DeletedFilesController deletedFilesController;
private final ResourceFactory resourceFactory;
private final PromiseProvider promises;
private final DtoFactory dtoFactory;
private final ProjectTypeRegistry typeRegistry;
/**
* Link to the workspace content root. Immutable among the workspace life.
*/
private final Container workspaceRoot;
private final WsAgentURLModifier urlModifier;
private DevMachine devMachine;
/**
* Internal store, which caches requested resources from the server.
*/
private ResourceStore store;
/**
* Cached dto project configuration.
*/
private ProjectConfigDto[] cachedConfigs;
@Inject
public ResourceManager(@Assisted DevMachine devMachine,
ProjectServiceClient ps,
EventBus eventBus,
EditorAgent editorAgent,
DeletedFilesController deletedFilesController,
ResourceFactory resourceFactory,
PromiseProvider promises,
DtoFactory dtoFactory,
ProjectTypeRegistry typeRegistry,
ResourceStore store,
WsAgentURLModifier urlModifier) {
this.devMachine = devMachine;
this.ps = ps;
this.eventBus = eventBus;
this.editorAgent = editorAgent;
this.deletedFilesController = deletedFilesController;
this.resourceFactory = resourceFactory;
this.promises = promises;
this.dtoFactory = dtoFactory;
this.typeRegistry = typeRegistry;
this.store = store;
this.urlModifier = urlModifier;
this.workspaceRoot = resourceFactory.newFolderImpl(Path.ROOT, this);
}
/**
* Returns the workspace registered projects.
*
* @return the {@link Promise} with registered projects
* @see Project
* @since 4.4.0
*/
public Promise<Project[]> getWorkspaceProjects() {
return ps.getProjects().then((Function<List<ProjectConfigDto>, Project[]>)dtoConfigs -> {
store.clear();
if (dtoConfigs.isEmpty()) {
cachedConfigs = new ProjectConfigDto[0];
return NO_PROJECTS;
}
cachedConfigs = dtoConfigs.toArray(new ProjectConfigDto[dtoConfigs.size()]);
Project[] projects = NO_PROJECTS;
for (ProjectConfigDto config : dtoConfigs) {
if (Path.valueOf(config.getPath()).segmentCount() == 1) {
final Project project = resourceFactory.newProjectImpl(config, ResourceManager.this);
store.register(project);
final Optional<ProblemProjectMarker> optionalMarker = getProblemMarker(config);
if (optionalMarker.isPresent()) {
project.addMarker(optionalMarker.get());
}
Project[] tmpProjects = copyOf(projects, projects.length + 1);
tmpProjects[projects.length] = project;
projects = tmpProjects;
}
}
/* We need to guarantee that list of projects would be sorted by the logic provided in compareTo method implementation. */
java.util.Arrays.sort(projects);
for (Project project : projects) {
eventBus.fireEvent(new ResourceChangedEvent(new ResourceDeltaImpl(project, ADDED | DERIVED)));
}
return projects;
});
}
/**
* Returns the workspace root container. This container is a holder which may contains only {@link Project}s.
*
* @return the workspace container
* @see Container
* @since 4.4.0
*/
public Container getWorkspaceRoot() {
return workspaceRoot;
}
/**
* Update state of specific properties in project and save this state on the server.
* As the result method should return the {@link Promise} with new {@link Project} object.
* <p/>
* During the update method have to iterate on children of updated resource and if any of
* them has changed own type, e.g. folder -> project, project -> folder, specific event
* has to be fired.
* <p/>
* Method is not intended to be called in third party components. It is the service method
* for {@link Project}.
*
* @param path
* the path to project which should be updated
* @param request
* the update request
* @return the {@link Promise} with new {@link Project} object.
* @see ResourceChangedEvent
* @see ProjectRequest
* @see Project#update()
* @since 4.4.0
*/
protected Promise<Project> update(final Path path, final ProjectRequest request) {
final ProjectConfig projectConfig = request.getBody();
final SourceStorage source = projectConfig.getSource();
final SourceStorageDto sourceDto = dtoFactory.createDto(SourceStorageDto.class);
if (source != null) {
sourceDto.setLocation(source.getLocation());
sourceDto.setType(source.getType());
sourceDto.setParameters(source.getParameters());
}
final ProjectConfigDto dto = dtoFactory.createDto(ProjectConfigDto.class)
.withName(projectConfig.getName())
.withPath(path.toString())
.withDescription(projectConfig.getDescription())
.withType(projectConfig.getType())
.withMixins(projectConfig.getMixins())
.withAttributes(projectConfig.getAttributes())
.withSource(sourceDto);
return ps.updateProject(dto).thenPromise(reference -> {
/* Note: After update, project may become to be other type,
e.g. blank -> java or maven, or ant, or etc. And this may
cause sub-project creations. Simultaneously on the client
side there is outdated information about sub-projects, so
we need to get updated project list. */
//dispose outdated resource
final Optional<Resource> outdatedResource = store.getResource(path);
checkState(outdatedResource.isPresent(), "Outdated resource wasn't found");
final Resource resource = outdatedResource.get();
checkState(resource instanceof Container, "Outdated resource is not a container");
Container container = (Container)resource;
if (resource instanceof Folder) {
Container parent = resource.getParent();
checkState(parent != null, "Parent of the resource wasn't found");
container = parent;
}
return synchronize(container).then(new Function<Resource[], Project>() {
@Override
public Project apply(Resource[] synced) throws FunctionException {
final Optional<Resource> updatedProject = store.getResource(path);
checkState(updatedProject.isPresent(), "Updated resource is not present");
checkState(updatedProject.get().isProject(), "Updated resource is not a project");
eventBus.fireEvent(new ResourceChangedEvent(new ResourceDeltaImpl(updatedProject.get(), UPDATED)));
return (Project)updatedProject.get();
}
});
});
}
Promise<Folder> createFolder(final Container parent, final String name) {
final Path path = Path.valueOf(name);
return findResource(parent.getLocation().append(path), true).thenPromise(resource -> {
if (resource.isPresent()) {
return promises.reject(new IllegalStateException("Resource already exists"));
}
if (parent.getLocation().isRoot()) {
return promises.reject(new IllegalArgumentException("Failed to create folder in workspace root"));
}
if (path.segmentCount() == 1 && !checkFolderName(name)) {
return promises.reject(new IllegalArgumentException("Invalid folder name"));
}
return ps.createFolder(parent.getLocation().append(name)).thenPromise(reference -> {
final Resource createdFolder = newResourceFrom(reference);
store.register(createdFolder);
return promises.resolve(createdFolder.asFolder());
});
});
}
Promise<File> createFile(final Container parent, final String name, final String content) {
if (!checkFileName(name)) {
return promises.reject(new IllegalArgumentException("Invalid file name"));
}
return findResource(parent.getLocation().append(name), true).thenPromise(resource -> {
if (resource.isPresent()) {
return promises.reject(new IllegalStateException("Resource already exists"));
}
if (parent.getLocation().isRoot()) {
return promises.reject(new IllegalArgumentException("Failed to create file in workspace root"));
}
return ps.createFile(parent.getLocation().append(name), content).thenPromise(reference -> {
final Resource createdFile = newResourceFrom(reference);
store.register(createdFile);
return promises.resolve(createdFile.asFile());
});
});
}
Promise<Project> createProject(final Project.ProjectRequest createRequest) {
checkArgument(checkProjectName(createRequest.getBody().getName()), "Invalid project name");
checkArgument(typeRegistry.getProjectType(createRequest.getBody().getType()) != null, "Invalid project type");
final Path path = Path.valueOf(createRequest.getBody().getPath());
return findResource(path, true).thenPromise(resource -> {
if (resource.isPresent()) {
if (resource.get().isProject()) {
throw new IllegalStateException("Project already exists");
} else if (resource.get().isFile()) {
throw new IllegalStateException("File can not be converted to project");
}
return update(path, createRequest);
}
final MutableProjectConfig projectConfig = (MutableProjectConfig)createRequest.getBody();
final List<NewProjectConfig> projectConfigList = projectConfig.getProjects();
projectConfigList.add(asDto(projectConfig));
final List<NewProjectConfigDto> configDtoList = asDto(projectConfigList);
return ps.createBatchProjects(configDtoList).thenPromise(
configList -> ps.getProjects().then((Function<List<ProjectConfigDto>, Project>)updatedConfiguration -> {
//cache new configs
cachedConfigs = updatedConfiguration.toArray(new ProjectConfigDto[updatedConfiguration.size()]);
for (ProjectConfigDto projectConfigDto : configList) {
if (projectConfigDto.getPath().equals(path.toString())) {
final Project newResource = resourceFactory.newProjectImpl(projectConfigDto, ResourceManager.this);
store.register(newResource);
eventBus.fireEvent(new ResourceChangedEvent(new ResourceDeltaImpl(newResource, ADDED | DERIVED)));
return newResource;
}
}
throw new IllegalStateException("Created project is not found");
}));
});
}
private NewProjectConfigDto asDto(MutableProjectConfig config) {
final SourceStorage source = config.getSource();
final SourceStorageDto sourceStorageDto = dtoFactory.createDto(SourceStorageDto.class)
.withType(source.getType())
.withLocation(source.getLocation())
.withParameters(source.getParameters());
return dtoFactory.createDto(NewProjectConfigDto.class)
.withName(config.getName())
.withPath(config.getPath())
.withDescription(config.getDescription())
.withSource(sourceStorageDto)
.withType(config.getType())
.withMixins(config.getMixins())
.withAttributes(config.getAttributes())
.withOptions(config.getOptions());
}
private List<NewProjectConfigDto> asDto(List<NewProjectConfig> configList) {
List<NewProjectConfigDto> result = new ArrayList<>(configList.size());
for (NewProjectConfig config : configList) {
final SourceStorage source = config.getSource();
final SourceStorageDto sourceStorageDto = dtoFactory.createDto(SourceStorageDto.class)
.withType(source.getType())
.withLocation(source.getLocation())
.withParameters(source.getParameters());
result.add(dtoFactory.createDto(NewProjectConfigDto.class)
.withName(config.getName())
.withPath(config.getPath())
.withDescription(config.getDescription())
.withSource(sourceStorageDto)
.withType(config.getType())
.withMixins(config.getMixins())
.withAttributes(config.getAttributes())
.withOptions(config.getOptions()));
}
return result;
}
protected Promise<Project> importProject(final Project.ProjectRequest importRequest) {
checkArgument(checkProjectName(importRequest.getBody().getName()), "Invalid project name");
checkNotNull(importRequest.getBody().getSource(), "Null source configuration occurred");
final Path path = Path.valueOf(importRequest.getBody().getPath());
return findResource(path, true).thenPromise(resource -> {
final SourceStorage sourceStorage = importRequest.getBody().getSource();
final SourceStorageDto sourceStorageDto = dtoFactory.createDto(SourceStorageDto.class)
.withType(sourceStorage.getType())
.withLocation(sourceStorage.getLocation())
.withParameters(sourceStorage.getParameters());
return ps.importProject(path, sourceStorageDto)
.thenPromise(ignored -> ps.getProject(path).then((Function<ProjectConfigDto, Project>)config -> {
cachedConfigs = add(cachedConfigs, config);
Resource project = resourceFactory.newProjectImpl(config, ResourceManager.this);
checkState(project != null, "Failed to locate imported project's configuration");
store.register(project);
eventBus.fireEvent(new ResourceChangedEvent(
new ResourceDeltaImpl(project, (resource.isPresent() ? UPDATED : ADDED) | DERIVED)));
return (Project)project;
}));
});
}
protected Promise<Resource> move(final Resource source, final Path destination, final boolean force) {
checkArgument(!source.getLocation().isRoot(), "Workspace root is not allowed to be moved");
return findResource(destination, true).thenPromise(resource -> {
checkState(!resource.isPresent() || force, "Cannot create '" + destination.toString() + "'. Resource already exists.");
if (isResourceOpened(source)) {
deletedFilesController.add(source.getLocation().toString());
}
eventBus.fireEvent(newFileTrackingSuspendEvent());
store.dispose(source.getLocation(), !source.isFile()); //TODO: need to be tested
return ps.move(source.getLocation(), destination.parent(), destination.lastSegment(), force)
.thenPromise(ignored -> {
if (source.isProject() && source.getLocation().segmentCount() == 1) {
return ps.getProjects().then((Function<List<ProjectConfigDto>, Resource>)updatedConfigs -> {
eventBus.fireEvent(newFileTrackingResumeEvent());
//cache new configs
cachedConfigs = updatedConfigs.toArray(new ProjectConfigDto[updatedConfigs.size()]);
store.dispose(source.getLocation(), true);
for (ProjectConfigDto projectConfigDto : cachedConfigs) {
if (projectConfigDto.getPath().equals(destination.toString())) {
final Project newResource =
resourceFactory.newProjectImpl(projectConfigDto, ResourceManager.this);
store.register(newResource);
eventBus.fireEvent(new ResourceChangedEvent(new ResourceDeltaImpl(newResource, source,
ADDED | MOVED_FROM |
MOVED_TO |
DERIVED)));
return newResource;
}
}
throw new IllegalStateException("Resource not found");
});
}
return findResource(destination, false).then((Function<Optional<Resource>, Resource>)movedResource -> {
if (movedResource.isPresent()) {
eventBus.fireEvent(new ResourceChangedEvent(new ResourceDeltaImpl(movedResource.get(), source,
ADDED | MOVED_FROM |
MOVED_TO | DERIVED)));
eventBus.fireEvent(newFileTrackingResumeEvent());
return movedResource.get();
}
eventBus.fireEvent(newFileTrackingResumeEvent());
throw new IllegalStateException("Resource not found");
});
});
});
}
protected Promise<Resource> copy(final Resource source, final Path destination, final boolean force) {
checkArgument(!source.getLocation().isRoot(), "Workspace root is not allowed to be copied");
return findResource(destination, true).thenPromise(resource -> {
checkState(!resource.isPresent() || force, "Cannot create '" + destination.toString() + "'. Resource already exists.");
return ps.copy(source.getLocation(), destination.parent(), destination.lastSegment(), force)
.thenPromise(ignored -> findResource(destination, false)
.then((Function<Optional<Resource>, Resource>)copiedResource -> {
if (copiedResource.isPresent()) {
eventBus.fireEvent(new ResourceChangedEvent(new ResourceDeltaImpl(copiedResource.get(), source,
ADDED | COPIED_FROM | DERIVED)));
return copiedResource.get();
}
throw new IllegalStateException(
"Resource not found");
}));
});
}
protected Promise<Void> delete(final Resource resource) {
checkArgument(!resource.getLocation().isRoot(), "Workspace root is not allowed to be moved");
return ps.deleteItem(resource.getLocation()).then((Function<Void, Void>)ignored -> {
Resource[] descToRemove = null;
if (resource instanceof Container) {
final Optional<Resource[]> optDescendants = store.getAll(resource.getLocation());
if (optDescendants.isPresent()) {
descToRemove = optDescendants.get();
}
}
store.dispose(resource.getLocation(), !resource.isFile());
if (isResourceOpened(resource)) {
deletedFilesController.add(resource.getLocation().toString());
}
eventBus.fireEvent(new ResourceChangedEvent(new ResourceDeltaImpl(resource, REMOVED | DERIVED)));
if (descToRemove != null) {
for (Resource toRemove : descToRemove) {
if (isResourceOpened(resource)) {
deletedFilesController.add(toRemove.getLocation().toString());
}
eventBus.fireEvent(new ResourceChangedEvent(new ResourceDeltaImpl(toRemove, REMOVED | DERIVED)));
}
}
return null;
});
}
protected Promise<Void> write(final File file, String content) {
checkArgument(content != null, "Null content occurred");
return ps.setFileContent(file.getLocation(), content);
}
protected Promise<String> read(File file) {
return ps.getFileContent(file.getLocation());
}
Promise<Resource[]> getRemoteResources(final Container container, final int depth, boolean includeFiles) {
checkArgument(depth > -2, "Invalid depth");
if (depth == DEPTH_ZERO) {
return promises.resolve(NO_RESOURCES);
}
int depthToReload = depth;
final Optional<Resource[]> descendants = store.getAll(container.getLocation());
if (depthToReload != -1 && descendants.isPresent()) {
for (Resource resource : descendants.get()) {
if (resource.getLocation().segmentCount() - container.getLocation().segmentCount() > depth) {
depthToReload = resource.getLocation().segmentCount() - container.getLocation().segmentCount();
}
}
}
return ps.getTree(container.getLocation(), depthToReload, includeFiles).then(new Function<TreeElement, Resource[]>() {
@Override
public Resource[] apply(TreeElement tree) throws FunctionException {
class Visitor implements ResourceVisitor {
Resource[] resources;
private int size = 0; //size of total items
private int incStep = 50; //step to increase resource array
private Visitor() {
this.resources = NO_RESOURCES;
}
@Override
public void visit(Resource resource) {
if (resource.isProject()) {
inspectProject(resource.asProject());
}
if (size > resources.length - 1) { //check load factor and increase resource array
resources = copyOf(resources, resources.length + incStep);
}
resources[size++] = resource;
}
}
final Visitor visitor = new Visitor();
traverse(tree, visitor);
return copyOf(visitor.resources, visitor.size);
}
}).then((Function<Resource[], Resource[]>)reloaded -> {
Resource[] result = new Resource[0];
if (descendants.isPresent()) {
Resource[] outdated = descendants.get();
final Resource[] removed = removeAll(outdated, reloaded, false);
for (Resource resource : removed) {
store.dispose(resource.getLocation(), false);
eventBus.fireEvent(new ResourceChangedEvent(new ResourceDeltaImpl(resource, REMOVED)));
}
final Resource[] updated = removeAll(outdated, reloaded, true);
for (Resource resource : updated) {
store.register(resource);
eventBus.fireEvent(new ResourceChangedEvent(new ResourceDeltaImpl(resource, UPDATED)));
final Optional<Resource> registered = store.getResource(resource.getLocation());
if (registered.isPresent()) {
result = Arrays.add(result, registered.get());
}
}
final Resource[] added = removeAll(reloaded, outdated, false);
for (Resource resource : added) {
store.register(resource);
eventBus.fireEvent(new ResourceChangedEvent(new ResourceDeltaImpl(resource, ADDED)));
final Optional<Resource> registered = store.getResource(resource.getLocation());
if (registered.isPresent()) {
result = Arrays.add(result, registered.get());
}
}
} else {
for (Resource resource : reloaded) {
store.register(resource);
eventBus.fireEvent(new ResourceChangedEvent(new ResourceDeltaImpl(resource, ADDED)));
final Optional<Resource> registered = store.getResource(resource.getLocation());
if (registered.isPresent()) {
result = Arrays.add(result, registered.get());
}
}
}
return result;
});
}
Promise<Optional<Container>> getContainer(final Path absolutePath) {
return findResource(absolutePath, false).then((Function<Optional<Resource>, Optional<Container>>)optionalFolder -> {
if (optionalFolder.isPresent()) {
final Resource resource = optionalFolder.get();
checkState(resource instanceof Container, "Not a container");
return of((Container)resource);
}
return absent();
});
}
protected Promise<Optional<File>> getFile(final Path absolutePath) {
final Optional<Resource> resourceOptional = store.getResource(absolutePath);
if (resourceOptional.isPresent() && resourceOptional.get().isFile()) {
return promises.resolve(of(resourceOptional.get().asFile()));
}
if (store.getResource(absolutePath.parent()).isPresent()) {
return findResource(absolutePath, true).thenPromise(optionalFile -> {
if (optionalFile.isPresent()) {
final Resource resource = optionalFile.get();
checkState(resource.getResourceType() == FILE, "Not a file");
return promises.resolve(of((File)resource));
}
return promises.resolve(absent());
});
} else {
return findResourceForExternalOperation(absolutePath, true).thenPromise(optionalFile -> {
if (optionalFile.isPresent()) {
final Resource resource = optionalFile.get();
checkState(resource.getResourceType() == FILE, "Not a file");
return promises.resolve(of((File)resource));
}
return promises.resolve(absent());
});
}
}
Optional<Container> parentOf(Resource resource) {
final Path parentLocation = resource.getLocation().segmentCount() == 1 ? Path.ROOT : resource.getLocation().parent();
final Optional<Resource> optionalParent = store.getResource(parentLocation);
if (!optionalParent.isPresent()) {
return absent();
}
final Resource parentResource = optionalParent.get();
checkState(parentResource instanceof Container, "Parent resource is not a container");
return of((Container)parentResource);
}
Promise<Resource[]> childrenOf(final Container container, boolean forceUpdate) {
if (forceUpdate) {
return getRemoteResources(container, DEPTH_ONE, true);
}
final Optional<Resource[]> optChildren = store.get(container.getLocation());
if (optChildren.isPresent()) {
return promises.resolve(optChildren.get());
} else {
return promises.resolve(NO_RESOURCES);
}
}
private Promise<Optional<Resource>> findResource(final Path absolutePath, boolean quiet) {
return ps.getItem(absolutePath).thenPromise(itemReference -> {
final Resource resource = newResourceFrom(itemReference);
store.dispose(absolutePath, false);
store.register(resource);
if (resource.isProject()) {
inspectProject(resource.asProject());
}
return promises.resolve(fromNullable(resource));
}).catchErrorPromise(arg -> {
if (!quiet) {
throw new IllegalStateException(arg.getCause());
}
return promises.resolve(absent());
});
}
private Promise<Optional<Resource>> findResourceForExternalOperation(final Path absolutePath, boolean quiet) {
Promise<Void> derived = promises.resolve(null);
for (int i = absolutePath.segmentCount() - 1; i > 0; i
final Path pathToCache = absolutePath.removeLastSegments(i);
derived = derived.thenPromise(arg -> loadAndRegisterResources(pathToCache));
}
return derived.thenPromise(ignored -> findResource(absolutePath, quiet));
}
private Promise<Void> loadAndRegisterResources(Path absolutePath) {
return ps.getTree(absolutePath, 1, true).thenPromise(treeElement -> {
final Optional<Resource[]> optionalChildren = store.get(absolutePath);
if (optionalChildren.isPresent()) {
for (Resource child : optionalChildren.get()) {
store.dispose(child.getLocation(), false);
}
}
for (TreeElement element : treeElement.getChildren()) {
final Resource resource = newResourceFrom(element.getNode());
if (resource.isProject()) {
inspectProject(resource.asProject());
}
store.register(resource);
}
return promises.resolve(null);
});
}
private void inspectProject(Project project) {
final Optional<ProjectConfigDto> optionalConfig = findProjectConfigDto(project.getLocation());
if (optionalConfig.isPresent()) {
final Optional<ProblemProjectMarker> optionalMarker = getProblemMarker(optionalConfig.get());
if (optionalMarker.isPresent()) {
project.addMarker(optionalMarker.get());
}
}
}
private boolean isResourceOpened(final Resource resource) {
if (!resource.isFile()) {
return false;
}
File file = (File)resource;
for (EditorPartPresenter editor : editorAgent.getOpenedEditors()) {
Path editorPath = editor.getEditorInput().getFile().getLocation();
if (editorPath.equals(file.getLocation())) {
return true;
}
}
return false;
}
private void traverse(TreeElement tree, ResourceVisitor visitor) {
for (final TreeElement element : tree.getChildren()) {
final Resource resource = newResourceFrom(element.getNode());
visitor.visit(resource);
if (resource instanceof Container) {
traverse(element, visitor);
}
}
}
private Resource newResourceFrom(final ItemReference reference) {
final Path path = Path.valueOf(reference.getPath());
switch (reference.getType()) {
case "file":
final Link link = reference.getLink(GET_CONTENT_REL);
return resourceFactory.newFileImpl(path, link.getHref(), this);
case "folder":
return resourceFactory.newFolderImpl(path, this);
case "project":
final Optional<ProjectConfigDto> config = findProjectConfigDto(path);
if (config.isPresent()) {
return resourceFactory.newProjectImpl(config.get(), this);
} else {
return resourceFactory.newFolderImpl(path, this);
}
default:
throw new IllegalArgumentException("Failed to recognize resource type to create.");
}
}
private Optional<ProjectConfigDto> findProjectConfigDto(final Path path) {
for (ProjectConfigDto config : cachedConfigs) {
if (Path.valueOf(config.getPath()).equals(path)) {
return of(config);
}
}
return absent();
}
private Optional<ProblemProjectMarker> getProblemMarker(ProjectConfigDto projectConfigDto) {
List<ProjectProblemDto> problems = projectConfigDto.getProblems();
if (problems == null || problems.isEmpty()) {
return absent();
}
Map<Integer, String> code2Message = new HashMap<>(problems.size());
for (ProjectProblemDto problem : problems) {
code2Message.put(problem.getCode(), problem.getMessage());
}
return of(new ProblemProjectMarker(code2Message));
}
protected Promise<Resource[]> synchronize(final Container container) {
return ps.getProjects().thenPromise(updatedConfiguration -> {
cachedConfigs = updatedConfiguration.toArray(new ProjectConfigDto[updatedConfiguration.size()]);
int maxDepth = 1;
final Optional<Resource[]> descendants = store.getAll(container.getLocation());
if (descendants.isPresent()) {
final Resource[] resources = descendants.get();
for (Resource resource : resources) {
final int segCount = resource.getLocation().segmentCount() - container.getLocation().segmentCount();
if (segCount > maxDepth) {
maxDepth = segCount;
}
}
}
final Container[] holder = new Container[]{container};
if (holder[0].isProject()) {
final Optional<ProjectConfigDto> config = findProjectConfigDto(holder[0].getLocation());
if (config.isPresent()) {
final ProjectImpl project = resourceFactory.newProjectImpl(config.get(), ResourceManager.this);
store.register(project);
holder[0] = project;
}
}
return getRemoteResources(holder[0], maxDepth, true).then((Function<Resource[], Resource[]>)resources -> {
eventBus.fireEvent(new ResourceChangedEvent(new ResourceDeltaImpl(holder[0], SYNCHRONIZED | DERIVED)));
return resources;
});
});
}
protected Promise<ResourceDelta[]> synchronize(final ResourceDelta[] deltas) {
Promise<Void> promise = promises.resolve(null);
for (final ResourceDelta delta : deltas) {
if (delta.getKind() == ADDED) {
if (delta.getFlags() == (MOVED_FROM | MOVED_TO)) {
promise.thenPromise(ignored -> onExternalDeltaMoved(delta));
} else {
promise.thenPromise(ignored -> onExternalDeltaAdded(delta));
}
} else if (delta.getKind() == REMOVED) {
promise.thenPromise(ignored -> onExternalDeltaRemoved(delta));
} else if (delta.getKind() == UPDATED) {
promise.thenPromise(ignored -> onExternalDeltaUpdated(delta));
}
}
return promise.thenPromise(ignored -> promises.resolve(deltas));
}
private Promise<Void> onExternalDeltaMoved(final ResourceDelta delta) {
final Optional<Resource> toRemove = store.getResource(delta.getFromPath());
store.dispose(delta.getFromPath(), true);
return findResourceForExternalOperation(delta.getToPath(), true).thenPromise(resource -> {
if (resource.isPresent() && toRemove.isPresent()) {
Resource intercepted = resource.get();
if (!store.getResource(intercepted.getLocation()).isPresent()) {
store.register(intercepted);
}
eventBus.fireEvent(new ResourceChangedEvent(new ResourceDeltaImpl(intercepted, toRemove.get(),
ADDED | MOVED_FROM | MOVED_TO | DERIVED)));
}
return promises.resolve(null);
});
}
private Promise<Void> onExternalDeltaAdded(final ResourceDelta delta) {
if (delta.getToPath().segmentCount() == 1) {
return ps.getProjects().thenPromise(updatedConfiguration -> {
cachedConfigs = updatedConfiguration.toArray(new ProjectConfigDto[updatedConfiguration.size()]);
for (ProjectConfigDto config : cachedConfigs) {
if (Path.valueOf(config.getPath()).equals(delta.getToPath())) {
final Project project = resourceFactory.newProjectImpl(config, ResourceManager.this);
store.register(project);
eventBus.fireEvent(new ResourceChangedEvent(new ResourceDeltaImpl(project, ADDED)));
}
}
return promises.resolve(null);
});
}
return findResourceForExternalOperation(delta.getToPath(), true).thenPromise(resource -> {
if (resource.isPresent()) {
Resource intercepted = resource.get();
if (!store.getResource(intercepted.getLocation()).isPresent()) {
store.register(intercepted);
}
eventBus.fireEvent(new ResourceChangedEvent(new ResourceDeltaImpl(intercepted, ADDED | DERIVED)));
}
return promises.resolve(null);
});
}
private Promise<Void> onExternalDeltaUpdated(final ResourceDelta delta) {
if (delta.getToPath().segmentCount() == 0) {
workspaceRoot.synchronize();
return null;
}
return findResourceForExternalOperation(delta.getToPath(), true).thenPromise(resource -> {
if (resource.isPresent()) {
eventBus.fireEvent(new ResourceChangedEvent(new ResourceDeltaImpl(resource.get(), UPDATED | DERIVED)));
}
return promises.resolve(null);
});
}
private Promise<Void> onExternalDeltaRemoved(final ResourceDelta delta) {
final Optional<Resource> resourceOptional = store.getResource(delta.getFromPath());
if (resourceOptional.isPresent()) {
final Resource resource = resourceOptional.get();
store.dispose(resource.getLocation(), true);
eventBus.fireEvent(new ResourceChangedEvent(new ResourceDeltaImpl(resource, REMOVED | DERIVED)));
}
return promises.resolve(null);
}
protected Promise<Resource[]> search(final Container container, String fileMask, String contentMask) {
QueryExpression queryExpression = new QueryExpression();
if (!isNullOrEmpty(contentMask)) {
queryExpression.setText(contentMask);
}
if (!isNullOrEmpty(fileMask)) {
queryExpression.setName(fileMask);
}
if (!container.getLocation().isRoot()) {
queryExpression.setPath(container.getLocation().toString());
}
return ps.search(queryExpression).thenPromise(references -> {
if (references.isEmpty()) {
return promises.resolve(NO_RESOURCES);
}
int maxDepth = 0;
final Path[] paths = new Path[references.size()];
for (int i = 0; i < paths.length; i++) {
final Path path = Path.valueOf(references.get(i).getPath());
paths[i] = path;
if (path.segmentCount() > maxDepth) {
maxDepth = path.segmentCount();
}
}
return getRemoteResources(container, maxDepth, true).then((Function<Resource[], Resource[]>)resources -> {
Resource[] filtered = NO_RESOURCES;
Path[] mutablePaths = paths;
outer:
for (Resource resource : resources) {
if (resource.getResourceType() != FILE) {
continue;
}
for (int i = 0; i < mutablePaths.length; i++) {
Path path = mutablePaths[i];
if (path.segmentCount() == resource.getLocation().segmentCount() && path.equals(resource.getLocation())) {
Resource[] tmpFiltered = copyOf(filtered, filtered.length + 1);
tmpFiltered[filtered.length] = resource;
filtered = tmpFiltered;
//reduce the size of mutablePaths by removing already checked item
int size = mutablePaths.length;
int numMoved = mutablePaths.length - i - 1;
if (numMoved > 0) {
arraycopy(mutablePaths, i + 1, mutablePaths, i, numMoved);
}
mutablePaths = copyOf(mutablePaths, --size);
continue outer;
}
}
}
return filtered;
});
});
}
Promise<SourceEstimation> estimate(Container container, String projectType) {
checkArgument(projectType != null, "Null project type");
checkArgument(!projectType.isEmpty(), "Empty project type");
return ps.estimate(container.getLocation(), projectType);
}
void notifyMarkerChanged(Resource resource, Marker marker, int status) {
eventBus.fireEvent(new MarkerChangedEvent(resource, marker, status));
eventBus.fireEvent(new ResourceChangedEvent(new ResourceDeltaImpl(resource, UPDATED)));
}
protected String getUrl(Resource resource) {
checkArgument(!resource.getLocation().isRoot(), "Workspace root doesn't have export URL");
final String baseUrl = devMachine.getWsAgentBaseUrl() + "/project/export";
if (resource.getResourceType() == FILE) {
return baseUrl + "/file" + resource.getLocation();
}
return urlModifier.modify(baseUrl + resource.getLocation());
}
public Promise<List<SourceEstimation>> resolve(Project project) {
return ps.resolveSources(project.getLocation());
}
interface ResourceVisitor {
void visit(Resource resource);
}
public interface ResourceFactory {
ProjectImpl newProjectImpl(ProjectConfig reference, ResourceManager resourceManager);
FolderImpl newFolderImpl(Path path, ResourceManager resourceManager);
FileImpl newFileImpl(Path path, String contentUrl, ResourceManager resourceManager);
}
public interface ResourceManagerFactory {
ResourceManager newResourceManager(DevMachine devMachine);
}
}
|
package org.innovateuk.ifs.finance.resource.cost;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class GrantClaimAmount extends AbstractFinanceRowItem implements GrantClaim {
private Long id;
private BigDecimal amount;
private GrantClaimAmount() {
this(null);
}
public GrantClaimAmount(Long targetId) {
super(targetId);
}
public GrantClaimAmount(Long id, BigDecimal amount, Long targetId) {
this(targetId);
this.id = id;
this.amount = amount;
}
@Override
public Long getId() {
return id;
}
@Override
public BigDecimal getTotal() {
return amount;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
@Override
@JsonIgnore
public String getName() {
return getCostType().getType();
}
@Override
@JsonIgnore
public boolean isEmpty() {
return false;
}
@Override
@JsonIgnore
public FinanceRowType getCostType() {
return FinanceRowType.GRANT_CLAIM_AMOUNT;
}
@Override
public void reset() {
// The grant claim amount doesn't get reset by research cat or organisation size.
}
@Override
public BigDecimal calculateClaimPercentage(BigDecimal total, BigDecimal totalOtherFunding) {
if (amount == null || total.compareTo(totalOtherFunding) == 0 || total.equals(BigDecimal.ZERO)) {
return BigDecimal.ZERO;
}
BigDecimal roundedCosts = total.setScale(0, BigDecimal.ROUND_HALF_EVEN); //Same as thymeleaf
return amount.add(totalOtherFunding)
.multiply(new BigDecimal(100))
.divide(roundedCosts, 2, RoundingMode.HALF_UP);
}
@Override
public BigDecimal calculateFundingSought(BigDecimal total, BigDecimal totalOtherFunding) {
return (amount == null ? BigDecimal.ZERO : amount)
.max(BigDecimal.ZERO);
}
@Override
@JsonIgnore
public boolean isRequestingFunding() {
return amount != null && !amount.equals(BigDecimal.ZERO);
}
}
|
package com.sometrik.framework;
import com.sometrik.framework.NativeCommand.Selector;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.text.Layout;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
public class FWDialog extends Dialog implements NativeCommandHandler {
private FrameWork frame;
private LinearLayout baseView;
private int id;
private ViewStyleManager normalStyle, activeStyle, currentStyle;
private FWTextView titleView;
public FWDialog(final FrameWork frame, final int id) {
super(frame);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.frame = frame;
this.id = id;
baseView = new LinearLayout(frame);
baseView.setOrientation(LinearLayout.VERTICAL);
setContentView(baseView);
LayoutParams params = getWindow().getAttributes();
params.height = LayoutParams.WRAP_CONTENT;
params.width = LayoutParams.MATCH_PARENT;
getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
final float scale = getContext().getResources().getDisplayMetrics().density;
this.normalStyle = currentStyle = new ViewStyleManager(frame.bitmapCache, scale, true);
this.activeStyle = new ViewStyleManager(frame.bitmapCache, scale, false);
titleView = new FWTextView(frame, false);
titleView.setStyle(Selector.NORMAL, "background-color", "#ffffff");
titleView.setStyle(Selector.NORMAL, "width", "match-parent");
titleView.setStyle(Selector.NORMAL, "gravity", "center-horizontal");
titleView.setStyle(Selector.NORMAL, "height", "wrap-content");
titleView.setStyle(Selector.NORMAL, "font-size", "24");
titleView.setStyle(Selector.NORMAL, "padding-top", "12");
titleView.setStyle(Selector.NORMAL, "padding-bottom", "12");
titleView.setStyle(Selector.NORMAL, "font-weight", "bold");
titleView.setStyle(Selector.NORMAL, "padding-left", "14");
titleView.setStyle(Selector.NORMAL, "color", "#c1272d");
titleView.applyStyles();
baseView.addView(titleView);
LinearLayout dividerView = new LinearLayout(frame);
LinearLayout.LayoutParams dividerParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 5);
dividerView.setBackgroundColor(Color.parseColor("#c1272d"));
dividerView.setLayoutParams(dividerParams);
baseView.addView(dividerView);
this.setOnCancelListener(new OnCancelListener(){
@Override
public void onCancel(DialogInterface arg0) {
frame.intChangedEvent(id, 0, 0);
}
});
show();
}
public View getContentView() {
return baseView;
}
@Override
public void onScreenOrientationChange(boolean isLandscape) {
}
@Override
public void addChild(View view) {
baseView.addView(view);
}
@Override
public void addOption(int optionId, String text) {
System.out.println("FWDialog couldn't handle command");
}
@Override
public void addData(String text, int row, int column, int sheet) {
System.out.println("FWDialog couldn't handle command");
}
@Override
public void setValue(String v) {
titleView.setText(v);
}
@Override
public void setValue(int v) { }
@Override
public void setViewVisibility(boolean visible) {
if (visible) {
show();
} else {
dismiss();
}
}
@Override
public void setStyle(Selector selector, String key, String value) {
if (selector == Selector.NORMAL) {
normalStyle.setStyle(key, value);
} else if (selector == Selector.ACTIVE) {
activeStyle.setStyle(key, value);
}
}
@Override
public void applyStyles() {
currentStyle.apply(this);
}
@Override
public void setError(boolean hasError, String errorText) { }
@Override
public void clear() {
dismiss();
}
@Override
public int getElementId() {
return id;
}
@Override
public void flush() {
// TODO Auto-generated method stub
}
@Override
public void addColumn(String text, int columnType) {
// TODO Auto-generated method stub
}
@Override
public void reshape(int value, int size) {
// TODO Auto-generated method stub
}
@Override
public void setBitmap(Bitmap bitmap) { }
@Override
public void reshape(int size) {
// TODO Auto-generated method stub
}
@Override
public void deinitialize() {
dismiss();
}
@Override
public void addImageUrl(String url, int width, int height) {
// TODO Auto-generated method stub
}
}
|
package candystore.datainjection;
import static org.fest.assertions.api.Assertions.assertThat;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import atf.toolbox.data.ScenarioData;
import atf.toolbox.data.TestDataProvider;
import atf.toolbox.data.XMLDataDriver;
/**
* CalculatorTest 1. Use the ATF Toolbox DataProvider 2. Use the ATF Toolbox
* XMLDataDriver to drive data from xml into the tests
*/
public class CalculatorTest
{
private static TestDataProvider atfTestDataProvider;
private static String testDataFilename = "datainjection-calculator-test-data.xml";
@BeforeClass(alwaysRun = true)
public static void beforeClassSetup()
{
atfTestDataProvider = new TestDataProvider();
}
@DataProvider(name = "AddTwoNumbers")
public static Object[][] additionData()
{
String testCaseName = "Test Case: Add 2 Numbers";
return atfTestDataProvider.Initialize(new XMLDataDriver(testDataFilename, testCaseName));
}
@DataProvider(name = "MultipleTwoNumbers")
public static Object[][] multiplicationData()
{
String testCaseName = "Test Case: Multiply 2 Numbers";
return atfTestDataProvider.Initialize(new XMLDataDriver(testDataFilename, testCaseName));
}
@Test(dataProvider = "AddTwoNumbers", groups = { "datainjection" })
public void addTwoNumbers(ScenarioData scenario)
{
int num1 = scenario.getIntParameterData("firstNumber");
int num2 = scenario.getIntParameterData("secondNumber");
int expectedResult = scenario.getIntParameterData("expectedSum");
assertThat((num1 + num2)).isEqualTo(expectedResult);
}
@Test(dataProvider = "MultipleTwoNumbers", groups = { "datainjection" })
public void multiplyTwoNumbers(ScenarioData scenario)
{
int num1 = scenario.getIntParameterData("firstNumber");
int num2 = scenario.getIntParameterData("secondNumber");
int expectedResult = scenario.getIntParameterData("expectedProduct");
assertThat((num1 * num2)).isEqualTo(expectedResult);
}
}
|
package us.dot.its.jpo.ode.services.vsd;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import us.dot.its.jpo.ode.OdeProperties;
import us.dot.its.jpo.ode.plugin.j2735.J2735Bsm;
import us.dot.its.jpo.ode.wrapper.MessageConsumer;
import us.dot.its.jpo.ode.wrapper.MessageProducer;
// TODO fix this class
// @Controller
public class BsmToVsdPackagerController {
private static final Logger logger = LoggerFactory.getLogger(BsmToVsdPackagerController.class);
@Autowired
private BsmToVsdPackagerController(OdeProperties odeProps) {
super();
String inputTopic = odeProps.getKafkaTopicBsmRawJson(); // TODO - needs to
// be filtered
String outputTopic = odeProps.getKafkaTopicEncodedVsd();
if (odeProps.isEnabledVsdKafkaTopic()) {
logger.info("Converting {} records from topic {} and publishing to topic {} ", J2735Bsm.class.getSimpleName(),
inputTopic, outputTopic);
BsmToVsdPackager<String> converter = new BsmToVsdPackager<>(MessageProducer.defaultByteArrayMessageProducer(
odeProps.getKafkaBrokers(), odeProps.getKafkaProducerType()), outputTopic);
MessageConsumer<String, String> consumer = new MessageConsumer<>(odeProps.getKafkaBrokers(),
this.getClass().getSimpleName(), converter);
consumer.setName(this.getClass().getSimpleName());
converter.start(consumer, inputTopic);
} else {
logger.warn("WARNING - VSD Kafka topic disabled, BSM-to-VSD packager not started.");
}
}
}
|
package org.seedstack.hub.rest.admin;
import org.seedstack.hub.application.fetch.ImportService;
import org.seedstack.hub.domain.model.component.Component;
import org.seedstack.hub.domain.model.component.Source;
import org.seedstack.hub.rest.component.list.ComponentCard;
import org.seedstack.hub.rest.component.list.ComponentCardAssembler;
import org.seedstack.seed.Logging;
import org.seedstack.seed.rest.Rel;
import org.seedstack.seed.security.RequiresRoles;
import org.slf4j.Logger;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import java.time.Duration;
import java.util.List;
import java.util.stream.Collectors;
import static org.seedstack.hub.rest.Rels.IMPORT_LIST;
@Path("/admin")
@Produces({"application/json", "application/hal+json"})
public class AdminResource {
@Logging
private Logger logger;
@Inject
private ImportService importService;
@Inject
private ComponentCardAssembler assembler;
@POST
@RequiresRoles("admin")
@Path("/import")
@Rel(value = IMPORT_LIST, home = true)
@Consumes({"application/json"})
public Response importList(List<Source> sources) {
long startTime = System.currentTimeMillis();
List<ComponentCard> componentCards = sources.parallelStream()
.map(source -> {
logger.info("importing " + source.getUrl());
Component component = importService.importComponent(source);
logger.info("imported " + source.getUrl());
return component;
})
.map(assembler::assembleDtoFromAggregate)
.collect(Collectors.toList());
long stopTime = System.currentTimeMillis();
logger.info(Duration.ofMillis(stopTime - startTime).toString());
return Response.ok().entity(componentCards).build();
}
}
|
package aQute.bnd.osgi.repository;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.osgi.resource.Resource;
import aQute.bnd.header.Attrs;
import aQute.bnd.osgi.Processor;
import aQute.bnd.osgi.resource.CapReqBuilder;
import aQute.bnd.osgi.resource.ResourceBuilder;
import aQute.libg.gzip.GZipUtils;
public class XMLResourceParser extends Processor {
final static XMLInputFactory inputFactory = XMLInputFactory.newInstance();
static {
inputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
inputFactory.setProperty(XMLInputFactory.IS_VALIDATING, false);
inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
}
private static final String NS_URI = "http:
private static final String TAG_REPOSITORY = "repository";
private static final String TAG_REFERRAL = "referral";
private static final String TAG_RESOURCE = "resource";
private static final String TAG_CAPABILITY = "capability";
private static final String TAG_REQUIREMENT = "requirement";
private static final String TAG_ATTRIBUTE = "attribute";
private static final String TAG_DIRECTIVE = "directive";
private static final String ATTR_REFERRAL_URL = "url";
private static final String ATTR_REFERRAL_DEPTH = "depth";
private static final String ATTR_NAMESPACE = "namespace";
private static final String ATTR_NAME = "name";
private static final String ATTR_VALUE = "value";
private static final String ATTR_TYPE = "type";
final private List<Resource> resources = new ArrayList<>();
final private XMLStreamReader reader;
final private Set<URI> traversed;
final private String what;
@SuppressWarnings("unused")
final private URI url;
private int depth;
public XMLResourceParser(URI url) throws Exception {
this(url.toURL().openStream(), url.toString(), url);
}
public XMLResourceParser(InputStream in, String what, URI uri) throws Exception {
this(in, what, 100, new HashSet<URI>(), uri);
}
public void setDepth(int n) {
this.depth = n;
}
public XMLResourceParser(InputStream in, String what, int depth, Set<URI> traversed, URI url) throws Exception {
this.what = what;
this.depth = depth;
this.traversed = traversed;
this.url = url;
reader = inputFactory.createXMLStreamReader(GZipUtils.detectCompression(in));
}
List<Resource> getResources() {
if (!isOk())
return null;
return resources;
}
public List<Resource> parse() throws Exception {
if (!check(reader.hasNext(), "No content found"))
return null;
next();
if (!check(reader.isStartElement(), "Expected a start element at the root, is %s", reader.getEventType()))
return null;
String name = reader.getLocalName();
if (!check(TAG_REPOSITORY.equals(name), "Invalid tag name of top element, expected %s, got %s", TAG_REPOSITORY,
name))
return null;
String nsUri = reader.getNamespaceURI();
if (nsUri != null) {
check(NS_URI.equals(nsUri), "Incorrect namespace. Expected %s, got %s", NS_URI, nsUri);
}
next(); // either start resource/referral or end
while (reader.isStartElement()) {
String localName = reader.getLocalName();
if (localName.equals(TAG_REFERRAL))
parseReferral();
else if (localName.equals(TAG_RESOURCE))
parseResource(resources);
else {
check(false, "Unexpected element %s", localName);
next();
}
}
check(reader.isEndElement() && reader.getLocalName().equals(TAG_REPOSITORY),
"Expected to be at the end but are on %s", reader.getLocalName());
return getResources();
}
public void next() throws XMLStreamException {
report();
reader.nextTag();
}
private void report() {
if (reader.isStartElement()) {
trace("<%s>", reader.getLocalName());
} else if (reader.isEndElement()) {
trace("</%s>", reader.getLocalName());
} else {
trace("** unknown element %s", reader.getEventType());
}
}
private void parseReferral() throws Exception {
if (--depth < 0)
error("Too deep, traversed %s", traversed);
else {
String depthString = reader.getAttributeValue(NS_URI, ATTR_REFERRAL_DEPTH);
String urlString = reader.getAttributeValue(NS_URI, ATTR_REFERRAL_URL);
if (check(urlString != null, "Expected URL in referral")) {
// TODO resolve url
URI url = new URI(urlString);
traversed.add(url);
int depth = 100;
if (depthString != null) {
depth = Integer.parseInt(depthString);
}
InputStream in = url.toURL().openStream();
try (XMLResourceParser referralParser = new XMLResourceParser(in, urlString, depth, traversed, url);) {
referralParser.parse();
resources.addAll(referralParser.resources);
}
}
}
tagEnd(TAG_REFERRAL);
}
private void tagEnd(String tag) throws XMLStreamException {
if (!check(reader.isEndElement(), "Expected end element, got %s for %s (%s)", reader.getEventType(), tag,
reader.getLocalName())) {
trace("oops, invalid end %s", tag);
}
next();
}
private void parseResource(List<Resource> resources) throws Exception {
ResourceBuilder resourceBuilder = new ResourceBuilder();
next();
while (reader.isStartElement()) {
parseCapabilityOrRequirement(resourceBuilder);
}
Resource resource = resourceBuilder.build();
resources.add(resource);
tagEnd(TAG_RESOURCE);
}
private void parseCapabilityOrRequirement(ResourceBuilder resourceBuilder) throws Exception {
String name = reader.getLocalName();
check(TAG_REQUIREMENT.equals(name) || TAG_CAPABILITY.equals(name), "Expected <%s> or <%s> tag, got <%s>",
TAG_REQUIREMENT, TAG_CAPABILITY, name);
String namespace = reader.getAttributeValue(null, ATTR_NAMESPACE);
CapReqBuilder capReqBuilder = new CapReqBuilder(namespace);
next();
while (reader.isStartElement()) {
parseAttributesOrDirectives(capReqBuilder);
}
if (TAG_REQUIREMENT.equals(name)) {
resourceBuilder.addRequirement(capReqBuilder);
} else {
resourceBuilder.addCapability(capReqBuilder);
}
tagEnd(name);
}
private void parseAttributesOrDirectives(CapReqBuilder capReqBuilder) throws Exception {
String name = reader.getLocalName();
switch (name) {
case TAG_ATTRIBUTE :
parseAttribute(capReqBuilder);
break;
case TAG_DIRECTIVE :
parseDirective(capReqBuilder);
break;
default :
check(false, "Invalid tag, expected either <%s> or <%s>, got <%s>", TAG_ATTRIBUTE, TAG_DIRECTIVE);
}
next();
tagEnd(name);
}
private boolean check(boolean check, String format, Object... args) {
if (check)
return true;
String message = String.format(format, args);
error("%s: %s", what, message);
return false;
}
private void parseAttribute(CapReqBuilder capReqBuilder) throws Exception {
String attributeName = reader.getAttributeValue(null, ATTR_NAME);
String attributeValue = reader.getAttributeValue(null, ATTR_VALUE);
String attributeType = reader.getAttributeValue(null, ATTR_TYPE);
Object value = Attrs.convert(attributeType, attributeValue);
capReqBuilder.addAttribute(attributeName, value);
}
private void parseDirective(CapReqBuilder capReqBuilder) throws XMLStreamException {
String attributeName = reader.getAttributeValue(null, ATTR_NAME);
String attributeValue = reader.getAttributeValue(null, ATTR_VALUE);
String attributeType = reader.getAttributeValue(null, ATTR_TYPE);
check(attributeType == null, "Expected a directive to have no type: %s:%s=%s", attributeName, attributeType,
attributeValue);
capReqBuilder.addDirective(attributeName, attributeValue);
}
}
|
package org.languagetool.rules.spelling;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.jetbrains.annotations.NotNull;
import org.languagetool.JLanguageTool;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
/**
* Helper to load text files from classpath.
* @since 3.3, public since 3.5
*/
public class CachingWordListLoader {
// Speed up the server use case, where rules get initialized for every call.
private static final LoadingCache<String, List<String>> cache = CacheBuilder.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(new CacheLoader<String, List<String>>() {
@Override
public List<String> load(@NotNull String fileInClassPath) throws IOException {
return loadWordsFromPath(fileInClassPath);
}
});
private static List<String> loadWordsFromPath(String filePath) throws IOException {
List<String> result = new ArrayList<>();
if (!JLanguageTool.getDataBroker().resourceExists(filePath)) {
return result;
}
try (InputStream inputStream = JLanguageTool.getDataBroker().getFromResourceDirAsStream(filePath);
Scanner scanner = new Scanner(inputStream, "utf-8")) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.isEmpty()) {
continue;
}
if (line.startsWith("
continue;
}
if (line.trim().length() < line.length()) {
throw new RuntimeException("No leading or trailing space expected in " + filePath + ": '" + line + "'");
}
result.add(line.replaceFirst("
}
}
return result;
}
public List<String> loadWords(String filePath) throws IOException {
return cache.getUnchecked(filePath);
}
}
|
package cz.xtf.builder.builders;
import cz.xtf.builder.OpenShiftApplication;
import cz.xtf.builder.db.OpenShiftAuxiliary;
import cz.xtf.core.bm.ManagedBuildReference;
import io.fabric8.kubernetes.api.model.ConfigMap;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.PersistentVolumeClaim;
import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.openshift.api.model.BuildConfig;
import io.fabric8.openshift.api.model.DeploymentConfig;
import io.fabric8.openshift.api.model.ImageStream;
import io.fabric8.openshift.api.model.Role;
import io.fabric8.openshift.api.model.RoleBinding;
import io.fabric8.openshift.api.model.Route;
import lombok.extern.slf4j.Slf4j;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@Slf4j
public class ApplicationBuilder {
public static ApplicationBuilder fromImage(String name, String imageUrl) {
ApplicationBuilder appBuilder = new ApplicationBuilder(name);
appBuilder.deploymentConfig().onConfigurationChange().podTemplate().container().fromImage(imageUrl);
return appBuilder;
}
public static ApplicationBuilder fromManagedBuild(String name, ManagedBuildReference mbr) {
ApplicationBuilder appBuilder = new ApplicationBuilder(name);
appBuilder.deploymentConfig().onImageChange().onConfigurationChange().podTemplate().container().fromImage(mbr.getNamespace(), mbr.getStreamName());
return appBuilder;
}
public static ApplicationBuilder fromS2IBuild(String name, String imageUrl, String gitRepo) {
ApplicationBuilder appBuilder = new ApplicationBuilder(name);
appBuilder.buildConfig().onConfigurationChange().gitSource(gitRepo).setOutput(name).sti().forcePull(true).fromDockerImage(imageUrl);
appBuilder.imageStream();
appBuilder.deploymentConfig().onImageChange().onConfigurationChange().podTemplate().container().fromImage(name);
return appBuilder;
}
private final String applicationName;
private final Set<RouteBuilder> routes = new HashSet<>();
private final Set<ServiceBuilder> services = new HashSet<>();
private final Set<ImageStreamBuilder> images = new HashSet<>();
private final Set<DeploymentConfigBuilder> deployments = new HashSet<>();
private final Set<BuildConfigBuilder> builds = new HashSet<>();
private final Set<SecretBuilder> secrets = new HashSet<>();
private final Set<ConfigMapWithPropertyFilesBuilder> configMaps = new HashSet<>();
private final Set<RoleBuilder> roles = new HashSet<>();
private final Set<RoleBindingBuilder> roleBindings = new HashSet<>();
private final Set<PVCBuilder> persistentVolumeClaims = new HashSet<>();
public ApplicationBuilder(String name) {
this.applicationName = name;
}
public String getName() {
return applicationName;
}
public ImageStreamBuilder imageStream() {
return imageStream(applicationName);
}
public ImageStreamBuilder imageStream(String name) {
ImageStreamBuilder builder;
Optional<ImageStreamBuilder> orig = images.stream().filter(b -> b.getName().equals(name)).findFirst();
if (orig.isPresent()) {
builder = orig.get();
} else {
builder = new ImageStreamBuilder(this, name);
images.add(builder);
}
return builder;
}
public BuildConfigBuilder buildConfig() {
return buildConfig(applicationName);
}
public BuildConfigBuilder buildConfig(String name) {
BuildConfigBuilder builder;
Optional<BuildConfigBuilder> orig = builds.stream().filter(b -> b.getName().equals(name)).findFirst();
if (orig.isPresent()) {
builder = orig.get();
} else {
builder = new BuildConfigBuilder(this, name);
builds.add(builder);
}
return builder;
}
public DeploymentConfigBuilder deploymentConfig() {
return deploymentConfig(applicationName);
}
public DeploymentConfigBuilder deploymentConfig(String name) {
DeploymentConfigBuilder builder;
Optional<DeploymentConfigBuilder> orig = deployments.stream().filter(b -> b.getName().equals(name)).findFirst();
if (orig.isPresent()) {
builder = orig.get();
} else {
builder = new DeploymentConfigBuilder(this, name);
deployments.add(builder);
}
return builder;
}
public ServiceBuilder service() {
return service(applicationName);
}
public ServiceBuilder service(String name) {
ServiceBuilder result;
Optional<ServiceBuilder> orig = services.stream().filter(b -> b.getName().equals(name)).findFirst();
if (orig.isPresent()) {
result = orig.get();
} else {
result = new ServiceBuilder(this, name);
result.addContainerSelector("deploymentconfig", applicationName);
services.add(result);
}
return result;
}
public RouteBuilder route() {
return route(applicationName);
}
public RouteBuilder route(String name) {
RouteBuilder result;
Optional<RouteBuilder> orig = routes.stream().filter(r -> r.getName().startsWith(name)).findFirst();
if (orig.isPresent()) {
result = orig.get();
} else {
result = new RouteBuilder(this, name);
result.forService(applicationName);
routes.add(result);
}
return result;
}
public RoleBuilder role() {
return role(applicationName);
}
public RoleBuilder role(String name) {
RoleBuilder result;
Optional<RoleBuilder> orig = roles.stream().filter(r -> r.getName().startsWith(name)).findFirst();
if (orig.isPresent()) {
result = orig.get();
} else {
result = new RoleBuilder(this, name);
roles.add(result);
}
return result;
}
public RoleBindingBuilder roleBinding() {
return roleBinding(applicationName);
}
public RoleBindingBuilder roleBinding(String name) {
RoleBindingBuilder result;
Optional<RoleBindingBuilder> orig = roleBindings.stream().filter(r -> r.getName().startsWith(name)).findFirst();
if (orig.isPresent()) {
result = orig.get();
} else {
result = new RoleBindingBuilder(this, name);
roleBindings.add(result);
}
return result;
}
public ConfigMapWithPropertyFilesBuilder configMap() {
return configMap(applicationName);
}
public ConfigMapWithPropertyFilesBuilder configMap(String name) {
ConfigMapWithPropertyFilesBuilder result;
Optional<ConfigMapWithPropertyFilesBuilder> orig = configMaps.stream().filter(r -> r.getName().equals(name)).findFirst();
if (orig.isPresent()) {
result = orig.get();
} else {
result = new ConfigMapWithPropertyFilesBuilder(name);
configMaps.add(result);
}
return result;
}
public SecretBuilder secret() {
return secret(applicationName);
}
public SecretBuilder secret(String name) {
SecretBuilder result;
Optional<SecretBuilder> orig = secrets.stream().filter(r -> r.getName().equals(name)).findFirst();
if (orig.isPresent()) {
result = orig.get();
} else {
result = new SecretBuilder(name);
secrets.add(result);
}
return result;
}
public PVCBuilder pvc() {
return pvc(applicationName);
}
public PVCBuilder pvc(String name) {
PVCBuilder result;
Optional<PVCBuilder> orig = persistentVolumeClaims.stream().filter(r -> r.getName().equals(name)).findFirst();
if (orig.isPresent()) {
result = orig.get();
} else {
result = new PVCBuilder(name);
persistentVolumeClaims.add(result);
}
return result;
}
public List<ImageStream> buildImageStreams() {
return images.stream().map(ImageStreamBuilder::build).collect(Collectors.toList());
}
public List<BuildConfig> buildBuildConfigs() {
return builds.stream().map(BuildConfigBuilder::build).collect(Collectors.toList());
}
public List<DeploymentConfig> buildDeploymentConfigs() {
return deployments.stream().map(DeploymentConfigBuilder::build).collect(Collectors.toList());
}
public List<Service> buildServices() {
return services.stream().map(ServiceBuilder::build).collect(Collectors.toList());
}
public List<Route> buildRoutes() {
return routes.stream().map(RouteBuilder::build).collect(Collectors.toList());
}
public List<Role> buildRoles() {
return roles.stream().map(RoleBuilder::build).collect(Collectors.toList());
}
public List<RoleBinding> buildRoleBindings() {
return roleBindings.stream().map(RoleBindingBuilder::build).collect(Collectors.toList());
}
public List<ConfigMap> buildConfigMaps() {
return configMaps.stream().map(ConfigMapWithPropertyFilesBuilder::build).collect(Collectors.toList());
}
public List<Secret> buildSecrets() {
return secrets.stream().map(SecretBuilder::build).collect(Collectors.toList());
}
public List<PersistentVolumeClaim> buildPVCs() {
return persistentVolumeClaims.stream().map(PVCBuilder::build).collect(Collectors.toList());
}
public List<HasMetadata> build() {
List<HasMetadata> result = new LinkedList<>();
result.addAll(buildImageStreams());
result.addAll(buildBuildConfigs());
result.addAll(buildDeploymentConfigs());
result.addAll(buildServices());
result.addAll(buildRoutes());
result.addAll(buildConfigMaps());
result.addAll(buildSecrets());
result.addAll(buildPVCs());
return result;
}
public OpenShiftApplication buildApplication() {
return new OpenShiftApplication(this);
}
public ApplicationBuilder addDatabase(OpenShiftAuxiliary database) {
database.configureDeployment(this);
database.configureApplicationDeployment(deploymentConfig());
return this;
}
}
|
package net.buycraft.plugin.bukkit;
import lombok.RequiredArgsConstructor;
import net.buycraft.plugin.data.QueuedPlayer;
import net.buycraft.plugin.execution.PlayerCommandExecutor;
import org.apache.commons.lang.StringUtils;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerJoinEvent;
@RequiredArgsConstructor
public class BuycraftListener implements Listener {
private final BuycraftPlugin plugin;
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
if (plugin.getApiClient() == null) {
return;
}
QueuedPlayer qp = plugin.getDuePlayerFetcher().fetchAndRemoveDuePlayer(event.getPlayer().getName());
if (qp != null) {
plugin.getLogger().info(String.format("Executing login commands for %s...", event.getPlayer().getName()));
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new PlayerCommandExecutor(qp, plugin.getPlatform()));
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
if (!plugin.getConfiguration().isDisableBuyCommand()) {
for (String s : plugin.getConfiguration().getBuyCommandName()) {
if (event.getMessage().substring(1).equalsIgnoreCase(s) ||
event.getMessage().regionMatches(true, 1, s + " ", 0, s.length() + 1)) {
plugin.getViewCategoriesGUI().open(event.getPlayer());
event.setCancelled(true);
}
}
}
}
}
|
package com.imcode.imcms.api;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
/**
* I18n-ed part of meta.
*/
@Entity
@Table(name="i18n_meta")
@NamedQueries({
@NamedQuery(name="I18nMeta.getByLanguage", query="select m from I18nMeta m where m.metaId = :metaId and m.language.id = :languageId")
//@NamedQuery(name="I18nMeta.getByMetaId&LanguageId", query="select m from I18nMeta m where m.metaId = :metaId and m.language.id=:languageId")
})
public class I18nMeta implements Serializable {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="i18n_meta_id")
private Long id;
@Column(name="meta_id")
private Integer metaId;
@Column(name="meta_enabled")
private Boolean enabled;
@OneToOne(fetch=FetchType.EAGER)
@JoinColumn(name="language_id", referencedColumnName="language_id")
private I18nLanguage language;
@OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
@JoinColumn(name="i18n_meta_id", referencedColumnName="i18n_meta_id")
private Set<I18nKeyword> keywords;
@Column(name="meta_headline")
private String headline;
@Column(name="meta_text")
private String menuText;
@Column(name="meta_image")
private String menuImageURL;
public String getHeadline() {
return headline;
}
public void setHeadline(String headline) {
this.headline = headline;
}
public String getMenuText() {
return menuText;
}
public void setMenuText(String text) {
this.menuText = text;
}
public String getMenuImageURL() {
return menuImageURL;
}
public void setMenuImageURL(String image) {
this.menuImageURL = image;
}
public I18nLanguage getLanguage() {
return language;
}
public void setLanguage(I18nLanguage language) {
this.language = language;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getMetaId() {
return metaId;
}
public void setMetaId(Integer metaId) {
this.metaId = metaId;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Set<I18nKeyword> getKeywords() {
return keywords;
}
public void setKeywords(Set<I18nKeyword> keywords) {
this.keywords = keywords;
}
public Set<String> getKeywordsValues() {
Set<String> values = new HashSet<String>();
for (I18nKeyword keyword: keywords) {
values.add(keyword.getValue());
}
return values;
}
public void setKeywordsValues(Set<String> values) {
keywords.clear();
Long id = getId();
for (String value: values) {
I18nKeyword keyword = new I18nKeyword();
keyword.setValue(value);
keyword.setI18nMetaId(id);
keywords.add(keyword);
}
}
}
|
package com.kii.thingif;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.Pair;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.WorkerThread;
import com.google.gson.JsonParseException;
import com.kii.thingif.command.Action;
import com.kii.thingif.command.Command;
import com.kii.thingif.command.CommandForm;
import com.kii.thingif.exception.ThingIFException;
import com.kii.thingif.exception.ThingIFRestException;
import com.kii.thingif.exception.StoredThingIFAPIInstanceNotFoundException;
import com.kii.thingif.exception.UnsupportedActionException;
import com.kii.thingif.exception.UnsupportedSchemaException;
import com.kii.thingif.gateway.EndNode;
import com.kii.thingif.gateway.Gateway;
import com.kii.thingif.gateway.PendingEndNode;
import com.kii.thingif.internal.GsonRepository;
import com.kii.thingif.internal.http.IoTRestClient;
import com.kii.thingif.internal.http.IoTRestRequest;
import com.kii.thingif.schema.Schema;
import com.kii.thingif.trigger.ServerCode;
import com.kii.thingif.trigger.Predicate;
import com.kii.thingif.trigger.Trigger;
import com.kii.thingif.internal.utils.JsonUtils;
import com.kii.thingif.internal.utils.Path;
import com.kii.thingif.trigger.TriggeredServerCodeResult;
import com.kii.thingif.trigger.TriggersWhat;
import com.squareup.okhttp.MediaType;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class operates an IoT device that is specified by {@link #onboard(String, String, String, JSONObject)} method.
*/
public class ThingIFAPI implements Parcelable {
private static final String SHARED_PREFERENCES_KEY_INSTANCE = "ThingIFAPI_INSTANCE";
private static final String SDK_VERSION = "0.12.0";
private static Context context;
private final String tag;
private final KiiApp app;
private final Owner owner;
private Target target;
private final Map<Pair<String, Integer>, Schema> schemas = new HashMap<Pair<String, Integer>, Schema>();
private final IoTRestClient restClient;
private String installationID;
/**
* Try to load the instance of ThingIFAPI using stored serialized instance.
* <BR>
* Instance is automatically saved when following methods are called.
* <BR>
* {@link #onboard(String, String, String, JSONObject)}, {@link #onboard(String, String)},
* {@link #copyWithTarget(Target, String)}
* and {@link #installPush} has been successfully completed.
* <BR>
* (When {@link #copyWithTarget(Target, String)} is called, only the copied instance is saved.)
* <BR>
* <BR>
*
* If the ThingIFAPI instance is build without the tag, all instance is saved in same place
* and overwritten when the instance is saved.
* <BR>
* <BR>
*
* If the ThingIFAPI instance is build with the tag(optional), tag is used as key to distinguish
* the storage area to save the instance. This would be useful to saving multiple instance.
* You need specify tag to load the instance by the
* {@link #loadFromStoredInstance(Context, String) api}.
*
* @param context context
* @return ThingIFAPI instance.
* @throws StoredThingIFAPIInstanceNotFoundException when the instance has not stored yet.
*/
@NonNull
public static ThingIFAPI loadFromStoredInstance(@NonNull Context context) throws StoredThingIFAPIInstanceNotFoundException {
return loadFromStoredInstance(context, null);
}
/**
* Try to load the instance of ThingIFAPI using stored serialized instance.
* <BR>
* For details please refer to the {@link #loadFromStoredInstance(Context)} document.
*
* @param context context
* @param tag specified when the ThingIFAPI has been built.
* @return ThingIFAPI instance.
* @throws StoredThingIFAPIInstanceNotFoundException when the instance has not stored yet.
*/
@NonNull
public static ThingIFAPI loadFromStoredInstance(@NonNull Context context, String tag) throws StoredThingIFAPIInstanceNotFoundException {
ThingIFAPI.context = context.getApplicationContext();
SharedPreferences preferences = getSharedPreferences();
String serializedJson = preferences.getString(getSharedPreferencesKey(tag), null);
if (serializedJson != null) {
return GsonRepository.gson().fromJson(serializedJson, ThingIFAPI.class);
}
throw new StoredThingIFAPIInstanceNotFoundException(tag);
}
/**
* Clear all saved instances in the SharedPreferences.
*/
public static void removeAllStoredInstances() {
SharedPreferences preferences = getSharedPreferences();
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.apply();
}
/**
* Remove saved specified instance in the SharedPreferences.
*
* @param tag
*/
public static void removeStoredInstance(@Nullable String tag) {
SharedPreferences preferences = getSharedPreferences();
SharedPreferences.Editor editor = preferences.edit();
editor.remove(getSharedPreferencesKey(tag));
editor.apply();
}
private static void saveInstance(ThingIFAPI instance) {
SharedPreferences preferences = getSharedPreferences();
if (preferences != null) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString(getSharedPreferencesKey(instance.tag), GsonRepository.gson().toJson(instance));
editor.apply();
}
}
private static String getSharedPreferencesKey(String tag) {
return SHARED_PREFERENCES_KEY_INSTANCE + (tag == null ? "" : "_" +tag);
}
ThingIFAPI(
@Nullable Context context,
@Nullable String tag,
@NonNull KiiApp app,
@NonNull Owner owner,
@Nullable Target target,
@NonNull List<Schema> schemas,
String installationID) {
// Parameters are checked by ThingIFAPIBuilder
if (context != null) {
ThingIFAPI.context = context.getApplicationContext();
}
this.tag = tag;
this.app = app;
this.owner = owner;
this.target = target;
for (Schema schema : schemas) {
this.schemas.put(new Pair<String, Integer>(schema.getSchemaName(), schema.getSchemaVersion()), schema);
}
this.installationID = installationID;
this.restClient = new IoTRestClient();
}
/**
* Create the clone instance that has specified target and tag.
*
* @param target
* @param tag
* @return ThingIFAPI instance
*/
public ThingIFAPI copyWithTarget(@NonNull Target target, @Nullable String tag) {
if (target == null) {
throw new IllegalArgumentException("target is null");
}
ThingIFAPI api = new ThingIFAPI(context, tag, this.app, this.owner, target, new ArrayList<Schema>(this.schemas.values()), this.installationID);
saveInstance(api);
return api;
}
@NonNull
@WorkerThread
public Target onboard(
@NonNull String vendorThingID,
@NonNull String thingPassword,
@Nullable String thingType,
@Nullable JSONObject thingProperties)
throws ThingIFException {
OnboardWithVendorThingIDOptions.Builder builder = new OnboardWithVendorThingIDOptions.Builder();
builder.setThingType(thingType).setThingProperties(thingProperties);
return onboardWithVendorThingID(vendorThingID, thingPassword, builder.build());
}
@NonNull
@WorkerThread
public Target onboard(
@NonNull String vendorThingID,
@NonNull String thingPassword,
@Nullable OnboardWithVendorThingIDOptions options)
throws ThingIFException {
return onboardWithVendorThingID(vendorThingID, thingPassword, options);
}
private Target onboardWithVendorThingID(
String vendorThingID,
String thingPassword,
OnboardWithVendorThingIDOptions options)
throws ThingIFException {
if (this.onboarded()) {
throw new IllegalStateException("This instance is already onboarded.");
}
if (TextUtils.isEmpty(vendorThingID)) {
throw new IllegalArgumentException("vendorThingID is null or empty");
}
if (TextUtils.isEmpty(thingPassword)) {
throw new IllegalArgumentException("thingPassword is null or empty");
}
JSONObject requestBody = new JSONObject();
LayoutPosition layoutPosition = null;
try {
requestBody.put("vendorThingID", vendorThingID);
requestBody.put("thingPassword", thingPassword);
if (options != null) {
String thingType = options.getThingType();
String firmwareVersion = options.getFirmwareVersion();
JSONObject thingProperties = options.getThingProperties();
layoutPosition = options.getLayoutPosition();
DataGroupingInterval dataGroupingInterval = options.getDataGroupingInterval();
if (thingType != null) {
requestBody.put("thingType", thingType);
}
if (firmwareVersion != null) {
requestBody.put("firmwareVersion", firmwareVersion);
}
if (thingProperties != null && thingProperties.length() > 0) {
requestBody.put("thingProperties", thingProperties);
}
if (layoutPosition != null) {
requestBody.put("layoutPosition", layoutPosition.name());
}
if (dataGroupingInterval != null) {
requestBody.put("dataGroupingInterval", dataGroupingInterval.getInterval());
}
}
requestBody.put("owner", this.owner.getTypedID().toString());
} catch (JSONException e) {
}
return this.onboard(MediaTypes.MEDIA_TYPE_ONBOARDING_WITH_VENDOR_THING_ID_BY_OWNER_REQUEST, requestBody, vendorThingID, layoutPosition);
}
@NonNull
@WorkerThread
public Target onboard(
@NonNull String thingID,
@NonNull String thingPassword) throws
ThingIFException {
return onboardWithThingID(thingID, thingPassword, null);
}
@NonNull
@WorkerThread
public Target onboard(
@NonNull String thingID,
@NonNull String thingPassword,
@Nullable OnboardWithThingIDOptions options)
throws ThingIFException {
return onboardWithThingID(thingID, thingPassword, options);
}
private Target onboardWithThingID(
String thingID,
String thingPassword,
OnboardWithThingIDOptions options)
throws ThingIFException {
if (this.onboarded()) {
throw new IllegalStateException("This instance is already onboarded.");
}
if (TextUtils.isEmpty(thingID)) {
throw new IllegalArgumentException("thingID is null or empty");
}
if (TextUtils.isEmpty(thingPassword)) {
throw new IllegalArgumentException("thingPassword is null or empty");
}
JSONObject requestBody = new JSONObject();
LayoutPosition layoutPosition = null;
try {
requestBody.put("thingID", thingID);
requestBody.put("thingPassword", thingPassword);
requestBody.put("owner", this.owner.getTypedID().toString());
if (options != null) {
layoutPosition = options.getLayoutPosition();
DataGroupingInterval dataGroupingInterval = options.getDataGroupingInterval();
if (layoutPosition != null) {
requestBody.put("layoutPosition", layoutPosition.name());
}
if (dataGroupingInterval != null) {
requestBody.put("dataGroupingInterval", dataGroupingInterval.getInterval());
}
}
} catch (JSONException e) {
}
// FIXME: Currently, Server does not return the VendorThingID when onboarding is successful.
return this.onboard(MediaTypes.MEDIA_TYPE_ONBOARDING_WITH_THING_ID_BY_OWNER_REQUEST, requestBody, null, layoutPosition);
}
private Target onboard(MediaType contentType, JSONObject requestBody, String vendorThingID, LayoutPosition layoutPosition) throws ThingIFException {
String path = MessageFormat.format("/thing-if/apps/{0}/onboardings", this.app.getAppID());
String url = Path.combine(this.app.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers, contentType, requestBody);
JSONObject responseBody = this.restClient.sendRequest(request);
String thingID = responseBody.optString("thingID", null);
String accessToken = responseBody.optString("accessToken", null);
if (layoutPosition == LayoutPosition.GATEWAY) {
this.target = new Gateway(thingID, vendorThingID);
} else if (layoutPosition == LayoutPosition.ENDNODE) {
this.target = new EndNode(thingID, vendorThingID, accessToken);
} else {
this.target = new StandaloneThing(thingID, vendorThingID,
accessToken);
}
saveInstance(this);
return this.target;
}
public EndNode onboardEndnodeWithGateway(
@NonNull PendingEndNode pendingEndNode,
@NonNull String endnodePassword)
throws ThingIFException {
return onboardEndNodeWithGateway(pendingEndNode, endnodePassword, null);
}
public EndNode onboardEndnodeWithGateway(
@NonNull PendingEndNode pendingEndNode,
@NonNull String endnodePassword,
@Nullable OnboardEndnodeWithGatewayOptions options)
throws ThingIFException {
return onboardEndNodeWithGateway(pendingEndNode, endnodePassword, options);
}
private EndNode onboardEndNodeWithGateway(
PendingEndNode pendingEndNode,
String endnodePassword,
@Nullable OnboardEndnodeWithGatewayOptions options)
throws ThingIFException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding the gateway");
}
if (this.target instanceof EndNode) {
throw new IllegalStateException("Target must be Gateway");
}
if (pendingEndNode == null) {
throw new IllegalArgumentException("pendingEndNode is null or empty");
}
if (TextUtils.isEmpty(pendingEndNode.getVendorThingID())) {
throw new IllegalArgumentException("vendorThingID is null or empty");
}
if (TextUtils.isEmpty(endnodePassword)) {
throw new IllegalArgumentException("endnodePassword is null or empty");
}
JSONObject requestBody = new JSONObject();
try {
requestBody.put("gatewayThingID", this.target.getTypedID().getID());
requestBody.put("endNodeVendorThingID", pendingEndNode.getVendorThingID());
requestBody.put("endNodePassword", endnodePassword);
if (!TextUtils.isEmpty(pendingEndNode.getThingType())) {
requestBody.put("endNodeThingType", pendingEndNode.getThingType());
}
if (pendingEndNode.getThingProperties() != null && pendingEndNode.getThingProperties().length() > 0) {
requestBody.put("endNodeThingProperties", pendingEndNode.getThingProperties());
}
if (options != null) {
DataGroupingInterval dataGroupingInterval = options.getDataGroupingInterval();
if (dataGroupingInterval != null) {
requestBody.put("dataGroupingInterval", dataGroupingInterval.getInterval());
}
}
requestBody.put("owner", this.owner.getTypedID().toString());
} catch (JSONException e) {
}
String path = MessageFormat.format("/thing-if/apps/{0}/onboardings", this.app.getAppID());
String url = Path.combine(this.app.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers, MediaTypes.MEDIA_TYPE_ONBOARDING_ENDNODE_WITH_GATEWAY_THING_ID_REQUEST, requestBody);
JSONObject responseBody = this.restClient.sendRequest(request);
String thingID = responseBody.optString("endNodeThingID", null);
String accessToken = responseBody.optString("accessToken", null);
return new EndNode(thingID, pendingEndNode.getVendorThingID(), accessToken);
}
/**
* Checks whether on boarding is done.
* @return true if done, otherwise false.
*/
public boolean onboarded()
{
return this.target != null;
}
/**
* Install push notification to receive notification from IoT Cloud. This will install on production environment.
* IoT Cloud will send notification when the Target replies to the Command.
* Application can receive the notification and check the result of Command
* fired by Application or registered Trigger.
* After installation is done Installation ID is managed in this class.
* @param deviceToken for GCM, specify token obtained by
* InstanceID.getToken().
* for JPUSH, specify id obtained by
* JPushInterface.getUdid().
* @param pushBackend Specify backend to use.
* @return Installation ID used in IoT Cloud.
* @throws ThingIFException Thrown when failed to connect IoT Cloud Server.
* @throws ThingIFRestException Thrown when server returns error response.
* @see #installPush(String, PushBackend, boolean) for development/production environment installation.
*/
@NonNull
@WorkerThread
public String installPush(
@Nullable String deviceToken,
@NonNull PushBackend pushBackend
) throws ThingIFException {
return this.installPush(deviceToken, pushBackend, false);
}
/**
* Install push notification to receive notification from IoT Cloud.
* IoT Cloud will send notification when the Target replies to the Command.
* Application can receive the notification and check the result of Command
* fired by Application or registered Trigger.
* After installation is done Installation ID is managed in this class.
* @param deviceToken for GCM, specify token obtained by
* InstanceID.getToken().
* for JPUSH, specify id obtained by
* JPushInterface.getUdid().
* @param pushBackend Specify backend to use.
* @param development Specify development flag to use. Indicates if the installation is for development or production environment.
* @return Installation ID used in IoT Cloud.
* @throws ThingIFException Thrown when failed to connect IoT Cloud Server.
* @throws ThingIFRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public String installPush(
@Nullable String deviceToken,
@NonNull PushBackend pushBackend,
boolean development
) throws ThingIFException{
if (pushBackend == null) {
throw new IllegalArgumentException("pushBackend is null");
}
String path = MessageFormat.format("/api/apps/{0}/installations", this.app.getAppID());
String url = Path.combine(this.app.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
JSONObject requestBody = new JSONObject();
try {
if (!TextUtils.isEmpty(deviceToken)) {
requestBody.put("installationRegistrationID", deviceToken);
}
if (development){
requestBody.put("development", true);
}
requestBody.put("deviceType", pushBackend.getDeviceType());
} catch (JSONException e) {
}
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers, MediaTypes.MEDIA_TYPE_INSTALLATION_CREATION_REQUEST, requestBody);
JSONObject responseBody = this.restClient.sendRequest(request);
this.installationID = responseBody.optString("installationID", null);
saveInstance(this);
return this.installationID;
}
/**
* Get installationID if the push is already installed.
* null will be returned if the push installation has not been done.
* @return Installation ID used in IoT Cloud.
*/
@Nullable
public String getInstallationID() {
return this.installationID;
}
void setInstallationID(String installationID) {
this.installationID = installationID;
}
/**
* Uninstall push notification.
* After done, notification from IoT Cloud won't be notified.
* @param installationID installation ID returned from
* {@link #installPush(String, PushBackend)}
* if null is specified, value obtained by
* {@link #getInstallationID()} is used.
* @throws ThingIFException Thrown when failed to connect IoT Cloud Server.
* @throws ThingIFRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public void uninstallPush(@NonNull String installationID) throws ThingIFException {
if (installationID == null) {
throw new IllegalArgumentException("installationID is null");
}
String path = MessageFormat.format("/api/apps/{0}/installations/{1}", this.app.getAppID(), installationID);
String url = Path.combine(this.app.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.DELETE, headers);
this.restClient.sendRequest(request);
}
/**
* Post new command to IoT Cloud.
* Command will be delivered to specified target and result will be notified
* through push notification.
* @param schemaName name of the schema.
* @param schemaVersion version of schema.
* @param actions Actions to be executed.
* @return Created Command instance. At this time, Command is delivered to
* the target Asynchronously and may not finished. Actual Result will be
* delivered through push notification or you can check the latest status
* of the command by calling {@link #getCommand}.
* @throws ThingIFException Thrown when failed to connect IoT Cloud Server.
* @throws ThingIFRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public Command postNewCommand(
@NonNull String schemaName,
int schemaVersion,
@NonNull List<Action> actions) throws ThingIFException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
Schema schema = this.getSchema(schemaName, schemaVersion);
if (schema == null) {
throw new UnsupportedSchemaException(schemaName, schemaVersion);
}
if (actions == null || actions.size() == 0) {
throw new IllegalArgumentException("actions is null or empty");
}
String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/commands", this.app.getAppID(), this.target.getTypedID().toString());
String url = Path.combine(this.app.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
Command command = new Command(schemaName, schemaVersion, this.owner.getTypedID(), actions);
JSONObject requestBody = JsonUtils.newJson(GsonRepository.gson(schema).toJson(command));
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers, MediaTypes.MEDIA_TYPE_JSON, requestBody);
JSONObject responseBody = this.restClient.sendRequest(request);
String commandID = responseBody.optString("commandID", null);
return this.getCommand(commandID);
}
/**
* Post new command to IoT Cloud.
* Command will be delivered to specified target and result will be notified
* through push notification.
* @param form form of command. It contains name of schema, version of
* schema, list of actions etc.
* @return Created Command instance. At this time, Command is delivered to
* the target Asynchronously and may not finished. Actual Result will be
* delivered through push notification or you can check the latest status
* of the command by calling {@link #getCommand}.
* @throws ThingIFException Thrown when failed to connect IoT Cloud Server.
* @throws ThingIFRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public Command postNewCommand(
@NonNull CommandForm form) throws ThingIFException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
final String schemaName = form.getSchemaName();
final int schemaVersion = form.getSchemaVersion();
Schema schema = this.getSchema(schemaName, schemaVersion);
if (schema == null) {
throw new UnsupportedSchemaException(schemaName, schemaVersion);
}
String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/commands",
this.app.getAppID(), this.target.getTypedID().toString());
String url = Path.combine(this.app.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
Command command = new Command(schemaName, schemaVersion, this.owner.getTypedID(),
form.getActions());
command.setTitle(form.getTitle());
command.setDescription(form.getDescription());
command.setMetadata(form.getMetadata());
JSONObject requestBody = JsonUtils.newJson(GsonRepository.gson(schema).toJson(command));
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers,
MediaTypes.MEDIA_TYPE_JSON, requestBody);
JSONObject responseBody = this.restClient.sendRequest(request);
String commandID = responseBody.optString("commandID", null);
return this.getCommand(commandID);
}
/**
* Get specified command.
* @param commandID ID of the command to obtain. ID is present in the
* instance returned by {@link #postNewCommand}
* and can be obtained by {@link Command#getCommandID}
*
* @return Command instance.
* @throws ThingIFException Thrown when failed to connect IoT Cloud Server.
* @throws ThingIFRestException Thrown when server returns error response.
* @throws UnsupportedSchemaException Thrown when the returned response has a schema that cannot handle this instance.
* @throws UnsupportedActionException Thrown when the returned response has a action that cannot handle this instance.
*/
@NonNull
@WorkerThread
public Command getCommand(
@NonNull String commandID)
throws ThingIFException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (TextUtils.isEmpty(commandID)) {
throw new IllegalArgumentException("commandID is null or empty");
}
String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/commands/{2}", this.app.getAppID(), this.target.getTypedID().toString(), commandID);
String url = Path.combine(this.app.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers);
JSONObject responseBody = this.restClient.sendRequest(request);
String schemaName = responseBody.optString("schema", null);
int schemaVersion = responseBody.optInt("schemaVersion");
Schema schema = this.getSchema(schemaName, schemaVersion);
if (schema == null) {
throw new UnsupportedSchemaException(schemaName, schemaVersion);
}
return this.deserialize(schema, responseBody, Command.class);
}
/**
* List Commands in the specified Target.<br>
* If the Schema of the Command included in the response does not matches with the Schema
* registered this ThingIfAPI instance, It won't be included in returned value.
* @param bestEffortLimit Maximum number of the Commands in the response.
* if the value is <= 0, default limit internally
* defined is applied.
* Meaning of 'bestEffort' is if the specified limit
* is greater than default limit, default limit is
* applied.
* @param paginationKey Used to get the next page of previously obtained.
* If there is further page to obtain, this method
* returns paginationKey as the 2nd element of pair.
* Applying this key to the argument results continue
* to get the result from the next page.
* @return 1st Element is Commands belongs to the Target. 2nd element is
* paginationKey if there is next page to be obtained.
* @throws ThingIFException Thrown when failed to connect IoT Cloud Server.
* @throws ThingIFRestException Thrown when server returns error response.
* @throws UnsupportedActionException Thrown when the returned response has a action that cannot handle this instance.
*/
@NonNull
public Pair<List<Command>, String> listCommands (
int bestEffortLimit,
@Nullable String paginationKey)
throws ThingIFException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/commands", this.app.getAppID(), this.target.getTypedID().toString());
String url = Path.combine(this.app.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers);
if (bestEffortLimit > 0) {
request.addQueryParameter("bestEffortLimit", bestEffortLimit);
}
if (!TextUtils.isEmpty(paginationKey)) {
request.addQueryParameter("paginationKey", paginationKey);
}
JSONObject responseBody = this.restClient.sendRequest(request);
String nextPaginationKey = responseBody.optString("nextPaginationKey", null);
JSONArray commandArray = responseBody.optJSONArray("commands");
List<Command> commands = new ArrayList<Command>();
if (commandArray != null) {
for (int i = 0; i < commandArray.length(); i++) {
JSONObject commandJson = commandArray.optJSONObject(i);
String schemaName = commandJson.optString("schema", null);
int schemaVersion = commandJson.optInt("schemaVersion");
Schema schema = this.getSchema(schemaName, schemaVersion);
if (schema == null) {
continue;
}
commands.add(this.deserialize(schema, commandJson, Command.class));
}
}
return new Pair<List<Command>, String>(commands, nextPaginationKey);
}
/**
* Post new Trigger with commands to IoT Cloud.
*
* <p>
* When thing related to this ThingIFAPI instance meets condition
* described by predicate, A registered command sends to thing related to
* target.
* </p>
*
* {@link getTarget()} instance and target argument must be same owner's
* things.
*
* @param schemaName name of the schema.
* @param schemaVersion version of schema.
* @param actions Specify actions included in the Command is fired by the
* trigger.
* @param predicate Specify when the Trigger fires command.
* @param target target of trigger.
* @return Instance of the Trigger registered in IoT Cloud.
* @throws ThingIFException Thrown when failed to connect IoT Cloud Server.
* @throws ThingIFRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public Trigger postNewTrigger(
@NonNull String schemaName,
int schemaVersion,
@NonNull List<Action> actions,
@NonNull Predicate predicate,
@NonNull Target target) throws ThingIFException {
return postNewTriggerWithCommands(schemaName, schemaVersion, actions, predicate, target);
}
/**
* Post new Trigger with commands to IoT Cloud.
*
* <p>
* Short version of {@link #postNewTrigger(String, int, List, Predicate,
* Target)}.
* </p>
*
* <p>
* This method equals to followings:
* </p>
* <code>
* api.postNewTrigger(schemaName, schemaVersion, actions, predicate, api.getTarget()).
* </code>
*
* @param schemaName name of the schema.
* @param schemaVersion version of schema.
* @param actions Specify actions included in the Command is fired by the
* trigger.
* @param predicate Specify when the Trigger fires command.
* @return Instance of the Trigger registered in IoT Cloud.
* @throws ThingIFException Thrown when failed to connect IoT Cloud Server.
* @throws ThingIFRestException Thrown when server returns error response.
* @see #postNewTrigger(String, int, List, Predicate, Target)
*/
@NonNull
@WorkerThread
public Trigger postNewTrigger(
@NonNull String schemaName,
int schemaVersion,
@NonNull List<Action> actions,
@NonNull Predicate predicate)
throws ThingIFException {
return postNewTriggerWithCommands(schemaName, schemaVersion, actions, predicate, this.target);
}
private Trigger postNewTriggerWithCommands(
String schemaName,
int schemaVersion,
List<Action> actions,
Predicate predicate,
Target commandTarget) throws ThingIFException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (TextUtils.isEmpty(schemaName)) {
throw new IllegalArgumentException("schemaName is null or empty");
}
if (actions == null || actions.size() == 0) {
throw new IllegalArgumentException("actions is null or empty");
}
if (predicate == null) {
throw new IllegalArgumentException("predicate is null");
}
if (commandTarget == null) {
throw new IllegalArgumentException("Command target is null");
}
JSONObject requestBody = new JSONObject();
Schema schema = this.getSchema(schemaName, schemaVersion);
Command command = new Command(schemaName, schemaVersion, commandTarget.getTypedID(), this.owner.getTypedID(), actions);
try {
requestBody.put("predicate", JsonUtils.newJson(GsonRepository.gson(schema).toJson(predicate)));
requestBody.put("triggersWhat", TriggersWhat.COMMAND.name());
requestBody.put("command", JsonUtils.newJson(GsonRepository.gson(schema).toJson(command)));
} catch (JSONException e) {
}
return this.postNewTrigger(requestBody);
}
/**
* Post new Trigger with server code to IoT Cloud.
*
* @param serverCode Specify server code you want to execute.
* @param predicate Specify when the Trigger fires command.
* @return Instance of the Trigger registered in IoT Cloud.
* @throws ThingIFException Thrown when failed to connect IoT Cloud Server.
* @throws ThingIFRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public Trigger postNewTrigger(
@NonNull ServerCode serverCode,
@NonNull Predicate predicate)
throws ThingIFException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (serverCode == null) {
throw new IllegalArgumentException("serverCode is null");
}
if (predicate == null) {
throw new IllegalArgumentException("predicate is null");
}
JSONObject requestBody = new JSONObject();
try {
requestBody.put("predicate", JsonUtils.newJson(GsonRepository.gson().toJson(predicate)));
requestBody.put("triggersWhat", TriggersWhat.SERVER_CODE.name());
requestBody.put("serverCode", JsonUtils.newJson(GsonRepository.gson().toJson(serverCode)));
} catch (JSONException e) {
}
return this.postNewTrigger(requestBody);
}
private Trigger postNewTrigger(@NonNull JSONObject requestBody) throws ThingIFException {
String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/triggers", this.app.getAppID(), this.target.getTypedID().toString());
String url = Path.combine(this.app.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers, MediaTypes.MEDIA_TYPE_JSON, requestBody);
JSONObject responseBody = this.restClient.sendRequest(request);
String triggerID = responseBody.optString("triggerID", null);
return this.getTrigger(triggerID);
}
/**
* Get specified Trigger.
* @param triggerID ID of the Trigger to get.
* @return Trigger instance.
* @throws ThingIFException Thrown when failed to connect IoT Cloud Server.
* @throws ThingIFRestException Thrown when server returns error response.
* @throws UnsupportedSchemaException Thrown when the returned response has a schema that cannot handle this instance.
* @throws UnsupportedActionException Thrown when the returned response has a action that cannot handle this instance.
*/
@NonNull
@WorkerThread
public Trigger getTrigger(
@NonNull String triggerID)
throws ThingIFException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (TextUtils.isEmpty(triggerID)) {
throw new IllegalArgumentException("triggerID is null or empty");
}
String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/triggers/{2}", this.app.getAppID(), this.target.getTypedID().toString(), triggerID);
String url = Path.combine(this.app.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers);
JSONObject responseBody = this.restClient.sendRequest(request);
Schema schema = null;
JSONObject commandObject = responseBody.optJSONObject("command");
if (commandObject != null) {
String schemaName = commandObject.optString("schema", null);
int schemaVersion = commandObject.optInt("schemaVersion");
schema = this.getSchema(schemaName, schemaVersion);
if (schema == null) {
throw new UnsupportedSchemaException(schemaName, schemaVersion);
}
}
return this.deserialize(schema, responseBody, this.target.getTypedID());
}
@NonNull
@WorkerThread
public Trigger patchTrigger(
@NonNull String triggerID,
@NonNull String schemaName,
int schemaVersion,
@Nullable List<Action> actions,
@Nullable Predicate predicate) throws
ThingIFException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (TextUtils.isEmpty(triggerID)) {
throw new IllegalArgumentException("triggerID is null or empty");
}
if (TextUtils.isEmpty(schemaName)) {
throw new IllegalArgumentException("schemaName is null or empty");
}
if (actions == null || actions.size() == 0) {
throw new IllegalArgumentException("actions is null or empty");
}
if (predicate == null) {
throw new IllegalArgumentException("predicate is null");
}
JSONObject requestBody = new JSONObject();
Schema schema = this.getSchema(schemaName, schemaVersion);
Command command = new Command(schemaName, schemaVersion, this.target.getTypedID(), this.owner.getTypedID(), actions);
try {
requestBody.put("predicate", JsonUtils.newJson(GsonRepository.gson(schema).toJson(predicate)));
requestBody.put("command", JsonUtils.newJson(GsonRepository.gson(schema).toJson(command)));
requestBody.put("triggersWhat", TriggersWhat.COMMAND.name());
} catch (JSONException e) {
}
return this.patchTrigger(triggerID, requestBody);
}
@NonNull
@WorkerThread
public Trigger patchTrigger(
@NonNull String triggerID,
@NonNull ServerCode serverCode,
@Nullable Predicate predicate) throws ThingIFException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (TextUtils.isEmpty(triggerID)) {
throw new IllegalArgumentException("triggerID is null or empty");
}
if (serverCode == null) {
throw new IllegalArgumentException("serverCode is null");
}
if (predicate == null) {
throw new IllegalArgumentException("predicate is null");
}
JSONObject requestBody = new JSONObject();
try {
requestBody.put("predicate", JsonUtils.newJson(GsonRepository.gson().toJson(predicate)));
requestBody.put("serverCode", JsonUtils.newJson(GsonRepository.gson().toJson(serverCode)));
requestBody.put("triggersWhat", TriggersWhat.SERVER_CODE.name());
} catch (JSONException e) {
}
return this.patchTrigger(triggerID, requestBody);
}
private Trigger patchTrigger(@NonNull String triggerID, @NonNull JSONObject requestBody) throws ThingIFException {
String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/triggers/{2}", this.app.getAppID(), this.target.getTypedID().toString(), triggerID);
String url = Path.combine(this.app.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.PATCH, headers, MediaTypes.MEDIA_TYPE_JSON, requestBody);
this.restClient.sendRequest(request);
return this.getTrigger(triggerID);
}
/**
* Enable/Disable registered Trigger
* If its already enabled(/disabled),
* this method won't throw Exception and behave as succeeded.
* @param triggerID ID of the Trigger to be enabled(/disabled).
* @param enable specify whether enable of disable the Trigger.
* @return Updated Trigger Instance.
* @throws ThingIFException Thrown when failed to connect IoT Cloud Server.
* @throws ThingIFRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public Trigger enableTrigger(
@NonNull String triggerID,
boolean enable)
throws ThingIFException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (TextUtils.isEmpty(triggerID)) {
throw new IllegalArgumentException("triggerID is null or empty");
}
String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/triggers/{2}/{3}", this.app.getAppID(), this.target.getTypedID().toString(), triggerID, (enable ? "enable" : "disable"));
String url = Path.combine(this.app.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.PUT, headers);
this.restClient.sendRequest(request);
return this.getTrigger(triggerID);
}
/**
* Delete the specified Trigger.
* @param triggerID ID of the Trigger to be deleted.
* @return Deleted Trigger Id.
* @throws ThingIFException Thrown when failed to connect IoT Cloud Server.
* @throws ThingIFRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public String deleteTrigger(
@NonNull String triggerID) throws
ThingIFException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (TextUtils.isEmpty(triggerID)) {
throw new IllegalArgumentException("triggerID is null or empty");
}
String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/triggers/{2}", this.app.getAppID(), target.getTypedID().toString(), triggerID);
String url = Path.combine(this.app.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.DELETE, headers);
this.restClient.sendRequest(request);
return triggerID;
}
/**
* Retrieves list of server code results that was executed by the specified trigger. Results will be listing with order by modified date descending (latest first)
* @param bestEffortLimit limit the maximum number of the results in the
* Response. It ensures numbers in
* response is equals to or less than specified number.
* But doesn't ensures number of the results
* in the response is equal to specified value.<br>
* If the specified value <= 0, Default size of the limit
* is applied by IoT Cloud.
* @param paginationKey If specified obtain rest of the items.
* @return first is list of the results and second is paginationKey returned
* by IoT Cloud. paginationKey is null when there is next page to be obtained.
* Obtained paginationKey can be used to get the rest of the items stored
* in the target.
* @throws ThingIFException Thrown when failed to connect IoT Cloud Server.
* @throws ThingIFRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public Pair<List<TriggeredServerCodeResult>, String> listTriggeredServerCodeResults (
@NonNull String triggerID,
int bestEffortLimit,
@Nullable String paginationKey
) throws ThingIFException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (TextUtils.isEmpty(triggerID)) {
throw new IllegalArgumentException("triggerID is null or empty");
}
String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/triggers/{2}/results/server-code", this.app.getAppID(), this.target.getTypedID().toString(), triggerID);
String url = Path.combine(this.app.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers);
if (bestEffortLimit > 0) {
request.addQueryParameter("bestEffortLimit", bestEffortLimit);
}
if (!TextUtils.isEmpty(paginationKey)) {
request.addQueryParameter("paginationKey", paginationKey);
}
JSONObject responseBody = this.restClient.sendRequest(request);
String nextPaginationKey = responseBody.optString("nextPaginationKey", null);
JSONArray resultArray = responseBody.optJSONArray("triggerServerCodeResults");
List<TriggeredServerCodeResult> results = new ArrayList<TriggeredServerCodeResult>();
if (resultArray != null) {
for (int i = 0; i < resultArray.length(); i++) {
JSONObject resultJson = resultArray.optJSONObject(i);
results.add(this.deserialize(resultJson, TriggeredServerCodeResult.class));
}
}
return new Pair<List<TriggeredServerCodeResult>, String>(results, nextPaginationKey);
}
/**
* List Triggers belongs to the specified Target.<br>
* If the Schema of the Trigger included in the response does not matches with the Schema
* registered this ThingIfAPI instance, It won't be included in returned value.
* @param bestEffortLimit limit the maximum number of the Triggers in the
* Response. It ensures numbers in
* response is equals to or less than specified number.
* But doesn't ensures number of the Triggers
* in the response is equal to specified value.<br>
* If the specified value <= 0, Default size of the limit
* is applied by IoT Cloud.
* @param paginationKey If specified obtain rest of the items.
* @return first is list of the Triggers and second is paginationKey returned
* by IoT Cloud. paginationKey is null when there is next page to be obtained.
* Obtained paginationKey can be used to get the rest of the items stored
* in the target.
* @throws ThingIFException Thrown when failed to connect IoT Cloud Server.
* @throws ThingIFRestException Thrown when server returns error response.
* @throws UnsupportedActionException Thrown when the returned response has a action that cannot handle this instance.
*/
@NonNull
@WorkerThread
public Pair<List<Trigger>, String> listTriggers(
int bestEffortLimit,
@Nullable String paginationKey) throws
ThingIFException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/triggers", this.app.getAppID(), this.target.getTypedID().toString());
String url = Path.combine(this.app.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers);
if (bestEffortLimit > 0) {
request.addQueryParameter("bestEffortLimit", bestEffortLimit);
}
if (!TextUtils.isEmpty(paginationKey)) {
request.addQueryParameter("paginationKey", paginationKey);
}
JSONObject responseBody = this.restClient.sendRequest(request);
String nextPaginationKey = responseBody.optString("nextPaginationKey", null);
JSONArray triggerArray = responseBody.optJSONArray("triggers");
List<Trigger> triggers = new ArrayList<Trigger>();
if (triggerArray != null) {
for (int i = 0; i < triggerArray.length(); i++) {
JSONObject triggerJson = triggerArray.optJSONObject(i);
JSONObject commandJson = triggerJson.optJSONObject("command");
Schema schema = null;
if (commandJson != null) {
String schemaName = commandJson.optString("schema", null);
int schemaVersion = commandJson.optInt("schemaVersion");
schema = this.getSchema(schemaName, schemaVersion);
if (schema == null) {
continue;
}
}
triggers.add(this.deserialize(schema, triggerJson, this.target.getTypedID()));
}
}
return new Pair<List<Trigger>, String>(triggers, nextPaginationKey);
}
/**
* Get the State of specified Target.
* State will be serialized with Gson library.
* @param classOfS Specify class of the State.
* @param <S> State class.
* @return Instance of Target State.
* @throws ThingIFException Thrown when failed to connect IoT Cloud Server.
* @throws ThingIFRestException Thrown when server returns error response.
*/
@NonNull
@WorkerThread
public <S extends TargetState> S getTargetState(
@NonNull Class<S> classOfS) throws ThingIFException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (classOfS == null) {
throw new IllegalArgumentException("classOfS is null");
}
String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/states", this.app.getAppID(), this.target.getTypedID().toString());
String url = Path.combine(this.app.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers);
JSONObject responseBody = this.restClient.sendRequest(request);
S ret = GsonRepository.gson().fromJson(responseBody.toString(), classOfS);
return ret;
}
/**
* Get the Vendor Thing ID of specified Target.
*
* @return Vendor Thing ID
* @throws ThingIFException
*/
@NonNull
@WorkerThread
public String getVendorThingID() throws ThingIFException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
String path = MessageFormat.format("/api/apps/{0}/things/{1}/vendor-thing-id", this.app.getAppID(), this.target.getTypedID().getID());
String url = Path.combine(this.app.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers);
JSONObject responseBody = this.restClient.sendRequest(request);
return responseBody.optString("_vendorThingID", null);
}
/**
* Update the Vendor Thing ID of specified Target.
*
* @param newVendorThingID New vendor thing id
* @param newPassword New password
* @throws ThingIFException
*/
@WorkerThread
public void updateVendorThingID(@NonNull String newVendorThingID, @NonNull String newPassword) throws ThingIFException {
if (this.target == null) {
throw new IllegalStateException("Can not perform this action before onboarding");
}
if (TextUtils.isEmpty(newPassword)) {
throw new IllegalArgumentException("newPassword is null or empty");
}
if (TextUtils.isEmpty(newVendorThingID)) {
throw new IllegalArgumentException("newVendorThingID is null or empty");
}
JSONObject requestBody = new JSONObject();
try {
requestBody.put("_vendorThingID", newVendorThingID);
requestBody.put("_password", newPassword);
} catch (JSONException e) {
}
String path = MessageFormat.format("/api/apps/{0}/things/{1}/vendor-thing-id", this.app.getAppID(), this.target.getTypedID().getID());
String url = Path.combine(this.app.getBaseUrl(), path);
Map<String, String> headers = this.newHeader();
IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.PUT, headers, MediaTypes.MEDIA_TYPE_VENDOR_THING_ID_UPDATE_REQUEST, requestBody);
this.restClient.sendRequest(request);
}
/** Get Kii App
* @return Kii Cloud Application.
*/
@NonNull
public KiiApp getApp() {
return this.app;
}
/**
* Get AppID
* @return
*/
@NonNull
public String getAppID() {
return this.app.getAppID();
}
/**
* Get AppKey
* @return
*/
@NonNull
public String getAppKey() {
return this.app.getAppKey();
}
/**
* Get base URL
* @return
*/
@NonNull
public String getBaseUrl() {
return this.app.getBaseUrl();
}
/**
*
* @return
*/
@NonNull
public List<Schema> getSchemas() {
return new ArrayList<Schema>(this.schemas.values());
}
/**
* Get owner who uses the ThingIFAPI.
* @return
*/
@NonNull
public Owner getOwner() {
return this.owner;
}
/**
* Get target thing that is operated by the ThingIFAPI.
* @return
*/
@Nullable
public Target getTarget() {
return this.target;
}
void setTarget(Target target) {
this.target = target;
saveInstance(this);
}
/**
* Get a tag.
* @return
*/
@Nullable
public String getTag() {
return this.tag;
}
@Nullable
private Schema getSchema(String schemaName, int schemaVersion) {
return this.schemas.get(new Pair<String, Integer>(schemaName, schemaVersion));
}
private Map<String, String> newHeader() {
Map<String, String> headers = new HashMap<String, String>();
if (!TextUtils.isEmpty(this.getAppID())) {
headers.put("X-Kii-AppID", this.getAppID());
}
if (!TextUtils.isEmpty(this.getAppKey())) {
headers.put("X-Kii-AppKey", this.getAppKey());
}
if (this.owner != null && !TextUtils.isEmpty(this.owner.getAccessToken())) {
headers.put("Authorization", "Bearer " + this.owner.getAccessToken());
}
return headers;
}
private <T> T deserialize(JSONObject json, Class<T> clazz) throws ThingIFException {
return this.deserialize(null, json, clazz);
}
private <T> T deserialize(Schema schema, JSONObject json, Class<T> clazz) throws ThingIFException {
return this.deserialize(schema, json.toString(), clazz);
}
private Trigger deserialize(Schema schema, JSONObject json, TypedID targetID) throws ThingIFException {
try {
json.put("targetID", targetID.toString());
} catch (JSONException e) {
throw new ThingIFException("unexpected error.", e);
}
return this.deserialize(schema, json.toString(), Trigger.class);
}
private <T> T deserialize(Schema schema, String json, Class<T> clazz) throws ThingIFException {
try {
return GsonRepository.gson(schema).fromJson(json, clazz);
} catch (JsonParseException e) {
if (e.getCause() instanceof ThingIFException) {
throw (ThingIFException)e.getCause();
}
throw e;
}
}
private static SharedPreferences getSharedPreferences() {
if (context != null) {
return context.getSharedPreferences("com.kii.thingif.preferences", Context.MODE_PRIVATE);
}
return null;
}
// Implementation of Parcelable
protected ThingIFAPI(Parcel in) {
this.tag = in.readString();
this.app = in.readParcelable(KiiApp.class.getClassLoader());
this.owner = in.readParcelable(Owner.class.getClassLoader());
this.target = in.readParcelable(Target.class.getClassLoader());
ArrayList<Schema> schemas = in.createTypedArrayList(Schema.CREATOR);
for (Schema schema : schemas) {
this.schemas.put(new Pair<String, Integer>(schema.getSchemaName(), schema.getSchemaVersion()), schema);
}
this.restClient = new IoTRestClient();
this.installationID = in.readString();
}
public static final Creator<ThingIFAPI> CREATOR = new Creator<ThingIFAPI>() {
@Override
public ThingIFAPI createFromParcel(Parcel in) {
return new ThingIFAPI(in);
}
@Override
public ThingIFAPI[] newArray(int size) {
return new ThingIFAPI[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.tag);
dest.writeParcelable(this.app, flags);
dest.writeParcelable(this.owner, flags);
dest.writeParcelable(this.target, flags);
dest.writeTypedList(new ArrayList<Schema>(this.schemas.values()));
dest.writeString(this.installationID);
}
/**
* Get version of the SDK.
* @return Version string.
*/
@NonNull
public static String getSDKVersion() {
return SDK_VERSION;
}
}
|
package core;
import java.io.File;
public class Constants {
public static final String APP_NAME = "Juggernaut";
public static final String APP_VERSION = "0.1";
public static final String APP_FULL_NAME = APP_NAME+" ("+APP_VERSION+")";
public static final int APP_WIDTH = 800;
public static final int APP_HEIGHT = 600;
public static final int APP_STYLE = 1;
public static final String DATA_FOLDER = "data";
public static final String BUILD_FOLDER = DATA_FOLDER+File.separator+"build";
public static final String HISTORY_FOLDER = DATA_FOLDER+File.separator+"history";
public static final String TEMP_FOLDER = DATA_FOLDER+File.separator+"temp";
public static final int PROCESS_OK = 0;
public static final int PROCESS_NOK = 0;
}
|
// This file is part of OpenTSDB.
// This program is free software: you can redistribute it and/or modify it
// option) any later version. This program is distributed in the hope that it
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
package net.opentsdb.core;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hbase.async.Bytes;
import org.hbase.async.HBaseException;
import org.hbase.async.KeyValue;
import org.hbase.async.Scanner;
import static org.hbase.async.Bytes.ByteMap;
import net.opentsdb.stats.Histogram;
import net.opentsdb.uid.NoSuchUniqueId;
import net.opentsdb.uid.NoSuchUniqueName;
/**
* Non-synchronized implementation of {@link Query}.
*/
final class TsdbQuery implements Query {
private static final Logger LOG = LoggerFactory.getLogger(TsdbQuery.class);
/** Used whenever there are no results. */
private static final DataPoints[] NO_RESULT = new DataPoints[0];
/**
* Keep track of the latency we perceive when doing Scans on HBase.
* We want buckets up to 16s, with 2 ms interval between each bucket up to
* 100 ms after we which we switch to exponential buckets.
*/
static final Histogram scanlatency = new Histogram(16000, (short) 2, 100);
/**
* Charset to use with our server-side row-filter.
* We use this one because it preserves every possible byte unchanged.
*/
private static final Charset CHARSET = Charset.forName("ISO-8859-1");
/** The TSDB we belong to. */
private final TSDB tsdb;
/** Start time (UNIX timestamp in seconds) on 32 bits ("unsigned" int). */
private int start_time;
/** End time (UNIX timestamp in seconds) on 32 bits ("unsigned" int). */
private int end_time;
/** ID of the metric being looked up. */
private byte[] metric;
/**
* Tags of the metrics being looked up.
* Each tag is a byte array holding the ID of both the name and value
* of the tag.
* Invariant: an element cannot be both in this array and in group_bys.
*/
private ArrayList<byte[]> tags;
/**
* Tags by which we must group the results.
* Each element is a tag ID.
* Invariant: an element cannot be both in this array and in {@code tags}.
*/
private ArrayList<byte[]> group_bys;
/**
* Values we may be grouping on.
* For certain elements in {@code group_bys}, we may have a specific list of
* values IDs we're looking for. Those IDs are stored in this map. The key
* is an element of {@code group_bys} (so a tag name ID) and the values are
* tag value IDs (at least two).
*/
private ByteMap<byte[][]> group_by_values;
/** If true, use rate of change instead of actual values. */
private boolean rate;
/** Aggregator function to use. */
private Aggregator aggregator;
/**
* Downsampling function to use, if any (can be {@code null}).
* If this is non-null, {@code sample_interval} must be strictly positive.
*/
private Aggregator downsampler;
/** Minimum time interval (in seconds) wanted between each data point. */
private int sample_interval;
/** Constructor. */
public TsdbQuery(final TSDB tsdb) {
this.tsdb = tsdb;
}
public void setStartTime(final long timestamp) {
if ((timestamp & 0xFFFFFFFF00000000L) != 0) {
throw new IllegalArgumentException("Invalid timestamp: " + timestamp);
} else if (end_time != 0 && timestamp >= getEndTime()) {
throw new IllegalArgumentException("new start time (" + timestamp
+ ") is greater than or equal to end time: " + getEndTime());
}
// Keep the 32 bits.
start_time = (int) timestamp;
}
public long getStartTime() {
if (start_time == 0) {
throw new IllegalStateException("setStartTime was never called!");
}
return start_time & 0x00000000FFFFFFFFL;
}
public void setEndTime(final long timestamp) {
if ((timestamp & 0xFFFFFFFF00000000L) != 0) {
throw new IllegalArgumentException("Invalid timestamp: " + timestamp);
} else if (start_time != 0 && timestamp <= getStartTime()) {
throw new IllegalArgumentException("new end time (" + timestamp
+ ") is less than or equal to start time: " + getStartTime());
}
// Keep the 32 bits.
end_time = (int) timestamp;
}
public long getEndTime() {
if (end_time == 0) {
setEndTime(System.currentTimeMillis() / 1000);
}
return end_time;
}
public void setTimeSeries(final String metric,
final Map<String, String> tags,
final Aggregator function,
final boolean rate) throws NoSuchUniqueName {
findGroupBys(tags);
this.metric = tsdb.metrics.getId(metric);
this.tags = Tags.resolveAll(tsdb, tags);
aggregator = function;
this.rate = rate;
}
public void downsample(final int interval, final Aggregator downsampler) {
if (downsampler == null) {
throw new NullPointerException("downsampler");
} else if (interval <= 0) {
throw new IllegalArgumentException("interval not > 0: " + interval);
}
this.downsampler = downsampler;
this.sample_interval = interval;
}
/**
* Extracts all the tags we must use to group results.
* <ul>
* <li>If a tag has the form {@code name=*} then we'll create one
* group per value we find for that tag.</li>
* <li>If a tag has the form {@code name={v1,v2,..,vN}} then we'll
* create {@code N} groups.</li>
* </ul>
* In the both cases above, {@code name} will be stored in the
* {@code group_bys} attribute. In the second case specifically,
* the {@code N} values would be stored in {@code group_by_values},
* the key in this map being {@code name}.
* @param tags The tags from which to extract the 'GROUP BY's.
* Each tag that represents a 'GROUP BY' will be removed from the map
* passed in argument.
*/
private void findGroupBys(final Map<String, String> tags) {
final Iterator<Map.Entry<String, String>> i = tags.entrySet().iterator();
while (i.hasNext()) {
final Map.Entry<String, String> tag = i.next();
final String tagvalue = tag.getValue();
if (tagvalue.equals("*") // 'GROUP BY' with any value.
|| tagvalue.indexOf('|', 1) >= 0) { // Multiple possible values.
if (group_bys == null) {
group_bys = new ArrayList<byte[]>();
}
group_bys.add(tsdb.tag_names.getId(tag.getKey()));
i.remove();
if (tagvalue.charAt(0) == '*') {
continue; // For a 'GROUP BY' with any value, we're done.
}
// 'GROUP BY' with specific values. Need to split the values
// to group on and store their IDs in group_by_values.
final String[] values = Tags.splitString(tagvalue, '|');
if (group_by_values == null) {
group_by_values = new ByteMap<byte[][]>();
}
final short value_width = tsdb.tag_values.width();
final byte[][] value_ids = new byte[values.length][value_width];
group_by_values.put(tsdb.tag_names.getId(tag.getKey()),
value_ids);
for (int j = 0; j < values.length; j++) {
final byte[] value_id = tsdb.tag_values.getId(values[j]);
System.arraycopy(value_id, 0, value_ids[j], 0, value_width);
}
}
}
}
public DataPoints[] run() throws HBaseException {
return groupByAndAggregate(findSpans());
}
private TreeMap<byte[], Span> findSpans() throws HBaseException {
final short metric_width = tsdb.metrics.width();
final TreeMap<byte[], Span> spans = // The key is a row key from HBase.
new TreeMap<byte[], Span>(new SpanCmp(metric_width));
int nrows = 0;
int hbase_time = 0; // milliseconds.
long starttime = System.nanoTime();
final Scanner scanner = getScanner();
try {
ArrayList<ArrayList<KeyValue>> rows;
while ((rows = scanner.nextRows().joinUninterruptibly()) != null) {
hbase_time += (System.nanoTime() - starttime) / 1000000;
for (final ArrayList<KeyValue> row : rows) {
final byte[] key = row.get(0).key();
if (Bytes.memcmp(metric, key, 0, metric_width) != 0) {
throw new AssertionError("HBase returned a row that doesn't match"
+ " our scanner (" + scanner + ")! " + row + " does not start"
+ " with " + Arrays.toString(metric));
}
Span datapoints = spans.get(key);
if (datapoints == null) {
datapoints = new Span(tsdb);
spans.put(key, datapoints);
}
datapoints.addRow(row);
nrows++;
starttime = System.nanoTime();
}
}
} catch (HBaseException e) {
throw e;
} catch (IllegalArgumentException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Should never be here", e);
} finally {
hbase_time += (System.nanoTime() - starttime) / 1000000;
scanlatency.add(hbase_time);
}
LOG.info(this + " matched " + nrows + " rows in " + spans.size() + " spans");
if (nrows == 0) {
return null;
}
return spans;
}
/**
* Creates the {@link SpanGroup}s to form the final results of this query.
* @param spans The {@link Span}s found for this query ({@link #findSpans}).
* Can be {@code null}, in which case the array returned will be empty.
* @return A possibly empty array of {@link SpanGroup}s built according to
* any 'GROUP BY' formulated in this query.
*/
private DataPoints[] groupByAndAggregate(final TreeMap<byte[], Span> spans) {
if (spans == null || spans.size() <= 0) {
return NO_RESULT;
}
if (group_bys == null) {
// We haven't been asked to find groups, so let's put all the spans
// together in the same group.
final SpanGroup group = new SpanGroup(tsdb,
getScanStartTime(),
getScanEndTime(),
spans.values(),
rate,
aggregator,
sample_interval, downsampler);
return new SpanGroup[] { group };
}
// Maps group value IDs to the SpanGroup for those values. Say we've
// been asked to group by two things: foo=* bar=* Then the keys in this
// map will contain all the value IDs combinations we've seen. If the
// name IDs for `foo' and `bar' are respectively [0, 0, 7] and [0, 0, 2]
// then we'll have group_bys=[[0, 0, 2], [0, 0, 7]] (notice it's sorted
// by ID, so bar is first) and say we find foo=LOL bar=OMG as well as
// foo=LOL bar=WTF and that the IDs of the tag values are:
// LOL=[0, 0, 1] OMG=[0, 0, 4] WTF=[0, 0, 3]
// then the map will have two keys:
// - one for the LOL-OMG combination: [0, 0, 1, 0, 0, 4] and,
// - one for the LOL-WTF combination: [0, 0, 1, 0, 0, 3].
final ByteMap<SpanGroup> groups = new ByteMap<SpanGroup>();
final short metric_ts_bytes = (short) (tsdb.metrics.width()
+ Const.TIMESTAMP_BYTES);
final short name_width = tsdb.tag_names.width();
final short value_width = tsdb.tag_values.width();
final short tag_bytes = (short) (name_width + value_width);
final byte[] group = new byte[group_bys.size() * value_width];
for (final Map.Entry<byte[], Span> entry : spans.entrySet()) {
final byte[] row = entry.getKey();
byte[] value_id = null;
int i = 0;
// TODO(tsuna): The following loop has a quadratic behavior. We can
// make it much better since both the row key and group_bys are sorted.
for (final byte[] tag_id : group_bys) {
value_id = Tags.getValueId(tsdb, row, tag_id);
if (value_id == null) {
break;
}
System.arraycopy(value_id, 0, group, i, value_width);
i += value_width;
}
if (value_id == null) {
LOG.error("WTF? Dropping span for row " + Arrays.toString(row)
+ " as it had no matching tag from the requested groups,"
+ " which is unexpected. Query=" + this);
continue;
}
//LOG.info("Span belongs to group " + Arrays.toString(group) + ": " + Arrays.toString(row));
SpanGroup thegroup = groups.get(group);
if (thegroup == null) {
thegroup = new SpanGroup(tsdb, getScanStartTime(), getScanEndTime(),
null, rate, aggregator,
sample_interval, downsampler);
// Copy the array because we're going to keep `group' and overwrite
// its contents. So we want the collection to have an immutable copy.
final byte[] group_copy = new byte[group.length];
System.arraycopy(group, 0, group_copy, 0, group.length);
groups.put(group_copy, thegroup);
}
thegroup.add(entry.getValue());
}
//for (final Map.Entry<byte[], SpanGroup> entry : groups) {
// LOG.info("group for " + Arrays.toString(entry.getKey()) + ": " + entry.getValue());
return groups.values().toArray(new SpanGroup[groups.size()]);
}
/**
* Creates the {@link Scanner} to use for this query.
*/
private Scanner getScanner() throws HBaseException {
final short metric_width = tsdb.metrics.width();
final byte[] start_row = new byte[metric_width + Const.TIMESTAMP_BYTES];
final byte[] end_row = new byte[metric_width + Const.TIMESTAMP_BYTES];
// We search at least one row before and one row after the start & end
// time we've been given as it's quite likely that the exact timestamp
// we're looking for is in the middle of a row. Plus, a number of things
// rely on having a few extra data points before & after the exact start
// & end dates in order to do proper rate calculation or downsampling near
// the "edges" of the graph.
Bytes.setInt(start_row, (int) getScanStartTime(), metric_width);
Bytes.setInt(end_row, (end_time == 0
? -1 // Will scan until the end (0xFFF...).
: (int) getScanEndTime()),
metric_width);
System.arraycopy(metric, 0, start_row, 0, metric_width);
System.arraycopy(metric, 0, end_row, 0, metric_width);
final Scanner scanner = tsdb.client.newScanner(tsdb.table);
scanner.setStartKey(start_row);
scanner.setStopKey(end_row);
if (tags.size() > 0 || group_bys != null) {
createAndSetFilter(scanner);
}
scanner.setFamily(TSDB.FAMILY);
return scanner;
}
/** Returns the UNIX timestamp from which we must start scanning. */
private long getScanStartTime() {
// The reason we look before by `MAX_TIMESPAN * 2' seconds is because of
// the following. Let's assume MAX_TIMESPAN = 600 (10 minutes) and the
// start_time = ... 12:31:00. If we initialize the scanner to look
// only 10 minutes before, we'll start scanning at time=12:21, which will
// give us the row that starts at 12:30 (remember: rows are always aligned
// on MAX_TIMESPAN boundaries -- so in this example, on 10m boundaries).
// But we need to start scanning at least 1 row before, so we actually
// look back by twice MAX_TIMESPAN. Only when start_time is aligned on a
// MAX_TIMESPAN boundary then we'll mistakenly scan back by an extra row,
// but this doesn't really matter.
// Additionally, in case our sample_interval is large, we need to look
// even further before/after, so use that too.
return getStartTime() - Const.MAX_TIMESPAN * 2 - sample_interval;
}
/** Returns the UNIX timestamp at which we must stop scanning. */
private long getScanEndTime() {
// For the end_time, we have a different problem. For instance if our
// end_time = ... 12:30:00, we'll stop scanning when we get to 12:40, but
// once again we wanna try to look ahead one more row, so to avoid this
// problem we always add 1 second to the end_time. Only when the end_time
// is of the form HH:59:59 then we will scan ahead an extra row, but once
// again that doesn't really matter.
// Additionally, in case our sample_interval is large, we need to look
// even further before/after, so use that too.
return getEndTime() + Const.MAX_TIMESPAN + 1 + sample_interval;
}
/**
* Sets the server-side regexp filter on the scanner.
* In order to find the rows with the relevant tags, we use a
* server-side filter that matches a regular expression on the row key.
* @param scanner The scanner on which to add the filter.
*/
void createAndSetFilter(final Scanner scanner) {
if (group_bys != null) {
Collections.sort(group_bys, Bytes.MEMCMP);
}
final short name_width = tsdb.tag_names.width();
final short value_width = tsdb.tag_values.width();
final short tagsize = (short) (name_width + value_width);
// Generate a regexp for our tags. Say we have 2 tags: { 0 0 1 0 0 2 }
// and { 4 5 6 9 8 7 }, the regexp will be:
// "^.{7}(?:.{6})*\\Q\000\000\001\000\000\002\\E(?:.{6})*\\Q\004\005\006\011\010\007\\E(?:.{6})*$"
final StringBuilder buf = new StringBuilder(
15 // "^.{N}" + "(?:.{M})*" + "$"
+ ((13 + tagsize) // "(?:.{M})*\\Q" + tagsize bytes + "\\E"
* (tags.size() + (group_bys == null ? 0 : group_bys.size() * 3))));
// In order to avoid re-allocations, reserve a bit more w/ groups ^^^
// Alright, let's build this regexp. From the beginning...
buf.append("(?s)" // Ensure we use the DOTALL flag.
+ "^.{")
// ... start by skipping the metric ID and timestamp.
.append(tsdb.metrics.width() + Const.TIMESTAMP_BYTES)
.append("}");
final Iterator<byte[]> tags = this.tags.iterator();
final Iterator<byte[]> group_bys = (this.group_bys == null
? new ArrayList<byte[]>(0).iterator()
: this.group_bys.iterator());
byte[] tag = tags.hasNext() ? tags.next() : null;
byte[] group_by = group_bys.hasNext() ? group_bys.next() : null;
// Tags and group_bys are already sorted. We need to put them in the
// regexp in order by ID, which means we just merge two sorted lists.
do {
// Skip any number of tags.
buf.append("(?:.{").append(tagsize).append("})*\\Q");
if (isTagNext(name_width, tag, group_by)) {
addId(buf, tag);
tag = tags.hasNext() ? tags.next() : null;
} else { // Add a group_by.
addId(buf, group_by);
final byte[][] value_ids = (group_by_values == null
? null
: group_by_values.get(group_by));
if (value_ids == null) { // We don't want any specific ID...
buf.append(".{").append(value_width).append('}'); // Any value ID.
} else { // We want specific IDs. List them: /(AAA|BBB|CCC|..)/
buf.append("(?:");
for (final byte[] value_id : value_ids) {
buf.append("\\Q");
addId(buf, value_id);
buf.append('|');
}
// Replace the pipe of the last iteration.
buf.setCharAt(buf.length() - 1, ')');
}
group_by = group_bys.hasNext() ? group_bys.next() : null;
}
} while (tag != group_by); // Stop when they both become null.
// Skip any number of tags before the end.
buf.append("(?:.{").append(tagsize).append("})*$");
scanner.setKeyRegexp(buf.toString(), CHARSET);
}
/**
* Helper comparison function to compare tag name IDs.
* @param name_width Number of bytes used by a tag name ID.
* @param tag A tag (array containing a tag name ID and a tag value ID).
* @param group_by A tag name ID.
* @return {@code true} number if {@code tag} should be used next (because
* it contains a smaller ID), {@code false} otherwise.
*/
private boolean isTagNext(final short name_width,
final byte[] tag,
final byte[] group_by) {
if (tag == null) {
return false;
} else if (group_by == null) {
return true;
}
final int cmp = Bytes.memcmp(tag, group_by, 0, name_width);
if (cmp == 0) {
throw new AssertionError("invariant violation: tag ID "
+ Arrays.toString(group_by) + " is both in 'tags' and"
+ " 'group_bys' in " + this);
}
return cmp < 0;
}
/**
* Appends the given ID to the given buffer, followed by "\\E".
*/
private static void addId(final StringBuilder buf, final byte[] id) {
for (final byte b : id) {
buf.append((char) (b & 0xFF));
if (b == '\\') { // Escape the escape characters that are in the ID.
buf.append('\\');
}
}
buf.append("\\E");
}
public String toString() {
final StringBuilder buf = new StringBuilder();
buf.append("TsdbQuery(start_time=")
.append(getStartTime())
.append(", end_time=")
.append(getEndTime())
.append(", metric=").append(Arrays.toString(metric));
try {
buf.append(" (").append(tsdb.metrics.getName(metric));
} catch (NoSuchUniqueId e) {
buf.append(" (<").append(e.getMessage()).append('>');
}
try {
buf.append("), tags=").append(Tags.resolveIds(tsdb, tags));
} catch (NoSuchUniqueId e) {
buf.append("), tags=<").append(e.getMessage()).append('>');
}
buf.append(", rate=").append(rate)
.append(", aggregator=").append(aggregator)
.append(", group_bys=(");
if (group_bys != null) {
for (final byte[] tag_id : group_bys) {
try {
buf.append(tsdb.tag_names.getName(tag_id));
} catch (NoSuchUniqueId e) {
buf.append('<').append(e.getMessage()).append('>');
}
buf.append(' ')
.append(Arrays.toString(tag_id));
if (group_by_values != null) {
final byte[][] value_ids = group_by_values.get(tag_id);
if (value_ids == null) {
continue;
}
buf.append("={");
for (final byte[] value_id : value_ids) {
try {
buf.append(tsdb.tag_values.getName(value_id));
} catch (NoSuchUniqueId e) {
buf.append('<').append(e.getMessage()).append('>');
}
buf.append(' ')
.append(Arrays.toString(value_id))
.append(", ");
}
buf.append('}');
}
buf.append(", ");
}
}
buf.append("))");
return buf.toString();
}
/**
* Comparator that ignores timestamps in row keys.
*/
private static final class SpanCmp implements Comparator<byte[]> {
private final short metric_width;
public SpanCmp(final short metric_width) {
this.metric_width = metric_width;
}
public int compare(final byte[] a, final byte[] b) {
final int length = Math.min(a.length, b.length);
if (a == b) { // Do this after accessing a.length and b.length
return 0; // in order to NPE if either a or b is null.
}
int i;
// First compare the metric ID.
for (i = 0; i < metric_width; i++) {
if (a[i] != b[i]) {
return (a[i] & 0xFF) - (b[i] & 0xFF); // "promote" to unsigned.
}
}
// Then skip the timestamp and compare the rest.
for (i += Const.TIMESTAMP_BYTES; i < length; i++) {
if (a[i] != b[i]) {
return (a[i] & 0xFF) - (b[i] & 0xFF); // "promote" to unsigned.
}
}
return a.length - b.length;
}
}
}
|
package com.battlelancer.thetvdbapi;
import com.battlelancer.seriesguide.Constants;
import com.battlelancer.seriesguide.SeriesDatabase;
import com.battlelancer.seriesguide.SeriesGuideApplication;
import com.battlelancer.seriesguide.SeriesGuideData;
import com.battlelancer.seriesguide.provider.SeriesContract;
import com.battlelancer.seriesguide.provider.SeriesContract.EpisodeSearch;
import com.battlelancer.seriesguide.provider.SeriesContract.Episodes;
import com.battlelancer.seriesguide.provider.SeriesContract.Seasons;
import com.battlelancer.seriesguide.provider.SeriesContract.Shows;
import com.battlelancer.seriesguide.util.Lists;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlPullParser;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.sax.Element;
import android.sax.EndElementListener;
import android.sax.EndTextElementListener;
import android.sax.RootElement;
import android.text.format.DateUtils;
import android.util.Log;
import android.util.Xml;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.zip.ZipInputStream;
public class TheTVDB {
private static final String mirror = "http:
private static final String mirror_banners = "http:
private static final String xmlMirror = mirror + "/api/";
private static final String TAG = "TheTVDB";
private static final int SECOND_IN_MILLIS = (int) DateUtils.SECOND_IN_MILLIS;
/**
* Adds a show and its episodes. If it already exists updates them. This
* uses two consequent connections. The first one downloads the base series
* record, to check if the show is already in the database. The second
* downloads all episode information. This allows for a smaller download, if
* a show already exists in your database.
*
* @param showId
* @return true if show and its episodes were added, false if it already
* exists
* @throws IOException
* @throws SAXException
*/
public static boolean addShow(String showId, Context context) throws SAXException {
String language = getTheTVDBLanguage(context);
Series show = fetchShow(showId, language, context);
boolean isShowExists = SeriesDatabase.isShowExists(showId, context);
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
batch.add(SeriesDatabase.buildShowOp(show, context, !isShowExists));
batch.addAll(importShowEpisodes(showId, language, context));
try {
context.getContentResolver().applyBatch(SeriesContract.CONTENT_AUTHORITY, batch);
} catch (RemoteException e) {
// Failed binder transactions aren't recoverable
throw new RuntimeException("Problem applying batch operation", e);
} catch (OperationApplicationException e) {
// Failures like constraint violation aren't recoverable
throw new RuntimeException("Problem applying batch operation", e);
}
SeriesDatabase.updateLatestEpisode(context, showId);
return !isShowExists;
}
/**
* Just fetch all series and episode details and overwrite, add.
*
* @param showId
* @throws SAXException
* @throws IOException
*/
public static void updateShow(String showId, Context context) throws SAXException {
String language = getTheTVDBLanguage(context);
Series show = fetchShow(showId, language, context);
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
batch.add(SeriesDatabase.buildShowOp(show, context, false));
batch.addAll(importShowEpisodes(showId, language, context));
try {
context.getContentResolver().applyBatch(SeriesContract.CONTENT_AUTHORITY, batch);
} catch (RemoteException e) {
// Failed binder transactions aren't recoverable
throw new RuntimeException("Problem applying batch operation", e);
} catch (OperationApplicationException e) {
// Failures like constraint violation aren't recoverable
throw new RuntimeException("Problem applying batch operation", e);
}
}
/**
* Get details for one show, identified by the given seriesid.
*
* @param seriesid
* @param language
* @return a Series object, holding the information about the show
* @throws SAXException
* @throws IOException
*/
public static Series fetchShow(String seriesid, String language, Context context)
throws SAXException {
String url = xmlMirror + Constants.API_KEY + "/series/" + seriesid + "/"
+ (language != null ? language + ".xml" : "");
return parseShow(url, context);
}
/**
* Search for shows which include a certain keyword in their title.
* Dependent on the TheTVDB search algorithms.
*
* @param title
* @return a List with SearchResult objects, max 100
* @throws SAXException
* @throws IOException
*/
public static List<SearchResult> searchShow(String title, Context context) throws IOException,
SAXException {
String language = getTheTVDBLanguage(context);
URL url;
try {
url = new URL(xmlMirror + "GetSeries.php?seriesname="
+ URLEncoder.encode(title, "UTF-8")
+ (language != null ? "&language=" + language : ""));
} catch (Exception e) {
throw new RuntimeException(e);
}
final List<SearchResult> series = new ArrayList<SearchResult>();
final SearchResult currentShow = new SearchResult();
RootElement root = new RootElement("Data");
Element item = root.getChild("Series");
// set handlers for elements we want to react to
item.setEndElementListener(new EndElementListener() {
public void end() {
series.add(currentShow.copy());
}
});
item.getChild("id").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentShow.setId(Integer.valueOf(body));
}
});
item.getChild("SeriesName").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentShow.setSeriesName(body.trim());
}
});
item.getChild("Overview").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentShow.setOverview(body.trim());
}
});
URLConnection connection = url.openConnection();
connection.setConnectTimeout(25000);
connection.setReadTimeout(90000);
InputStream in = connection.getInputStream();
try {
Xml.parse(in, Xml.Encoding.UTF_8, root.getContentHandler());
} catch (SocketTimeoutException se) {
throw new IOException();
}
in.close();
return series;
}
/**
* Parses the xml downloaded from the given url into a {@link Series}
* object. Downloads the poster if there is one.
*
* @param url
* @param context
* @return the show wrapped in a {@link Series} object
* @throws SAXException
*/
public static Series parseShow(String url, final Context context) throws SAXException {
final Series currentShow = new Series();
RootElement root = new RootElement("Data");
Element show = root.getChild("Series");
// set handlers for elements we want to react to
show.getChild("id").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentShow.setId(body.trim());
}
});
show.getChild("Language").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentShow.setLanguage(body.trim());
}
});
show.getChild("SeriesName").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentShow.setSeriesName(body.trim());
}
});
show.getChild("Overview").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentShow.setOverview(body.trim());
}
});
show.getChild("Actors").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentShow.setActors(body.trim());
}
});
show.getChild("Airs_DayOfWeek").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentShow.setAirsDayOfWeek(body.trim());
}
});
show.getChild("Airs_Time").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentShow.setAirsTime(SeriesGuideData.parseTimeToMilliseconds(body.trim()));
}
});
show.getChild("FirstAired").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentShow.setFirstAired(body.trim());
}
});
show.getChild("Genre").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentShow.setGenres(body.trim());
}
});
show.getChild("Network").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentShow.setNetwork(body.trim());
}
});
show.getChild("Rating").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentShow.setRating(body.trim());
}
});
show.getChild("Runtime").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentShow.setRuntime(body.trim());
}
});
show.getChild("Status").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
final String status = body.trim();
if (status.length() == 10) {
currentShow.setStatus(1);
} else if (status.length() == 5) {
currentShow.setStatus(0);
} else {
currentShow.setStatus(-1);
}
}
});
show.getChild("ContentRating").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentShow.setContentRating(body.trim());
}
});
show.getChild("poster").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
String posterurl = body.trim();
currentShow.setPoster(posterurl);
if (posterurl.length() != 0) {
fetchArt(posterurl, true, context);
}
}
});
show.getChild("IMDB_ID").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
currentShow.setImdbId(body.trim());
}
});
HttpUriRequest request = new HttpGet(url);
HttpClient httpClient = getHttpClient(context);
execute(request, httpClient, root.getContentHandler(), false);
return currentShow;
}
public static ArrayList<ContentProviderOperation> importShowEpisodes(String seriesid,
String language, Context context) throws SAXException {
String url = xmlMirror + Constants.API_KEY + "/series/" + seriesid + "/all/"
+ (language != null ? language + ".zip" : "en.zip");
return parseEpisodes(url, seriesid, context);
}
public static ArrayList<ContentProviderOperation> parseEpisodes(String url, String seriesid,
Context context) throws SAXException {
RootElement root = new RootElement("Data");
Element episode = root.getChild("Episode");
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
final HashSet<Long> episodeIDs = SeriesDatabase.getEpisodeIDsForShow(seriesid, context);
final HashSet<Long> existingSeasonIDs = SeriesDatabase.getSeasonIDsForShow(seriesid,
context);
final HashSet<Long> updatedSeasonIDs = new HashSet<Long>();
final ContentValues values = new ContentValues();
// set handlers for elements we want to react to
episode.setEndElementListener(new EndElementListener() {
public void end() {
// add insert/update op for episode
batch.add(SeriesDatabase.buildEpisodeOp(values,
!episodeIDs.contains(values.getAsLong(Episodes._ID))));
long seasonid = values.getAsLong(Seasons.REF_SEASON_ID);
if (!updatedSeasonIDs.contains(seasonid)) {
// add insert/update op for season
batch.add(SeriesDatabase.buildSeasonOp(values,
!existingSeasonIDs.contains(seasonid)));
updatedSeasonIDs.add(values.getAsLong(Seasons.REF_SEASON_ID));
}
values.clear();
}
});
episode.getChild("id").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes._ID, body.trim());
}
});
episode.getChild("EpisodeNumber").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.NUMBER, body.trim());
}
});
episode.getChild("SeasonNumber").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.SEASON, body.trim());
}
});
episode.getChild("DVD_episodenumber").setEndTextElementListener(
new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.DVDNUMBER, body.trim());
}
});
episode.getChild("FirstAired").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.FIRSTAIRED, body.trim());
}
});
episode.getChild("EpisodeName").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.TITLE, body.trim());
}
});
episode.getChild("Overview").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.OVERVIEW, body.trim());
}
});
episode.getChild("seasonid").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Seasons.REF_SEASON_ID, body.trim());
}
});
episode.getChild("seriesid").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Shows.REF_SHOW_ID, body.trim());
}
});
episode.getChild("Director").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.DIRECTORS, body.trim());
}
});
episode.getChild("GuestStars").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.GUESTSTARS, body.trim());
}
});
episode.getChild("Writer").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.WRITERS, body.trim());
}
});
episode.getChild("Rating").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.RATING, body.trim());
}
});
episode.getChild("filename").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
values.put(Episodes.IMAGE, body.trim());
}
});
HttpUriRequest request = new HttpGet(url);
HttpClient httpClient = getHttpClient(context);
execute(request, httpClient, root.getContentHandler(), true);
return batch;
}
/**
* Return list of show ids which have been updated since
* {@code previousUpdateTime}. Time is UNIX time.
*
* @param previousUpdateTime
* @param context
* @return
* @throws SAXException
*/
public static String[] deltaUpdateShows(long previousUpdateTime, Context context)
throws SAXException {
// get existing show ids
final Cursor shows = context.getContentResolver().query(Shows.CONTENT_URI, new String[] {
Shows._ID
}, null, null, null);
final HashSet<Integer> existingShowIds = new HashSet<Integer>();
while (shows.moveToNext()) {
existingShowIds.add(shows.getInt(0));
}
// get existing episode ids
final Cursor episodes = context.getContentResolver().query(Episodes.CONTENT_URI,
new String[] {
Episodes._ID, Shows.REF_SHOW_ID
}, null, null, null);
final HashMap<String, String> episodeMap = new HashMap<String, String>();
while (episodes.moveToNext()) {
episodeMap.put(episodes.getString(0), episodes.getString(1));
}
// parse updatable show ids
// TODO: look for better data structure (which allows insert=replace)
final ArrayList<String> updatableShowIds = new ArrayList<String>();
final RootElement root = new RootElement("Items");
root.getChild("Series").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
if (existingShowIds.contains(body)) {
updatableShowIds.add(body);
}
}
});
root.getChild("Episode").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
String showId = episodeMap.get(body);
if (showId != null && !updatableShowIds.contains(showId)) {
updatableShowIds.add(showId);
}
}
});
final String url = xmlMirror + "Updates.php?type=all&time=" + previousUpdateTime;
HttpUriRequest request = new HttpGet(url);
HttpClient httpClient = getHttpClient(context);
execute(request, httpClient, root.getContentHandler(), false);
return updatableShowIds.toArray(new String[updatableShowIds.size()]);
}
/**
* Get current server UNIX time.
*
* @param context
* @return
* @throws SAXException
*/
public static long getServerTime(Context context) throws SAXException {
final long[] serverTime = new long[1];
final RootElement root = new RootElement("Items");
root.getChild("Time").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
serverTime[0] = Long.valueOf(body);
}
});
final String url = xmlMirror + "Updates.php?type=none";
HttpUriRequest request = new HttpGet(url);
HttpClient httpClient = getHttpClient(context);
execute(request, httpClient, root.getContentHandler(), false);
return serverTime[0];
}
/**
* Tries to download art from the thetvdb banner mirror. Ignores blank ("")
* or null paths and skips existing images. Returns true even if there was
* no art downloaded.
*
* @param fileName of image
* @param isPoster
* @param context
* @return false if not all images could be fetched. true otherwise, even if
* nothing was downloaded
*/
public static boolean fetchArt(String fileName, boolean isPoster, Context context) {
if (fileName == null || context == null) {
return true;
}
Bitmap bitmap = null;
ImageCache imageCache = ((SeriesGuideApplication) context.getApplicationContext())
.getImageCache();
boolean resultCode = true;
if (fileName.length() != 0 && imageCache.get(fileName) == null) {
try {
String imageUrl;
if (isPoster) {
imageUrl = mirror_banners + "/_cache/" + fileName;
} else {
imageUrl = mirror_banners + "/" + fileName;
}
// try to download and decode the image
bitmap = downloadBitmap(imageUrl);
if (bitmap != null) {
imageCache.put(fileName, bitmap);
if (isPoster) {
// create thumbnail
imageCache.getThumbHelper(fileName);
}
} else {
resultCode = false;
}
} catch (MalformedURLException e) {
// do nothing, just skip this one (should only happen if there
// are faulty paths in thetvdb)
}
}
return resultCode;
}
static Bitmap downloadBitmap(String url) throws MalformedURLException {
final DefaultHttpClient client = new DefaultHttpClient();
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(TAG, "Error " + statusCode + " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
return BitmapFactory.decodeStream(inputStream);
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (IOException e) {
getRequest.abort();
Log.w(TAG, "I/O error while retrieving bitmap from " + url, e);
} catch (IllegalStateException e) {
getRequest.abort();
Log.w(TAG, "Incorrect URL: " + url);
} catch (Exception e) {
getRequest.abort();
Log.w(TAG, "Error while retrieving bitmap from " + url, e);
}
return null;
}
private static String getTheTVDBLanguage(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context
.getApplicationContext());
return prefs.getString("language", "en");
}
public static void onRenewFTSTable(Context context) {
context.getContentResolver().query(EpisodeSearch.CONTENT_URI_RENEWFTSTABLE, null, null,
null, null);
}
/**
* Generate and return a {@link HttpClient} configured for general use,
* including setting an application-specific user-agent string.
*/
public static HttpClient getHttpClient(Context context) {
final HttpParams params = new BasicHttpParams();
// Use generous timeouts for slow mobile networks
HttpConnectionParams.setConnectionTimeout(params, 20 * SECOND_IN_MILLIS);
HttpConnectionParams.setSoTimeout(params, 20 * SECOND_IN_MILLIS);
HttpConnectionParams.setSocketBufferSize(params, 8192);
final DefaultHttpClient client = new DefaultHttpClient(params);
return client;
}
/**
* Execute this {@link HttpUriRequest}, passing a valid response through
* {@link XmlHandler#parseAndApply(XmlPullParser, ContentResolver)}.
*/
private static void execute(HttpUriRequest request, HttpClient httpClient,
ContentHandler handler, boolean isZipFile) throws SAXException {
try {
final HttpResponse resp = httpClient.execute(request);
final int status = resp.getStatusLine().getStatusCode();
if (status != HttpStatus.SC_OK) {
throw new SAXException("Unexpected server response " + resp.getStatusLine()
+ " for " + request.getRequestLine());
}
final InputStream input = resp.getEntity().getContent();
if (isZipFile) {
// We downloaded the compressed file from TheTVDB
final ZipInputStream zipin = new ZipInputStream(input);
zipin.getNextEntry();
try {
Xml.parse(zipin, Xml.Encoding.UTF_8, handler);
} catch (SAXException e) {
throw new SAXException("Malformed response for " + request.getRequestLine(), e);
} catch (IOException ioe) {
throw new SAXException("Problem reading remote response for "
+ request.getRequestLine(), ioe);
} finally {
if (zipin != null) {
zipin.close();
}
}
} else {
try {
Xml.parse(input, Xml.Encoding.UTF_8, handler);
} catch (SAXException e) {
throw new SAXException("Malformed response for " + request.getRequestLine(), e);
} catch (IOException ioe) {
throw new SAXException("Problem reading remote response for "
+ request.getRequestLine(), ioe);
} finally {
if (input != null) {
input.close();
}
}
}
} catch (AssertionError ae) {
// looks like Xml.parse is throwing AssertionErrors instead of
// IOExceptions
throw new SAXException("Problem reading remote response for "
+ request.getRequestLine());
} catch (IOException e) {
throw new SAXException("Problem reading remote response for "
+ request.getRequestLine(), e);
}
}
}
|
package draw;
import grid.GridGraph;
import grid.StartGoalPoints;
import java.awt.Color;
import java.util.ArrayList;
import main.AnyAnglePathfinding;
import main.analysis.ProblemAnalysis;
import main.analysis.TwoPoint;
import main.testgen.Stringifier;
import main.testgen.TestDataGenerator;
import main.utility.Utility;
import uiandio.FileIO;
import algorithms.datatypes.Point;
public class EditorUI extends DrawCanvas {
private int sx;
private int sy;
private int ex;
private int ey;
private final GridPointSet pointSet;
private final ArrayList<ArrayList<Point>> connectedSets;
private final String mazeName;
public EditorUI(GridGraph gridGraph, ArrayList<ArrayList<Point>> connectedSets, String mazeName, StartGoalPoints startGoalPoints) {
super(gridGraph);
this.mazeName = mazeName;
this.connectedSets = connectedSets;
pointSet = new GridPointSet();
pointSet.setMinCircleSize();
if (startGoalPoints == null) {
sx = -1;
sy = -1;
ex = -1;
ey = -1;
} else {
sx = startGoalPoints.sx;
sy = startGoalPoints.sy;
ex = startGoalPoints.ex;
ey = startGoalPoints.ey;
}
refreshPoints();
}
public void addStartPoint(int x, int y) {
sx = x;
sy = y;
refreshPoints();
}
public void addEndPoint(int x, int y) {
ex = x;
ey = y;
refreshPoints();
}
private void refreshPoints() {
pointSet.clear();
if (startEndConnected()) {
pointSet.addPoint(sx, sy, Color.ORANGE);
pointSet.addPoint(ex, ey, Color.YELLOW);
} else {
if (sx != -1) {
pointSet.addPoint(sx, sy, Color.ORANGE);
}
if (ex != -1) {
pointSet.addPoint(ex, ey, Color.RED);
}
}
this.changeSet(pointSet);
}
private boolean startEndConnected() {
if (sx == -1 || sy == -1) return false;
Point start = new Point(sx, sy);
Point end = new Point(ex, ey);
for (int i=0; i<connectedSets.size(); i++) {
ArrayList<Point> currentSet = connectedSets.get(i);
if (currentSet.contains(start)) {
return currentSet.contains(end);
} else if (currentSet.contains(end)) {
return false;
}
}
return false;
}
public void generatePath() {
if (sx == -1 || ex == -1) return;
ArrayList<TwoPoint> tpList = TestDataGenerator.generateTwoPointList(sx, sy, ex, ey);
TestDataGenerator.generateTestData(gridGraph, tpList, mazeName, false);
}
public void generateMazeAnalysis() {
ArrayList<TwoPoint> tpList = new ArrayList<>();
TestDataGenerator.generateTestData(gridGraph, tpList, mazeName, true);
}
public void printPathAnalysis() {
if (sx == -1 || ex == -1) return;
ProblemAnalysis problemAnalysis = ProblemAnalysis.computeFast(gridGraph, sx, sy, ex, ey);
System.out.println("=Problem Analysis:=================");
System.out.println(problemAnalysis);
System.out.println("-Problem Name:
System.out.println(Stringifier.makeProblemName(sx, sy, ex, ey));
}
public void generateScen() {
// TODO Auto-generated method stub
String filePath = AnyAnglePathfinding.PATH_ANALYSISDATA;
String mapName = mazeName;
double shortestPath = Utility.computeOptimalPathLength(gridGraph, new Point(sx,sy), new Point(ex,ey));
System.out.println("-Writing to folder: " + filePath);
FileIO.makeDirs(filePath);
{
// Generate .map file
FileIO fileIO = new FileIO(filePath + mapName + ".map");
fileIO.writeLine("type octile");
fileIO.writeLine("height " + gridGraph.sizeY);
fileIO.writeLine("width " + gridGraph.sizeX);
fileIO.writeLine("map");
for (int y=0;y<gridGraph.sizeY;++y) {
StringBuilder sb = new StringBuilder();
for (int x=0;x<gridGraph.sizeX;++x) {
sb.append(gridGraph.isBlocked(x,y) ? "@" : ".");
}
fileIO.writeLine(sb.toString());
}
fileIO.close();
}
{
// Generate .scen file
FileIO fileIO = new FileIO(filePath + mapName + ".map.scen");
fileIO.writeLine("version 1");
String[] s = new String[]{
"1",
mapName + ".map",
gridGraph.sizeX + "",
gridGraph.sizeY + "",
sx + "",
sy + "",
ex + "",
ey + "",
shortestPath + ""
};
fileIO.writeLine(String.join("\t", s));
fileIO.close();
}
System.out.println("-Write complete.");
}
}
|
package tracking;
import Shapes.Shape;
import Shapes.Template;
import graphics.Frame;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
/**
*
* @author jeremi
*/
public class Tracking {
private Template tracked;
private Frame frame_1,frame_2;
public Tracking(Template tracked){
this.tracked = tracked;
}
/**
* @param args the command line arguments
*/
public static void init(String[] args) {
}
/*
gets all the shapes in the frame, rescale thier image in a buffer, compare buffer
with templates' image, returns an array containing n doubles (0 <= m <= 1), one per shape,
which contain the match percent
*/
public double[] compareWithTemplate(){
return compareWithTemplate(tracked,frame_2);
}
public double[] compareWithTemplate(Template t, Frame f){
double[] matchLevels = new double[f.getShapes().size()];
BufferedImage trackedSource = t.toImage();
for(int sh = 0; sh < f.getShapes().size();sh++){
Shape s = f.getShapes().get(sh);
BufferedImage s_source = s.getTemplate().toImage(),
rescaled = new BufferedImage(trackedSource.getWidth(),trackedSource.getHeight(),BufferedImage.TYPE_INT_RGB);
Graphics g = rescaled.createGraphics();
g.drawImage(s_source, 0,0,trackedSource.getWidth(),trackedSource.getHeight(),null);
g.dispose();
for(int y = 0; y < trackedSource.getHeight();y++){
double lineMatchLevel = 0;
for(int x = 0; x < trackedSource.getWidth();x++){
if(trackedSource.getRGB(x,y) == rescaled.getRGB(x,y)){
lineMatchLevel += 1/trackedSource.getWidth();
}
}
matchLevels[sh] = lineMatchLevel/trackedSource.getHeight();
}
}
return matchLevels;
}
/*
returns the shapes whom has the highest match level
uses compareWithTemplate()
*/
public Shape getHighestMatch(){
return getHighestMatch(tracked,frame_2);
}
public Shape getHighestMatch(Template t, Frame f){
double[] matches = this.compareWithTemplate();
int highest = 0;
for(int i = 0; i < matches.length;i++){
double d = matches[i];
if(d > highest){
highest = i;
}
}
Shape s = f.getShapes().get(highest);
return s;
}
public void nextFrame(Frame frame){
frame_1 = frame_2;
frame_2 = frame;
}
}
|
package com.bustiblelemons.views;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import com.bustiblelemons.bustiblelibs.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
/**
* Created 5 Nov 2013
*/
public class LoadingImage extends RelativeLayout implements ImageLoadingListener {
private View rootView;
private String addresToLoad;
private String failbackAddress;
private ProgressBar progress;
private ImageView image;
private boolean showProgress;
private int noImageRes = R.drawable.lemons;
private Animation animationIn;
private boolean useAnimations;
public LoadingImage(Context context) {
super(context);
init(context, null);
}
public LoadingImage(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public LoadingImage(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
rootView = LayoutInflater.from(context).inflate(R.layout.loading_image, this, true);
image = (ImageView) rootView.findViewById(R.id.___image);
progress = (ProgressBar) rootView.findViewById(R.id.___progress);
if (attrs != null) {
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.LoadingImage);
noImageRes = array.getResourceId(R.styleable.LoadingImage_no_image, R.drawable.lemons);
showProgress = array.getBoolean(R.styleable.LoadingImage_show_progressbar, false);
if (showProgress) {
progress.setVisibility(View.VISIBLE);
}
setupAnimations(array);
array.recycle();
}
}
private void setupAnimations(TypedArray array) {
useAnimations = array.getBoolean(R.styleable.LoadingImage_use_animations, false);
if (useAnimations) {
int _in = array.getResourceId(R.styleable.LoadingImage_animationIn, R.anim.abc_fade_in);
setAnimationIn(_in);
int _out = array.getResourceId(R.styleable.LoadingImage_animationOut,
R.anim.abc_fade_out);
}
}
private void setAnimationIn(int resId) {
this.animationIn = getAnimation(resId);
}
private Animation getAnimation(int resId) {
return resId > 0 ? AnimationUtils.loadAnimation(getContext(), resId) : null;
}
public void loadFrom(String url) {
loadFrom(url, null);
}
public void loadFrom(String url, String fallbackUrl) {
this.failbackAddress = fallbackUrl;
this.addresToLoad = !TextUtils.isEmpty(url) ? url : fallbackUrl;
if (!isSameUrl(addresToLoad)) {
rLoadUrl(addresToLoad);
}
}
private void rLoadUrl(String url) {
if (ImageLoader.getInstance().isInited()) {
ImageLoader.getInstance().loadImage(url, this);
}
}
private boolean isSameUrl(String url) {
String _tagUrl = (String) getTag(R.id.___tag_url);
return _tagUrl != null ? _tagUrl.equals(url) : false;
}
@Override
public void onLoadingStarted(String imageUri, View view) {
showProgressBar();
}
private void showProgressBar() {
if (showProgress) {
progress.setVisibility(VISIBLE);
}
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
if (failbackAddress != null) {
rLoadUrl(failbackAddress);
}
hideProgressbar();
}
private void hideProgressbar() {
if (showProgress) {
progress.setVisibility(GONE);
}
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
hideProgressbar();
setTag(R.id.___tag_url, imageUri);
loadBitmap(loadedImage);
}
private void loadBitmap(Bitmap loadedImage) {
if (useAnimations && animationIn != null) {
image.startAnimation(animationIn);
}
image.setImageBitmap(loadedImage);
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
hideProgressbar();
image.setImageResource(noImageRes);
}
}
|
package com.dianping.cat.report.page.home;
import org.unidal.web.mvc.ActionContext;
import org.unidal.web.mvc.payload.annotation.FieldMeta;
import com.dianping.cat.mvc.AbstractReportPayload;
import com.dianping.cat.report.ReportPage;
public class Payload extends AbstractReportPayload<Action,ReportPage> {
@FieldMeta("op")
private Action m_action;
@FieldMeta("docName")
private String m_docName = "user";
@FieldMeta("subDocName")
private String m_subDocName;
public Payload() {
super(ReportPage.HOME);
}
@Override
public Action getAction() {
return m_action;
}
public String getDocName() {
return m_docName;
}
public String getSubDocName() {
return m_subDocName;
}
public void setAction(String action) {
m_action = Action.getByName(action, Action.VIEW);
}
public void setDocName(String docName) {
m_docName = docName;
}
@Override
public void setPage(String page) {
m_page = ReportPage.getByName(page, ReportPage.HOME);
}
public void setSubDocName(String subDocName) {
m_subDocName = subDocName;
}
@Override
public void validate(ActionContext<?> ctx) {
if (m_action == null) {
m_action = Action.VIEW;
}
}
}
|
package ru.agolovin;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
public class MaxTriangleSideTest {
@Test
public void whenMaxTriangleSideExistThenResult() {
Point point1 = new Point(3, 5);
Point point2 = new Point(6, 1);
Point point3 = new Point(3, 1);
Triangle tr = new Triangle(point1, point2, point3);
tr.sideLength();
double result = MaxTriangleSide.maxSide(tr.ab, tr.ac, tr.bc);
assertThat(result, is(5.0));
}
}
|
package it.innove;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.support.annotation.Nullable;
import android.util.Log;
import com.facebook.react.bridge.*;
import com.facebook.react.modules.core.RCTNativeAppEventEmitter;
import java.lang.reflect.Method;
import java.util.*;
import static android.app.Activity.RESULT_OK;
import static android.bluetooth.BluetoothProfile.GATT;
import static android.os.Build.VERSION_CODES.LOLLIPOP;
import static com.facebook.react.bridge.UiThreadUtil.runOnUiThread;
class BleManager extends ReactContextBaseJavaModule implements ActivityEventListener {
public static final String LOG_TAG = "ReactNativeBleManager";
private static final int ENABLE_REQUEST = 539;
private class BondRequest {
private String uuid;
private Callback callback;
BondRequest(String _uuid, Callback _callback) {
uuid = _uuid;
callback = _callback;
}
}
private BluetoothAdapter bluetoothAdapter;
private BluetoothManager bluetoothManager;
private Context context;
private ReactApplicationContext reactContext;
private Callback enableBluetoothCallback;
private ScanManager scanManager;
private BondRequest bondRequest;
private BondRequest removeBondRequest;
// key is the MAC Address
public Map<String, Peripheral> peripherals = new LinkedHashMap<>();
// scan session id
public BleManager(ReactApplicationContext reactContext) {
super(reactContext);
context = reactContext;
this.reactContext = reactContext;
reactContext.addActivityEventListener(this);
Log.d(LOG_TAG, "BleManager created");
}
@Override
public String getName() {
return "BleManager";
}
private BluetoothAdapter getBluetoothAdapter() {
if (bluetoothAdapter == null) {
BluetoothManager manager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = manager.getAdapter();
}
return bluetoothAdapter;
}
private BluetoothManager getBluetoothManager() {
if (bluetoothManager == null) {
bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
}
return bluetoothManager;
}
public void sendEvent(String eventName,
@Nullable WritableMap params) {
getReactApplicationContext()
.getJSModule(RCTNativeAppEventEmitter.class)
.emit(eventName, params);
}
@ReactMethod
public void start(ReadableMap options, Callback callback) {
Log.d(LOG_TAG, "start");
if (getBluetoothAdapter() == null) {
Log.d(LOG_TAG, "No bluetooth support");
callback.invoke("No bluetooth support");
return;
}
boolean forceLegacy = false;
if (options.hasKey("forceLegacy")) {
forceLegacy = options.getBoolean("forceLegacy");
}
if (Build.VERSION.SDK_INT >= LOLLIPOP && !forceLegacy) {
scanManager = new LollipopScanManager(reactContext, this);
} else {
scanManager = new LegacyScanManager(reactContext, this);
}
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
context.registerReceiver(mReceiver, filter);
callback.invoke();
Log.d(LOG_TAG, "BleManager initialized");
}
@ReactMethod
public void enableBluetooth(Callback callback) {
if (getBluetoothAdapter() == null) {
Log.d(LOG_TAG, "No bluetooth support");
callback.invoke("No bluetooth support");
return;
}
if (!getBluetoothAdapter().isEnabled()) {
enableBluetoothCallback = callback;
Intent intentEnable = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
if (getCurrentActivity() == null)
callback.invoke("Current activity not available");
else
getCurrentActivity().startActivityForResult(intentEnable, ENABLE_REQUEST);
} else
callback.invoke();
}
@ReactMethod
public void scan(ReadableArray serviceUUIDs, final int scanSeconds, boolean allowDuplicates, ReadableMap options, Callback callback) {
Log.d(LOG_TAG, "scan");
if (getBluetoothAdapter() == null) {
Log.d(LOG_TAG, "No bluetooth support");
callback.invoke("No bluetooth support");
return;
}
if (!getBluetoothAdapter().isEnabled()) {
return;
}
for (Iterator<Map.Entry<String, Peripheral>> iterator = peripherals.entrySet().iterator(); iterator.hasNext(); ) {
Map.Entry<String, Peripheral> entry = iterator.next();
if (!entry.getValue().isConnected()) {
iterator.remove();
}
}
if(scanManager!=null) scanManager.scan(serviceUUIDs, scanSeconds, options, callback);
}
@ReactMethod
public void stopScan(Callback callback) {
Log.d(LOG_TAG, "Stop scan");
if (getBluetoothAdapter() == null) {
Log.d(LOG_TAG, "No bluetooth support");
callback.invoke("No bluetooth support");
return;
}
if (!getBluetoothAdapter().isEnabled()) {
callback.invoke();
return;
}
if(scanManager!=null) scanManager.stopScan(callback);
}
@ReactMethod
public void createBond(String peripheralUUID, Callback callback) {
Log.d(LOG_TAG, "Request bond to: " + peripheralUUID);
Set<BluetoothDevice> deviceSet = getBluetoothAdapter().getBondedDevices();
for (BluetoothDevice device : deviceSet) {
if (peripheralUUID.equalsIgnoreCase(device.getAddress())) {
callback.invoke();
return;
}
}
Peripheral peripheral = retrieveOrCreatePeripheral(peripheralUUID);
if (peripheral == null) {
callback.invoke("Invalid peripheral uuid");
} else if (bondRequest != null) {
callback.invoke("Only allow one bond request at a time");
} else if (peripheral.getDevice().createBond()) {
bondRequest = new BondRequest(peripheralUUID, callback); // request bond success, waiting for boradcast
return;
}
callback.invoke("Create bond request fail");
}
@ReactMethod
private void removeBond(String peripheralUUID, Callback callback) {
Log.d(LOG_TAG, "Remove bond to: " + peripheralUUID);
Peripheral peripheral = retrieveOrCreatePeripheral(peripheralUUID);
if (peripheral == null) {
callback.invoke("Invalid peripheral uuid");
return;
} else {
try {
Method m = peripheral.getDevice().getClass().getMethod("removeBond", (Class[]) null);
m.invoke(peripheral.getDevice(), (Object[]) null);
removeBondRequest = new BondRequest(peripheralUUID, callback);
return;
} catch (Exception e) {
Log.d(LOG_TAG, "Error in remove bond: " + peripheralUUID, e);
callback.invoke("Remove bond request fail");
}
}
}
@ReactMethod
public void connect(String peripheralUUID, Callback callback) {
Log.d(LOG_TAG, "Connect to: " + peripheralUUID);
Peripheral peripheral = retrieveOrCreatePeripheral(peripheralUUID);
if (peripheral == null) {
callback.invoke("Invalid peripheral uuid");
return;
}
peripheral.connect(callback, getCurrentActivity());
}
@ReactMethod
public void disconnect(String peripheralUUID, Callback callback) {
Log.d(LOG_TAG, "Disconnect from: " + peripheralUUID);
Peripheral peripheral = peripherals.get(peripheralUUID);
if (peripheral != null) {
peripheral.disconnect();
callback.invoke();
} else
callback.invoke("Peripheral not found");
}
@ReactMethod
public void startNotification(String deviceUUID, String serviceUUID, String characteristicUUID, Callback callback) {
Log.d(LOG_TAG, "startNotification");
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null) {
peripheral.registerNotify(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), callback);
} else
callback.invoke("Peripheral not found");
}
@ReactMethod
public void stopNotification(String deviceUUID, String serviceUUID, String characteristicUUID, Callback callback) {
Log.d(LOG_TAG, "stopNotification");
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null) {
peripheral.removeNotify(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), callback);
} else
callback.invoke("Peripheral not found");
}
@ReactMethod
public void write(String deviceUUID, String serviceUUID, String characteristicUUID, ReadableArray message, Integer maxByteSize, Callback callback) {
Log.d(LOG_TAG, "Write to: " + deviceUUID);
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null) {
byte[] decoded = new byte[message.size()];
for (int i = 0; i < message.size(); i++) {
decoded[i] = new Integer(message.getInt(i)).byteValue();
}
Log.d(LOG_TAG, "Message(" + decoded.length + "): " + bytesToHex(decoded));
peripheral.write(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), decoded, maxByteSize, null, callback, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
} else
callback.invoke("Peripheral not found");
}
@ReactMethod
public void writeWithoutResponse(String deviceUUID, String serviceUUID, String characteristicUUID, ReadableArray message, Integer maxByteSize, Integer queueSleepTime, Callback callback) {
Log.d(LOG_TAG, "Write without response to: " + deviceUUID);
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null) {
byte[] decoded = new byte[message.size()];
for (int i = 0; i < message.size(); i++) {
decoded[i] = new Integer(message.getInt(i)).byteValue();
}
Log.d(LOG_TAG, "Message(" + decoded.length + "): " + bytesToHex(decoded));
peripheral.write(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), decoded, maxByteSize, queueSleepTime, callback, BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
} else
callback.invoke("Peripheral not found");
}
@ReactMethod
public void read(String deviceUUID, String serviceUUID, String characteristicUUID, Callback callback) {
Log.d(LOG_TAG, "Read from: " + deviceUUID);
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null) {
peripheral.read(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), callback);
} else
callback.invoke("Peripheral not found", null);
}
@ReactMethod
public void retrieveServices(String deviceUUID, ReadableArray services, Callback callback) {
Log.d(LOG_TAG, "Retrieve services from: " + deviceUUID);
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null) {
peripheral.retrieveServices(callback);
} else
callback.invoke("Peripheral not found", null);
}
@ReactMethod
public void refreshCache(String deviceUUID, Callback callback) {
Log.d(LOG_TAG, "Refershing cache for: " + deviceUUID);
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null) {
peripheral.refreshCache(callback);
} else
callback.invoke("Peripheral not found");
}
@ReactMethod
public void readRSSI(String deviceUUID, Callback callback) {
Log.d(LOG_TAG, "Read RSSI from: " + deviceUUID);
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null) {
peripheral.readRSSI(callback);
} else
callback.invoke("Peripheral not found", null);
}
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi,
final byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i(LOG_TAG, "DiscoverPeripheral: " + device.getName());
String address = device.getAddress();
if (!peripherals.containsKey(address)) {
Peripheral peripheral = new Peripheral(device, rssi, scanRecord, reactContext);
peripherals.put(device.getAddress(), peripheral);
WritableMap map = peripheral.asWritableMap();
sendEvent("BleManagerDiscoverPeripheral", map);
} else {
// this isn't necessary
Peripheral peripheral = peripherals.get(address);
peripheral.updateRssi(rssi);
}
}
});
}
};
@ReactMethod
public void checkState() {
Log.d(LOG_TAG, "checkState");
BluetoothAdapter adapter = getBluetoothAdapter();
String state = "off";
if (adapter != null) {
switch (adapter.getState()) {
case BluetoothAdapter.STATE_ON:
state = "on";
break;
case BluetoothAdapter.STATE_OFF:
state = "off";
}
}
WritableMap map = Arguments.createMap();
map.putString("state", state);
Log.d(LOG_TAG, "state:" + state);
sendEvent("BleManagerDidUpdateState", map);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(LOG_TAG, "onReceive");
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
String stringState = "";
switch (state) {
case BluetoothAdapter.STATE_OFF:
stringState = "off";
break;
case BluetoothAdapter.STATE_TURNING_OFF:
stringState = "turning_off";
break;
case BluetoothAdapter.STATE_ON:
stringState = "on";
break;
case BluetoothAdapter.STATE_TURNING_ON:
stringState = "turning_on";
break;
}
WritableMap map = Arguments.createMap();
map.putString("state", stringState);
Log.d(LOG_TAG, "state: " + stringState);
sendEvent("BleManagerDidUpdateState", map);
} else if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
final int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String bondStateStr = "UNKNOWN";
switch (bondState) {
case BluetoothDevice.BOND_BONDED:
bondStateStr = "BOND_BONDED";
break;
case BluetoothDevice.BOND_BONDING:
bondStateStr = "BOND_BONDING";
break;
case BluetoothDevice.BOND_NONE:
bondStateStr = "BOND_NONE";
break;
}
Log.d(LOG_TAG, "bond state: " + bondStateStr);
if (bondRequest != null && bondRequest.uuid.equals(device.getAddress())) {
if (bondState == BluetoothDevice.BOND_BONDED) {
bondRequest.callback.invoke();
bondRequest = null;
} else if (bondState == BluetoothDevice.BOND_NONE || bondState == BluetoothDevice.ERROR) {
bondRequest.callback.invoke("Bond request has been denied");
bondRequest = null;
}
}
if (removeBondRequest != null && removeBondRequest.uuid.equals(device.getAddress()) && bondState == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
removeBondRequest.callback.invoke();
removeBondRequest = null;
}
}
}
};
@ReactMethod
public void getDiscoveredPeripherals(Callback callback) {
Log.d(LOG_TAG, "Get discovered peripherals");
WritableArray map = Arguments.createArray();
Map<String, Peripheral> peripheralsCopy = new LinkedHashMap<>(peripherals);
for (Map.Entry<String, Peripheral> entry : peripheralsCopy.entrySet()) {
Peripheral peripheral = entry.getValue();
WritableMap jsonBundle = peripheral.asWritableMap();
map.pushMap(jsonBundle);
}
callback.invoke(null, map);
}
@ReactMethod
public void getConnectedPeripherals(ReadableArray serviceUUIDs, Callback callback) {
Log.d(LOG_TAG, "Get connected peripherals");
WritableArray map = Arguments.createArray();
List<BluetoothDevice> periperals = getBluetoothManager().getConnectedDevices(GATT);
for (BluetoothDevice entry : periperals) {
Peripheral peripheral = new Peripheral(entry, reactContext);
WritableMap jsonBundle = peripheral.asWritableMap();
map.pushMap(jsonBundle);
}
callback.invoke(null, map);
}
@ReactMethod
public void getBondedPeripherals(Callback callback) {
Log.d(LOG_TAG, "Get bonded peripherals");
WritableArray map = Arguments.createArray();
Set<BluetoothDevice> deviceSet = getBluetoothAdapter().getBondedDevices();
for (BluetoothDevice device : deviceSet) {
Peripheral peripheral = new Peripheral(device, reactContext);
WritableMap jsonBundle = peripheral.asWritableMap();
map.pushMap(jsonBundle);
}
callback.invoke(null, map);
}
@ReactMethod
public void removePeripheral(String deviceUUID, Callback callback) {
Log.d(LOG_TAG, "Removing from list: " + deviceUUID);
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null) {
if (peripheral.isConnected()) {
callback.invoke("Peripheral can not be removed while connected");
} else {
peripherals.remove(deviceUUID);
callback.invoke();
}
} else
callback.invoke("Peripheral not found");
}
@ReactMethod
public void requestConnectionPriority(String deviceUUID, int connectionPriority, Callback callback) {
Log.d(LOG_TAG, "Request connection priority of " + connectionPriority + " from: " + deviceUUID);
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null) {
peripheral.requestConnectionPriority(connectionPriority, callback);
} else {
callback.invoke("Peripheral not found", null);
}
}
@ReactMethod
public void requestMTU(String deviceUUID, int mtu, Callback callback) {
Log.d(LOG_TAG, "Request MTU of " + mtu + " bytes from: " + deviceUUID);
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null) {
peripheral.requestMTU(mtu, callback);
} else {
callback.invoke("Peripheral not found", null);
}
}
private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public static WritableArray bytesToWritableArray(byte[] bytes) {
WritableArray value = Arguments.createArray();
for (int i = 0; i < bytes.length; i++)
value.pushInt((bytes[i] & 0xFF));
return value;
}
@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
Log.d(LOG_TAG, "onActivityResult");
if (requestCode == ENABLE_REQUEST && enableBluetoothCallback != null) {
if (resultCode == RESULT_OK) {
enableBluetoothCallback.invoke();
} else {
enableBluetoothCallback.invoke("User refused to enable");
}
enableBluetoothCallback = null;
}
}
@Override
public void onNewIntent(Intent intent) {
}
private Peripheral retrieveOrCreatePeripheral(String peripheralUUID) {
Peripheral peripheral = peripherals.get(peripheralUUID);
if (peripheral == null) {
if (peripheralUUID != null) {
peripheralUUID = peripheralUUID.toUpperCase();
}
if (BluetoothAdapter.checkBluetoothAddress(peripheralUUID)) {
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(peripheralUUID);
peripheral = new Peripheral(device, reactContext);
peripherals.put(peripheralUUID, peripheral);
}
}
return peripheral;
}
}
|
package com.enigmabridge.provider.rsa;
import com.enigmabridge.*;
import com.enigmabridge.create.Constants;
import com.enigmabridge.create.EBCreateUOResponse;
import com.enigmabridge.create.EBCreateUtils;
import com.enigmabridge.create.misc.EBRSAPrivateCrtKey;
import com.enigmabridge.create.misc.EBRSAPrivateCrtKeyWrapper;
import com.enigmabridge.provider.EBSymmetricKey;
import com.enigmabridge.provider.EnigmaProvider;
import com.enigmabridge.provider.asn1.EBASNUtils;
import com.enigmabridge.provider.asn1.EBEncodableUOKey;
import com.enigmabridge.provider.asn1.EBJSONEncodedUOKey;
import com.enigmabridge.provider.specs.EBKeyCreateSpec;
import com.enigmabridge.provider.specs.EBRSAKeyCreateSpec;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.pkcs.RSAPrivateKey;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.jcajce.provider.asymmetric.util.BaseKeyFactorySpi;
import org.bouncycastle.jcajce.provider.asymmetric.util.ExtendedInvalidKeySpecException;
import java.io.IOException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.security.*;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.*;
public class KeyFactorySpi
extends BaseKeyFactorySpi
{
protected final EnigmaProvider provider;
protected EBEngine engine;
protected SecureRandom random;
protected final UserObjectKeyCreator.Builder keyCreatorBld = new UserObjectKeyCreator.Builder();
protected UserObjectKeyCreator keyCreator;
public KeyFactorySpi(EnigmaProvider provider)
{
this.provider = provider;
}
/**
* KeySpec extraction is supported only from local types.
* PublicKey spec is supported for EB types.
* RSAPrivateKeySpec for EBRSAKey throws InvalidKeySpecException
*
* @param key key to process
* @param spec specs class to produce
* @return spec
* @throws InvalidKeySpecException
*/
protected KeySpec engineGetKeySpec(
Key key,
Class spec)
throws InvalidKeySpecException
{
if (spec.isAssignableFrom(RSAPrivateKeySpec.class) && key instanceof EBRSAKey)
{
throw new InvalidKeySpecException("EBRSAPrivate key is not extractable");
}
else if (spec.isAssignableFrom(RSAPublicKeySpec.class) && key instanceof EBRSAKey)
{
final EBRSAKey k = (EBRSAKey) key;
return new RSAPublicKeySpec(k.getModulus(), k.getPublicExponent());
}
else if (spec.isAssignableFrom(RSAPublicKeySpec.class) && key instanceof RSAPublicKey)
{
RSAPublicKey k = (RSAPublicKey)key;
return new RSAPublicKeySpec(k.getModulus(), k.getPublicExponent());
}
else if (spec.isAssignableFrom(RSAPrivateKeySpec.class) && key instanceof java.security.interfaces.RSAPrivateKey)
{
java.security.interfaces.RSAPrivateKey k = (java.security.interfaces.RSAPrivateKey)key;
return new RSAPrivateKeySpec(k.getModulus(), k.getPrivateExponent());
}
else if (spec.isAssignableFrom(RSAPrivateCrtKeySpec.class) && key instanceof RSAPrivateCrtKey)
{
RSAPrivateCrtKey k = (RSAPrivateCrtKey)key;
return new RSAPrivateCrtKeySpec(
k.getModulus(), k.getPublicExponent(),
k.getPrivateExponent(),
k.getPrimeP(), k.getPrimeQ(),
k.getPrimeExponentP(), k.getPrimeExponentQ(),
k.getCrtCoefficient());
}
return super.engineGetKeySpec(key, spec);
}
/**
* Key translation is not yet implemented.
*
* @param key key to translate
* @return translated key
* @throws InvalidKeyException
*/
protected Key engineTranslateKey(
Key key)
throws InvalidKeyException
{
// For EB key - just change engine.
try {
if (key instanceof EBRSAKey)
{
final EBRSAKey k = (EBRSAKey) key;
final UserObjectKeyBase keyBase = new UserObjectKeyBase.Builder()
.setUserObjectKeyCopy(k.getUserObjectKey())
.build();
final EBRSAKey.AbstractBuilder kBld = key instanceof EBRSAPublicKey ?
new EBRSAPublicKey.Builder() :
new EBRSAPrivateKey.Builder();
return kBld
.setModulus(k.getModulus())
.setPublicExponent(k.getPublicExponent())
.setEngine(provider.getEngine())
.setUo(keyBase)
.setOperationConfig(k.getOperationConfiguration() == null ? null : k.getOperationConfiguration().copy())
.build();
}
// For keyspec?
else if (key instanceof RSAPrivateCrtKey){
return engineGeneratePrivate(new EBRSAPrivateCrtKeyWrapper((RSAPrivateCrtKey)key));
}
else if (key instanceof RSAPrivateCrtKeySpec){
return engineGeneratePrivate(new EBRSAPrivateCrtKeyWrapper((RSAPrivateCrtKeySpec)key));
}
else if (key instanceof RSAPrivateKey) {
return engineGeneratePrivate(new EBRSAPrivateCrtKeyWrapper((RSAPrivateKey)key));
}
else if ("PKCS#8".equalsIgnoreCase(key.getFormat())){
try {
return generatePrivate(PrivateKeyInfo.getInstance(key.getEncoded()), null);
} catch(Exception e){
// Try last thing - convert to specs.
}
}
// Specs?
try {
final KeyFactory kFactBc = KeyFactory.getInstance("RSA", "BC");
// At first extract CRT key specs from the locally generated private key
final RSAPrivateCrtKeySpec keySpec = kFactBc.getKeySpec(key, RSAPrivateCrtKeySpec.class);
return engineGeneratePrivate(new EBRSAPrivateCrtKeyWrapper(keySpec));
} catch(Exception e){
// Cannot be converted
throw new InvalidKeyException("key type unknown", e);
}
} catch (MalformedURLException e) {
throw new InvalidKeyException("Cannot translate the key", e);
} catch (IOException e) {
throw new InvalidKeyException("Cannot translate the key", e);
} catch (InvalidKeySpecException e) {
throw new InvalidKeyException("Cannot translate the key", e);
}
}
/**
* Worker method creating RSA private key from the wrapper.
*
* @param wrapper RSA private key wrapper
* @return PrivateKey EB handle
* @throws InvalidKeySpecException
*/
protected PrivateKey engineGeneratePrivate(
EBRSAPrivateCrtKeyWrapper wrapper)
throws InvalidKeySpecException
{
final int uoFunction = UserObjectType.getRSADecryptFunctionFromModulus(wrapper.getModulus());
if (engine == null){
engine = provider.getEngine();
}
keyCreatorBld.setEngine(this.engine)
.setRandom(this.random)
.setUoType(new UserObjectType(uoFunction,
Constants.GENKEY_CLIENT,
Constants.GENKEY_CLIENT
));
keyCreator = keyCreatorBld.build();
keyCreator
.setAppKey(wrapper)
.setUoTypeFunction(uoFunction)
.setAppKeyGeneration(Constants.GENKEY_CLIENT);
try {
final UserObjectKeyBase.Builder keyBld = keyCreator.create();
// Create Java RSA key - will be done with key specs.
final EBRSAPrivateKey rsa2kPrivKey = new EBRSAPrivateKey.Builder()
.setPublicExponent(wrapper.getPublicExponent())
.setModulus(wrapper.getModulus())
.setUo(keyBld.build())
.setEngine(engine)
.build();
return rsa2kPrivKey;
} catch (IOException e) {
throw new ProviderException("Create RSA key failed", e);
}
}
protected void initFromSpec(EBKeyCreateSpec ebSpec)
{
if (ebSpec != null && ebSpec.getEBEngine() != null){
this.engine = ebSpec.getEBEngine();
}
if (this.engine == null){
this.engine = provider.getEngine();
}
if (this.random == null && this.engine != null){
this.random = this.engine.getRnd();
}
if (this.random == null){
this.random = new SecureRandom();
}
if (ebSpec != null && ebSpec.getTemplateRequest() != null){
keyCreatorBld.setGetTemplateRequest(ebSpec.getTemplateRequest());
}
}
protected PrivateKey engineGeneratePrivate(
KeySpec keySpec)
throws InvalidKeySpecException
{
BigInteger publicExponent = null;
// For non-crt key public modulus is needed.
if (keySpec instanceof EBRSAKeyCreateSpec)
{
publicExponent = ((EBRSAKeyCreateSpec) keySpec).getPublicExponent();
}
// If our specs are passed, initialize from it.
if (keySpec instanceof EBKeyCreateSpec)
{
final EBKeyCreateSpec createSpec = (EBKeyCreateSpec) keySpec;
initFromSpec(createSpec);
keySpec = createSpec.getUnderlyingSpec();
}
else
{
initFromSpec(null);
}
if (keySpec instanceof PKCS8EncodedKeySpec)
{
return engineGeneratePrivate((PKCS8EncodedKeySpec)keySpec, publicExponent);
}
else if (keySpec instanceof RSAPrivateCrtKeySpec)
{
return engineGeneratePrivate(new EBRSAPrivateCrtKeyWrapper((RSAPrivateCrtKeySpec)keySpec));
}
else if (keySpec instanceof RSAPrivateKeySpec)
{
if (publicExponent != null)
{
return engineGeneratePrivate(new EBRSAPrivateCrtKeyWrapper(new EBRSAPrivateCrtKey((RSAPrivateKeySpec)keySpec, publicExponent)));
}
else
{
throw new InvalidKeySpecException("Cannot accept KeySpec type: " + keySpec.getClass().getName() + ", public modulus is missing");
}
}
throw new InvalidKeySpecException("Unknown KeySpec type: " + keySpec.getClass().getName());
}
protected PrivateKey engineGeneratePrivate(PKCS8EncodedKeySpec p8, BigInteger publicExponent) throws InvalidKeySpecException {
try {
final EBEncodableUOKey keyInfo = EBEncodableUOKey.getInstance(p8.getEncoded());
final ASN1ObjectIdentifier algOid = keyInfo.getPrivateKeyAlgorithm().getAlgorithm();
// Try EB wrapped
try {
if (EBASNUtils.eb_rsa_priv.equals(algOid)) {
final EBJSONEncodedUOKey encKey = EBJSONEncodedUOKey.getInstance(keyInfo.parsePrivateKey());
return new EBRSAPrivateKey.Builder()
.setEngine(engine)
.setAsn(encKey)
.build();
} else if (EBASNUtils.eb_rsa_pub.equals(algOid)){
throw new InvalidKeySpecException("public key serialization is not supported");
}
} catch (IOException io2){
throw new InvalidKeySpecException("IOException when parsing key from PKCS8 encoded form", io2);
}
// Try classical one.
try
{
return generatePrivate(PrivateKeyInfo.getInstance(p8.getEncoded()), publicExponent);
}
catch (Exception e)
{
// in case it's just a RSAPrivateKey object... -- openSSL produces these
try
{
return engineGeneratePrivate(new EBRSAPrivateCrtKeyWrapper(
RSAPrivateKey.getInstance(p8.getEncoded())));
}
catch (Exception ex)
{
throw new ExtendedInvalidKeySpecException("unable to process key spec: " + e.toString(), e);
}
}
}catch (Exception io){
throw new InvalidKeySpecException("IOException when parsing key from PKCS8 encoded form", io);
}
}
protected PublicKey engineGeneratePublic(
KeySpec keySpec)
throws InvalidKeySpecException
{
// Build public key using BC.
try {
final KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
return kf.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
return super.engineGeneratePublic(keySpec);
} catch (NoSuchProviderException e) {
return super.engineGeneratePublic(keySpec);
}
}
public PrivateKey generatePrivate(PrivateKeyInfo keyInfo)
throws IOException
{
return generatePrivate(keyInfo, null);
}
public PrivateKey generatePrivate(PrivateKeyInfo keyInfo, BigInteger publicExponent)
throws IOException
{
ASN1ObjectIdentifier algOid = keyInfo.getPrivateKeyAlgorithm().getAlgorithm();
if (org.bouncycastle.jcajce.provider.asymmetric.rsa.RSAUtil.isRsaOid(algOid))
{
RSAPrivateKey rsaPrivKey = RSAPrivateKey.getInstance(keyInfo.parsePrivateKey());
if (rsaPrivKey.getCoefficient().intValue() != 0)
{
try
{
return engineGeneratePrivate(new EBRSAPrivateCrtKeyWrapper(rsaPrivKey));
}
catch (InvalidKeySpecException e)
{
throw new IOException("Conversion exception", e);
}
}
else if (rsaPrivKey.getPublicExponent().intValue() != 0 || publicExponent != null)
{
try
{
return engineGeneratePrivate(new EBRSAPrivateCrtKeyWrapper(new EBRSAPrivateCrtKey(
publicExponent != null ? publicExponent : rsaPrivKey.getPublicExponent(),
rsaPrivKey.getPrivateExponent(),
rsaPrivKey.getModulus()
)));
}
catch (InvalidKeySpecException e)
{
throw new IOException("Conversion exception", e);
}
}
else
{
throw new IOException("Cannot convert non-CRT private key without public modulus");
}
}
else
{
throw new IOException("algorithm identifier " + algOid + " in key not recognised");
}
}
public PublicKey generatePublic(SubjectPublicKeyInfo keyInfo)
throws IOException
{
throw new IOException("algorithm identifier " + keyInfo.getAlgorithm() + " in key not recognised");
}
}
|
package com.intellij.codeInsight.lookup.impl;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.completion.CompletionBundle;
import com.intellij.codeInsight.completion.CompletionPreferencePolicy;
import com.intellij.codeInsight.completion.CompletionUtil;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.lookup.*;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.ide.IdeEventQueue;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.event.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiProximityComparator;
import com.intellij.ui.LightweightHint;
import com.intellij.ui.ListScrollingUtil;
import com.intellij.ui.plaf.beg.BegPopupMenuBorder;
import com.intellij.util.SmartList;
import gnu.trove.THashSet;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.Perl5Matcher;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import java.util.List;
public class LookupImpl extends LightweightHint implements Lookup {
private static final int MAX_PREFERRED_COUNT = 7;
static final Object EMPTY_ITEM_ATTRIBUTE = Key.create("emptyItem");
static final Object ALL_METHODS_ATTRIBUTE = Key.create("allMethods");
public static final Key<LookupImpl> LOOKUP_IN_EDITOR_KEY = Key.create("LOOKUP_IN_EDITOR_KEY");
private final Project myProject;
private final Editor myEditor;
private final LookupItem[] myItems;
private final SortedMap<LookupItemWeightComparable, SortedSet<LookupItem>> myItemsMap;
private String myPrefix;
private int myPreferredItemsCount;
private final LookupItemPreferencePolicy myItemPreferencePolicy;
private final CharFilter myCharFilter;
private RangeMarker myLookupStartMarker;
private String myInitialPrefix;
private JList myList;
private LookupCellRenderer myCellRenderer;
private Boolean myPositionedAbove = null;
private CaretListener myEditorCaretListener;
private EditorMouseListener myEditorMouseListener;
private DocumentListener myDocumentListener;
private ArrayList<LookupListener> myListeners = new ArrayList<LookupListener>();
private boolean myCanceled = true;
private boolean myDisposed = false;
private int myIndex;
public LookupImpl(Project project,
Editor editor,
LookupItem[] items,
String prefix,
LookupItemPreferencePolicy itemPreferencePolicy,
CharFilter filter){
super(new JPanel(new BorderLayout()));
myProject = project;
myEditor = editor;
myItems = items;
myPrefix = prefix;
myItemPreferencePolicy = itemPreferencePolicy;
myCharFilter = filter;
myEditor.putUserData(LOOKUP_IN_EDITOR_KEY, this);
if (myPrefix == null){
myPrefix = "";
}
myInitialPrefix = myPrefix;
myList = new JList() ;
myList.setFocusable(false);
myCellRenderer = new LookupCellRenderer(this);
myList.setCellRenderer(myCellRenderer);
myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
myItemsMap = initWeightMap(itemPreferencePolicy);
updateList();
myList.setBackground(LookupCellRenderer.BACKGROUND_COLOR);
JScrollPane scrollPane = new JScrollPane(myList);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setBorder(new BegPopupMenuBorder());
getComponent().add(scrollPane, BorderLayout.CENTER);
myEditorCaretListener = new CaretListener() {
public void caretPositionChanged(CaretEvent e){
int curOffset = myEditor.getCaretModel().getOffset();
if (curOffset != getLookupStart() + myPrefix.length()){
hide();
}
}
};
myEditor.getCaretModel().addCaretListener(myEditorCaretListener);
myEditorMouseListener = new EditorMouseAdapter() {
public void mouseClicked(EditorMouseEvent e){
e.consume();
hide();
}
};
myEditor.addEditorMouseListener(myEditorMouseListener);
myDocumentListener = new DocumentAdapter() {
public void documentChanged(DocumentEvent e) {
if (!myLookupStartMarker.isValid()){
hide();
}
}
};
myEditor.getDocument().addDocumentListener(myDocumentListener);
myList.addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e){
LookupItem item = (LookupItem)myList.getSelectedValue();
if (item != null && item.getAttribute(EMPTY_ITEM_ATTRIBUTE) != null){
item = null;
}
fireCurrentItemChanged(item);
}
}
);
myList.addMouseListener(
new MouseAdapter() {
public void mouseClicked(MouseEvent e){
if (e.getClickCount() == 2){
CommandProcessor.getInstance().executeCommand(
myProject, new Runnable() {
public void run() {
finishLookup(NORMAL_SELECT_CHAR);
}
},
"",
null
);
}
}
}
);
selectMostPreferableItem();
final Application application = ApplicationManager.getApplication();
if (!application.isUnitTestMode()) {
application.invokeLater(
new Runnable() {
public void run(){
if (myIndex >= 0 && myIndex < myList.getModel().getSize()){
ListScrollingUtil.selectItem(myList, myIndex);
}
else if(myItems.length > 0){
ListScrollingUtil.selectItem(myList, 0);
}
}
}
);
}
}
public int getPreferredItemsCount() {
return myPreferredItemsCount;
}
private SortedMap<LookupItemWeightComparable, SortedSet<LookupItem>> initWeightMap(final LookupItemPreferencePolicy itemPreferencePolicy) {
final SortedMap<LookupItemWeightComparable, SortedSet<LookupItem>> map = new TreeMap<LookupItemWeightComparable, SortedSet<LookupItem>>();
if (LookupManagerImpl.isUseNewSorting()) {
final Document document = myEditor.getDocument();
final PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(document);
final PsiElement element = psiFile.findElementAt(myEditor.getCaretModel().getOffset());
final PsiProximityComparator proximityComparator = new PsiProximityComparator(element, myProject);
for (final LookupItem item : myItems) {
final int[] weight = itemPreferencePolicy instanceof CompletionPreferencePolicy
? ((CompletionPreferencePolicy)itemPreferencePolicy).getWeight(item)
: new int[]{item.getObject() instanceof PsiElement ? proximityComparator.getProximity((PsiElement)item.getObject()) : 0};
final LookupItemWeightComparable key = new LookupItemWeightComparable(item.getPriority(), weight);
SortedSet<LookupItem> sortedSet = map.get(key);
if (sortedSet == null) map.put(key, sortedSet = new TreeSet<LookupItem>());
sortedSet.add(item);
}
}
return map;
}
Project getProject(){
return myProject;
}
String getPrefix(){
return myPrefix;
}
void setPrefix(String prefix){
myPrefix = prefix;
}
String getInitialPrefix(){
return myInitialPrefix;
}
public JList getList(){
return myList;
}
public LookupItem[] getItems(){
return myItems;
}
private boolean suits(LookupItem<?> item, PatternMatcher matcher, Pattern pattern) {
for (final String text : item.getAllLookupStrings()) {
if (StringUtil.startsWithIgnoreCase(text, myPrefix) || matcher.matches(text, pattern)) {
return true;
}
}
return false;
}
void updateList(){
final PatternMatcher matcher = new Perl5Matcher();
final Pattern pattern = CompletionUtil.createCamelHumpsMatcher(myPrefix);
Object oldSelected = myList.getSelectedValue();
DefaultListModel model = new DefaultListModel();
ArrayList<LookupItem> array = new ArrayList<LookupItem>();
Set<LookupItem> first = new THashSet<LookupItem>();
for (final LookupItemWeightComparable comparable : myItemsMap.keySet()) {
final SortedSet<LookupItem> items = myItemsMap.get(comparable);
final List<LookupItem> suitable = new SmartList<LookupItem>();
for (final LookupItem item : items) {
if (suits(item, matcher, pattern)) {
suitable.add(item);
}
}
if (array.size() + suitable.size() > MAX_PREFERRED_COUNT) break;
for (final LookupItem item : suitable) {
array.add(item);
first.add(item);
model.addElement(item);
}
}
myPreferredItemsCount = array.size();
for (LookupItem<?> item : myItems) {
if (!first.contains(item) && suits(item, matcher, pattern)) {
model.addElement(item);
array.add(item);
}
}
boolean isEmpty = array.isEmpty();
if (isEmpty){
LookupItem<String> item = new LookupItem<String>(CompletionBundle.message("completion.no.suggestions"), "");
item.setAttribute(EMPTY_ITEM_ATTRIBUTE, "");
model.addElement(item);
array.add(item);
}
//PsiDocumentManager.getInstance(myProject).commitDocument(myEditor.saveToString());
myList.setModel(model);
myList.setVisibleRowCount(Math.min(myList.getModel().getSize(), CodeInsightSettings.getInstance().LOOKUP_HEIGHT));
if (!isEmpty){
selectMostPreferableItem();
if (myIndex >= 0){
ListScrollingUtil.selectItem(myList, myIndex);
}
else{
if (oldSelected == null || !ListScrollingUtil.selectItem(myList, oldSelected)){
ListScrollingUtil.selectItem(myList, 0);
}
}
}
LookupItem[] items = array.toArray(new LookupItem[array.size()]);
int maxWidth = myCellRenderer.getMaximumWidth(items);
myList.setFixedCellWidth(maxWidth);
}
/**
* @return point in layered pane coordinate system.
*/
Point calculatePosition(){
Dimension dim = getComponent().getPreferredSize();
int lookupStart = getLookupStart();
LogicalPosition pos = myEditor.offsetToLogicalPosition(lookupStart);
Point location = myEditor.logicalPositionToXY(pos);
location.y += myEditor.getLineHeight();
JComponent editorComponent = myEditor.getComponent();
JComponent internalComponent = myEditor.getContentComponent();
JLayeredPane layeredPane = editorComponent.getRootPane().getLayeredPane();
Point layeredPanePoint=SwingUtilities.convertPoint(internalComponent,location, layeredPane);
layeredPanePoint.x = layeredPanePoint.x - myCellRenderer.ICON_WIDTH - 5 ;
if (dim.width > layeredPane.getWidth()){
dim.width = layeredPane.getWidth();
}
int wshift = layeredPane.getWidth() - (layeredPanePoint.x + dim.width);
if (wshift < 0){
layeredPanePoint.x += wshift;
}
if (myPositionedAbove == null){
int shiftLow = layeredPane.getHeight() - (layeredPanePoint.y + dim.height);
int shiftHigh = layeredPanePoint.y - dim.height;
myPositionedAbove = shiftLow < 0 && shiftLow < shiftHigh ? Boolean.TRUE : Boolean.FALSE;
}
if (myPositionedAbove.booleanValue()){
layeredPanePoint.y -= dim.height + myEditor.getLineHeight();
}
return layeredPanePoint;
}
public void finishLookup(final char completionChar){
final LookupItem item = (LookupItem)myList.getSelectedValue();
if (item == null){
fireItemSelected(null, completionChar);
hide();
return;
}
if(item.getObject() instanceof DeferredUserLookupValue) {
if(!((DeferredUserLookupValue)item.getObject()).handleUserSelection(item,myProject)) {
fireItemSelected(null, completionChar);
hide();
return;
}
}
final String s = item.getLookupString();
final int prefixLength = myPrefix.length();
if (item.getAttribute(EMPTY_ITEM_ATTRIBUTE) != null){
fireItemSelected(null, completionChar);
hide();
return;
}
ApplicationManager.getApplication().runWriteAction(
new Runnable() {
public void run(){
myCanceled = false;
hide();
int lookupStart = getLookupStart();
//SD - start
//this patch fixes the problem, that template is finished after showing lookup
LogicalPosition lookupPosition = myEditor.offsetToLogicalPosition(lookupStart);
myEditor.getCaretModel().moveToLogicalPosition(lookupPosition);
//SD - end
if (myEditor.getSelectionModel().hasSelection()){
myEditor.getDocument().deleteString(myEditor.getSelectionModel().getSelectionStart(), myEditor.getSelectionModel().getSelectionEnd());
}
if (s.startsWith(myPrefix)){
myEditor.getDocument().insertString(lookupStart + prefixLength, s.substring(prefixLength));
}
else{
if (prefixLength > 0){
FeatureUsageTracker.getInstance().triggerFeatureUsed("editing.completion.camelHumps");
myEditor.getDocument().deleteString(lookupStart, lookupStart + prefixLength);
}
myEditor.getDocument().insertString(lookupStart, s);
}
int offset = lookupStart + s.length();
myEditor.getCaretModel().moveToOffset(offset);
myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
myEditor.getSelectionModel().removeSelection();
fireItemSelected(item, completionChar);
}
}
);
}
private int getLookupStart() {
return myLookupStartMarker != null ? myLookupStartMarker.getStartOffset() : calcLookupStart();
}
public void show(){
int lookupStart = calcLookupStart();
myLookupStartMarker = myEditor.getDocument().createRangeMarker(lookupStart, lookupStart);
myLookupStartMarker.setGreedyToLeft(true);
//myList.setSelectedIndex(0);
if (ApplicationManager.getApplication().isUnitTestMode()) return;
Point p = calculatePosition();
HintManager hintManager = HintManager.getInstance();
hintManager.showEditorHint(this, myEditor, p, HintManager.HIDE_BY_ESCAPE | HintManager.UPDATE_BY_SCROLLING, 0, false);
}
private int calcLookupStart() {
int offset = myEditor.getSelectionModel().hasSelection()
? myEditor.getSelectionModel().getSelectionStart()
: myEditor.getCaretModel().getOffset();
return offset - myPrefix.length();
}
private void selectMostPreferableItem(){
//if (!isVisible()) return;
myIndex = LookupItemUtil.doSelectMostPreferableItem(myItemPreferencePolicy, myPrefix, ((DefaultListModel)myList.getModel()).toArray());
myList.setSelectedIndex(myIndex);
}
public LookupItem getCurrentItem(){
LookupItem item = (LookupItem)myList.getSelectedValue();
if (item != null && item.getAttribute(EMPTY_ITEM_ATTRIBUTE) != null){
return null;
}
return item;
}
public void setCurrentItem(LookupItem item){
ListScrollingUtil.selectItem(myList, item);
}
public void addLookupListener(LookupListener listener){
myListeners.add(listener);
}
public void removeLookupListener(LookupListener listener){
myListeners.remove(listener);
}
public Rectangle getCurrentItemBounds(){
int index = myList.getSelectedIndex();
Rectangle itmBounds = myList.getCellBounds(index, index);
if (itmBounds == null){
return null;
}
Rectangle listBounds=myList.getBounds();
JLayeredPane layeredPane=myList.getRootPane().getLayeredPane();
Point layeredPanePoint=SwingUtilities.convertPoint(myList,listBounds.x,listBounds.y,layeredPane);
itmBounds.x = layeredPanePoint.x;
itmBounds.y = layeredPanePoint.y;
return itmBounds;
}
private void fireItemSelected(final LookupItem item, char completionChar){
PsiDocumentManager.getInstance(myProject).commitAllDocuments(); //[Mike] todo: remove? Valentin thinks it's a major performance hit.
if (item != null && myItemPreferencePolicy != null){
myItemPreferencePolicy.itemSelected(item);
}
if (!myListeners.isEmpty()){
LookupEvent event = new LookupEvent(this, item, completionChar);
LookupListener[] listeners = myListeners.toArray(new LookupListener[myListeners.size()]);
for (LookupListener listener : listeners) {
listener.itemSelected(event);
}
}
}
private void fireLookupCanceled(){
if (!myListeners.isEmpty()){
LookupEvent event = new LookupEvent(this, null);
LookupListener[] listeners = myListeners.toArray(new LookupListener[myListeners.size()]);
for (LookupListener listener : listeners) {
listener.lookupCanceled(event);
}
}
}
private void fireCurrentItemChanged(LookupItem item){
if (!myListeners.isEmpty()){
LookupEvent event = new LookupEvent(this, item);
LookupListener[] listeners = myListeners.toArray(new LookupListener[myListeners.size()]);
for (LookupListener listener : listeners) {
listener.currentItemChanged(event);
}
}
}
public boolean fillInCommonPrefix(boolean toCompleteUniqueName){
ListModel listModel = myList.getModel();
String commonPrefix = null;
String subprefix = null;
boolean isStrict = false;
for(int i = 0; i < listModel.getSize(); i++){
LookupItem item = (LookupItem)listModel.getElementAt(i);
if (item.getAttribute(EMPTY_ITEM_ATTRIBUTE) != null) return false;
String string = item.getLookupString();
String string1 = string.substring(0, myPrefix.length());
String string2 = string.substring(myPrefix.length());
if (commonPrefix == null){
commonPrefix = string2;
subprefix = string1;
}
else{
while(commonPrefix.length() > 0){
if (string2.startsWith(commonPrefix)){
if (string2.length() > commonPrefix.length()){
isStrict = true;
}
if (!string1.equals(subprefix)){
subprefix = null;
}
break;
}
commonPrefix = commonPrefix.substring(0, commonPrefix.length() - 1);
}
if (commonPrefix.length() == 0) return false;
}
}
if (!isStrict && !toCompleteUniqueName) return false;
final String _subprefix = subprefix;
final String _commonPrefix = commonPrefix;
CommandProcessor.getInstance().executeCommand(
myProject, new Runnable() {
public void run(){
if (_subprefix != null){ // correct case
int lookupStart = getLookupStart();
myEditor.getDocument().replaceString(lookupStart, lookupStart + _subprefix.length(), _subprefix);
}
myPrefix += _commonPrefix;
EditorModificationUtil.insertStringAtCaret(myEditor, _commonPrefix);
}
},
null,
null
);
myList.repaint(); // to refresh prefix highlighting
return true;
}
public boolean isPositionedAboveCaret(){
return myPositionedAbove.booleanValue();
}
public void hide(){
if (myDisposed) return;
if (IdeEventQueue.getInstance().getPopupManager().closeActivePopup()) {
return;
}
myDisposed = true;
myEditor.getCaretModel().removeCaretListener(myEditorCaretListener);
myEditor.removeEditorMouseListener(myEditorMouseListener);
myEditor.getDocument().removeDocumentListener(myDocumentListener);
myEditor.putUserData(LOOKUP_IN_EDITOR_KEY, null);
super.hide();
if (myCanceled){
fireLookupCanceled();
}
}
static boolean isNarrowDownMode(){
return CodeInsightSettings.getInstance().NARROW_DOWN_LOOKUP_LIST;
}
public CharFilter getCharFilter() {
return myCharFilter;
}
}
|
package br.com.redesocial.modelo.dao;
import java.sql.ResultSet;
import br.com.redesocial.modelo.dto.Multimidia;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Lara, Jeferson, Luciano, Jonathan
*/
public class MultimidiaDAO extends DAOCRUDBase<Multimidia> {
@Override
public void inserir(Multimidia m) throws Exception {
Connection conexao = getConexao();
if (m.getMidia().equals("")){
throw new Exception("A mídia não pode estar vazia!");
}
PreparedStatement pstmt;
pstmt = conexao.prepareStatement("insert into multimidias(midia, tipo_conteudo, data, album) values(?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
pstmt.setBytes (1, m.getMidia());
pstmt.setString (2, m.getTipoConteudo());
pstmt.setTimestamp(3, new java.sql.Timestamp(m.getData().getTime()));
pstmt.setInt (4, m.getAlbum().getId());
pstmt.executeUpdate();
m.setId(getId(pstmt));
}
@Override
public Multimidia selecionar(int id) throws Exception{
Connection conexao = getConexao();
PreparedStatement pstmt;
pstmt = conexao.prepareStatement("select * from multimidias where id = ?");
pstmt.setInt(1, id);
ResultSet rs;
rs = pstmt.executeQuery();
if (rs.next()){
Multimidia m = new Multimidia();
m.setId(rs.getInt("id"));
m.setMidia(rs.getBytes("midia"));
m.setTipoConteudo(rs.getString("tipo_conteudo"));
m.setData(rs.getTimestamp("data"));
return m;
} else {
return null;
}
}
@Override
public void excluir(int id) throws Exception {
Connection conexao = getConexao();
PreparedStatement pstmt;
pstmt = conexao.prepareStatement("delete from multimidias where id = ?");
pstmt.setInt(1, id);
pstmt.executeUpdate();
}
@Override
public List listar() throws Exception {
Connection conexao = getConexao();
PreparedStatement pstmt;
pstmt = conexao.prepareStatement("select * from multimidias order by data desc");
ResultSet rs;
rs = pstmt.executeQuery();
List lista;
lista = new ArrayList();
while (rs.next()){
Multimidia m = new Multimidia();
m.setId(rs.getInt("id"));
m.setMidia(rs.getBytes("midia"));
m.setTipoConteudo(rs.getString("tipo_conteudo"));
m.setData(rs.getTimestamp("data"));
lista.add(m);
}
return lista;
}
@Override
public void alterar(Multimidia m) throws Exception {
Connection conexao = getConexao();
PreparedStatement pstmt;
pstmt = conexao.prepareStatement("update multimidias set midia = ?, tipo_conteudo = ?, data = ?, album = ?, where id = ?");
pstmt.setBytes(1, m.getMidia());
pstmt.setString(2, m.getTipoConteudo());
pstmt.setTimestamp(3, new java.sql.Timestamp(m.getData().getTime()));
pstmt.setInt(4, m.getAlbum().getId());
pstmt.executeUpdate();
}
public List listarMultimidiasAlbum(int id) throws Exception{
Connection conexao = getConexao();
PreparedStatement pstmt;
pstmt = conexao.prepareStatement("select * from multimidias where album = ? ");
pstmt.setInt(1, id);
ResultSet rs;
rs = pstmt.executeQuery();
List lista;
lista = new ArrayList();
while (rs.next()){
Multimidia m = new Multimidia();
m.setId(rs.getInt("id"));
m.setMidia(rs.getBytes("midia"));
m.setTipoConteudo(rs.getString("tipo_conteudo"));
m.setData(rs.getTimestamp("data"));
lista.add(m);
}
return lista;
}
}
|
package com.anpmech.mpd;
import com.anpmech.mpd.connection.CommandResponse;
import com.anpmech.mpd.connection.MPDConnection;
import com.anpmech.mpd.connection.MPDConnectionStatus;
import com.anpmech.mpd.connection.MonoIOMPDConnection;
import com.anpmech.mpd.connection.MultiIOMPDConnection;
import com.anpmech.mpd.connection.ThreadSafeMonoConnection;
import com.anpmech.mpd.exception.MPDException;
import com.anpmech.mpd.item.Album;
import com.anpmech.mpd.item.AlbumBuilder;
import com.anpmech.mpd.item.Artist;
import com.anpmech.mpd.item.Directory;
import com.anpmech.mpd.item.FilesystemTreeEntry;
import com.anpmech.mpd.item.Genre;
import com.anpmech.mpd.item.Item;
import com.anpmech.mpd.item.Music;
import com.anpmech.mpd.item.MusicBuilder;
import com.anpmech.mpd.item.PlaylistFile;
import com.anpmech.mpd.item.Stream;
import com.anpmech.mpd.subsystem.Sticker;
import com.anpmech.mpd.subsystem.status.MPDStatisticsMap;
import com.anpmech.mpd.subsystem.status.MPDStatusMap;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import static com.anpmech.mpd.Tools.KEY;
import static com.anpmech.mpd.Tools.VALUE;
/**
* MPD Server controller.
*/
public class MPD {
public static final String STREAMS_PLAYLIST = "[Radio Streams]";
private static final String TAG = "MPD";
protected final MPDPlaylist mPlaylist;
private final MPDConnection mConnection;
private final ThreadSafeMonoConnection mIdleConnection;
private final MPDStatisticsMap mStatistics;
private final MPDStatusMap mStatus;
/**
* Constructs a new MPD server controller without connection.
*/
public MPD() {
super();
mConnection = new MultiIOMPDConnection(5000);
mIdleConnection = new MonoIOMPDConnection(0);
mPlaylist = new MPDPlaylist(mConnection);
mStatistics = new MPDStatisticsMap(mConnection);
mStatus = new MPDStatusMap(mConnection);
}
/**
* Constructs a new MPD server controller.
*
* @param server server address or host name
* @param port server port
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public MPD(final InetAddress server, final int port, final CharSequence password)
throws MPDException, IOException {
this();
setDefaultPassword(password);
connect(server, port);
}
/**
* Constructs a new MPD server controller.
*
* @param server server address or host name
* @param port server port
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public MPD(final String server, final int port, final CharSequence password)
throws IOException, MPDException {
this(InetAddress.getByName(server), port, password);
}
private static String[] getAlbumArtistPair(final Album album) {
final Artist artist = album.getArtist();
final String[] artistPair;
if (artist == null) {
artistPair = new String[]{null, null};
} else {
if (album.hasAlbumArtist()) {
artistPair = new String[]{Music.TAG_ALBUM_ARTIST, artist.getName()};
} else {
artistPair = new String[]{Music.TAG_ARTIST, artist.getName()};
}
}
return artistPair;
}
private static MPDCommand getAlbumDetailsCommand(final Album album) {
final String[] artistPair = getAlbumArtistPair(album);
return MPDCommand.create(MPDCommand.MPD_CMD_COUNT,
Music.TAG_ALBUM, album.getName(),
artistPair[0], artistPair[1]);
}
private static MPDCommand getSongsCommand(final Album album) {
final String[] artistPair = getAlbumArtistPair(album);
return MPDCommand.create(MPDCommand.MPD_CMD_FIND, Music.TAG_ALBUM, album.getName(),
artistPair[0], artistPair[1]);
}
/*
* get raw command String for listAlbums
*/
private static MPDCommand listAlbumsCommand(final String artist, final boolean useAlbumArtist) {
String albumArtist = null;
if (artist != null) {
if (useAlbumArtist) {
albumArtist = Music.TAG_ALBUM_ARTIST;
} else {
albumArtist = Music.TAG_ARTIST;
}
}
return MPDCommand.create(MPDCommand.MPD_CMD_LIST_TAG, Music.TAG_ALBUM,
albumArtist, artist);
}
/*
* get raw command String for listAllAlbumsGrouped
*/
private static MPDCommand listAllAlbumsGroupedCommand(final boolean useAlbumArtist) {
final String artistTag;
if (useAlbumArtist) {
artistTag = Music.TAG_ALBUM_ARTIST;
} else {
artistTag = Music.TAG_ARTIST;
}
return MPDCommand.create(MPDCommand.MPD_CMD_LIST_TAG, Music.TAG_ALBUM,
MPDCommand.MPD_CMD_GROUP, artistTag);
}
private static MPDCommand nextCommand() {
return MPDCommand.create(MPDCommand.MPD_CMD_NEXT);
}
private static MPDCommand skipToPositionCommand(final int position) {
return MPDCommand.create(MPDCommand.MPD_CMD_PLAY, Integer.toString(position));
}
/**
* Adds a {@code Album} item object to the playlist queue.
*
* @param album {@code Album} item object to be added to the media server playlist queue.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void add(final Album album) throws IOException, MPDException {
add(album, false, false);
}
/**
* Adds a {@code Album} item object to the playlist queue.
*
* @param album {@code Album} item object to be added to the media server playlist queue.
* @param replace Whether to clear the playlist queue prior to adding the item(s).
* @param play Whether to play the playlist queue after adding the item(s).
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void add(final Album album, final boolean replace, final boolean play)
throws IOException, MPDException {
final CommandQueue commandQueue;
if (isCommandAvailable(MPDCommand.MPD_CMD_FIND_ADD)) {
final String[] artistPair = getAlbumArtistPair(album);
commandQueue = new CommandQueue();
commandQueue
.add(MPDCommand.MPD_CMD_FIND_ADD, Music.TAG_ALBUM, album.getName(),
artistPair[0], artistPair[1]);
} else {
final List<Music> songs = getSongs(album);
Collections.sort(songs);
commandQueue = MPDPlaylist.addAllCommand(songs);
}
add(commandQueue, replace, play);
}
/**
* Adds a {@code Artist} item object to the playlist queue.
*
* @param artist {@code Artist} item object to be added to the media server playlist queue.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void add(final Artist artist) throws IOException, MPDException {
add(artist, false, false);
}
/**
* Adds a {@code Artist} item object to the playlist queue.
*
* @param artist {@code Artist} item object to be added to the media server playlist queue.
* @param replace Whether to clear the playlist queue prior to adding the item(s).
* @param play Whether to play the playlist queue after adding the item(s).
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void add(final Artist artist, final boolean replace, final boolean play)
throws IOException, MPDException {
final CommandQueue commandQueue;
if (isCommandAvailable(MPDCommand.MPD_CMD_FIND_ADD)) {
commandQueue = new CommandQueue();
commandQueue
.add(MPDCommand.MPD_CMD_FIND_ADD, Music.TAG_ARTIST, artist.getName());
} else {
final List<Music> songs = getSongs(artist);
Collections.sort(songs);
commandQueue = MPDPlaylist.addAllCommand(songs);
}
add(commandQueue, replace, play);
}
/**
* Add a {@code Music} or {@code Directory} item object to the playlist queue. {@code
* PlaylistFile} items are added in it's own method.
*
* @param music {@code Music} item object to be added to the media server playlist queue.
* @param replace Whether to clear the playlist queue prior to adding the item(s).
* @param play Whether to play the playlist queue after adding the item(s).
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void add(final FilesystemTreeEntry music, final boolean replace, final boolean play)
throws IOException, MPDException {
if (music instanceof PlaylistFile) {
add((PlaylistFile) music, replace, play);
} else {
final CommandQueue commandQueue = new CommandQueue();
commandQueue.add(MPDPlaylist.addCommand(music.getFullPath()));
add(commandQueue, replace, play);
}
}
/**
* Add a {@code Music} item object to the playlist queue.
*
* @param music {@code Music} item object to be added to the playlist queue.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void add(final FilesystemTreeEntry music) throws IOException, MPDException {
add(music, false, false);
}
public void add(final Genre genre, final boolean replace, final boolean play)
throws IOException, MPDException {
final CommandQueue commandQueue;
if (isCommandAvailable(MPDCommand.MPD_CMD_FIND_ADD)) {
commandQueue = new CommandQueue();
commandQueue
.add(MPDCommand.MPD_CMD_FIND_ADD, Music.TAG_GENRE, genre.getName());
} else {
final List<Music> music = find(Music.TAG_GENRE, genre.getName());
Collections.sort(music);
commandQueue = MPDPlaylist.addAllCommand(music);
}
add(commandQueue, replace, play);
}
/**
* Adds songs to the queue. Optionally, clears the queue prior to the addition. Optionally,
* play the added songs afterward.
*
* @param commandQueue The commandQueue that will be responsible of inserting the songs into
* the queue.
* @param replace If true, replaces the entire playlist queue with the added files.
* @param playAfterAdd If true, starts playing once added.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
private void add(final CommandQueue commandQueue, final boolean replace,
final boolean playAfterAdd) throws IOException, MPDException {
int playPos = 0;
final boolean isPlaying = mStatus.isState(MPDStatusMap.STATE_PLAYING);
final boolean isConsume = mStatus.isConsume();
final boolean isRandom = mStatus.isRandom();
final int playlistLength = mStatus.getPlaylistLength();
/** Replace */
if (replace) {
if (isPlaying) {
if (playlistLength > 1) {
try {
commandQueue.addAll(0, MPDPlaylist.cropCommand(this));
} catch (final IllegalStateException ignored) {
/** Shouldn't occur, we already checked for playing. */
}
}
} else {
commandQueue.add(0, MPDPlaylist.clearCommand());
}
} else if (playAfterAdd && !isRandom) {
/** Since we didn't clear the playlist queue, we need to play the (current queue+1) */
playPos = mPlaylist.size();
}
if (replace) {
if (isPlaying) {
commandQueue.add(nextCommand());
} else if (playAfterAdd) {
commandQueue.add(skipToPositionCommand(playPos));
}
} else if (playAfterAdd) {
commandQueue.add(skipToPositionCommand(playPos));
}
/** Finally, clean up the last playing song. */
if (replace && isPlaying && !isConsume) {
commandQueue.add(MPDPlaylist.MPD_CMD_PLAYLIST_REMOVE, "0");
}
/**
* It's rare, but possible to make it through the add()
* methods without adding to the command queue.
*/
if (!commandQueue.isEmpty()) {
mConnection.send(commandQueue);
}
}
/**
* Add a {@code Playlist} item object to the playlist queue.
*
* @param databasePlaylist A playlist item stored on the media server to add to the playlist
* queue.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void add(final PlaylistFile databasePlaylist) throws IOException, MPDException {
add(databasePlaylist, false, false);
}
/**
* Add a {@code Playlist} item object to the playlist queue.
*
* @param databasePlaylist A playlist item stored on the media server to add to the playlist
* queue.
* @param replace Whether to clear the playlist queue prior to adding the
* databasePlaylist string.
* @param play Whether to play the playlist queue prior after adding the
* databasePlaylist string.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void add(final PlaylistFile databasePlaylist, final boolean replace,
final boolean play) throws IOException, MPDException {
final CommandQueue commandQueue = new CommandQueue();
commandQueue.add(MPDPlaylist.loadCommand(databasePlaylist.getName()));
add(commandQueue, replace, play);
}
protected void addAlbumDetails(final List<Album> albums)
throws IOException, MPDException {
final CommandQueue commandQueue = new CommandQueue(albums.size());
for (final Album album : albums) {
commandQueue.add(getAlbumDetailsCommand(album));
}
final List<List<String>> response = mConnection.sendSeparated(commandQueue);
if (response.size() == albums.size()) {
final AlbumBuilder albumBuilder = new AlbumBuilder();
for (int i = 0; i < response.size(); i++) {
final List<String> list = response.get(i);
final Album album = albums.get(i);
long duration = 0L;
long songCount = 0L;
albumBuilder.setAlbum(albums.get(i));
/** First, extract the album specifics from the response. */
for (final String[] pair : Tools.splitResponse(list)) {
if ("songs".equals(pair[KEY])) {
songCount = Long.parseLong(pair[VALUE]);
} else if ("playtime".equals(pair[KEY])) {
duration = Long.parseLong(pair[VALUE]);
}
}
albumBuilder.setAlbumDetails(songCount, duration);
/** Then extract the date and path from a song of the album. */
final List<Music> songs = getFirstTrack(album);
if (!songs.isEmpty()) {
albumBuilder.setSongDetails(songs.get(0).getDate(),
songs.get(0).getParentDirectory());
}
albums.set(i, albumBuilder.build());
}
}
}
protected void addAlbumSongDetails(final List<Album> albums) throws IOException, MPDException {
if (!albums.isEmpty()) {
final ListIterator<Album> iterator = albums.listIterator();
final AlbumBuilder albumBuilder = new AlbumBuilder();
while (iterator.hasNext()) {
final Album album = iterator.next();
final List<Music> songs = getFirstTrack(album);
if (!songs.isEmpty()) {
albumBuilder.setAlbum(album);
albumBuilder.setSongDetails(songs.get(0).getDate(),
songs.get(0).getParentDirectory());
iterator.set(albumBuilder.build());
}
}
}
}
/**
* Adds all songs in the database to the queue. Optionally, clears the queue prior to the
* addition. Optionally, play the added songs afterward.
*
* @param replace If true, replaces the entire playlist queue with the added files.
* @param playAfterAdd If true, starts playing once added.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void addAll(final boolean replace, final boolean playAfterAdd)
throws IOException, MPDException {
final CommandQueue commandQueue = new CommandQueue();
commandQueue.add(MPDPlaylist.MPD_CMD_PLAYLIST_ADD, "/");
add(commandQueue, replace, playAfterAdd);
}
/** TODO: This needs to be an add(Stream, ...) method. */
public void addStream(final String stream, final boolean replace, final boolean play)
throws IOException, MPDException {
final CommandQueue commandQueue = new CommandQueue();
commandQueue.add(MPDPlaylist.addCommand(stream));
add(commandQueue, replace, play);
}
@SuppressWarnings("TypeMayBeWeakened")
public void addToPlaylist(final PlaylistFile playlist, final Album album)
throws IOException, MPDException {
if (mIdleConnection.isCommandAvailable(MPDCommand.MPD_CMD_SEARCH_ADD_PLAYLIST)) {
final String[] artistPair = getAlbumArtistPair(album);
mConnection.send(MPDCommand.MPD_CMD_SEARCH_ADD_PLAYLIST, playlist.getFullPath(),
Music.TAG_ALBUM, album.getName(), artistPair[0], artistPair[1]);
} else {
final List<Music> songs = getSongs(album);
Collections.sort(songs);
addToPlaylist(playlist, songs);
}
}
@SuppressWarnings("TypeMayBeWeakened")
public void addToPlaylist(final PlaylistFile playlist, final Artist artist)
throws IOException, MPDException {
if (mIdleConnection.isCommandAvailable(MPDCommand.MPD_CMD_SEARCH_ADD_PLAYLIST)) {
mConnection.send(MPDCommand.MPD_CMD_SEARCH_ADD_PLAYLIST, playlist.getFullPath(),
Music.TAG_ARTIST, artist.getName());
} else {
final List<Music> songs = getSongs(artist);
Collections.sort(songs);
addToPlaylist(playlist, songs);
}
}
@SuppressWarnings("TypeMayBeWeakened")
public void addToPlaylist(final PlaylistFile playlist, final Collection<Music> musicCollection)
throws IOException, MPDException {
if (!musicCollection.isEmpty()) {
final CommandQueue commandQueue = new CommandQueue();
for (final Music music : musicCollection) {
commandQueue
.add(MPDCommand.MPD_CMD_PLAYLIST_ADD, playlist.getFullPath(),
music.getFullPath());
}
mConnection.send(commandQueue);
}
}
@SuppressWarnings("TypeMayBeWeakened")
public void addToPlaylist(final PlaylistFile playlist, final FilesystemTreeEntry entry)
throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_PLAYLIST_ADD, playlist.getFullPath(),
entry.getFullPath());
}
public void addToPlaylist(final PlaylistFile playlist, final Genre genre)
throws IOException, MPDException {
if (mIdleConnection.isCommandAvailable(MPDCommand.MPD_CMD_SEARCH_ADD_PLAYLIST)) {
mConnection.send(MPDCommand.MPD_CMD_SEARCH_ADD_PLAYLIST, playlist.getFullPath(),
Music.TAG_GENRE, genre.getName());
} else {
final List<Music> music = find(Music.TAG_GENRE, genre.getName());
Collections.sort(music);
addToPlaylist(playlist, music);
}
}
public void addToPlaylist(final PlaylistFile playlist, final Music music)
throws IOException, MPDException {
addToPlaylist(playlist, Collections.singletonList(music));
}
/**
* Increases or decreases volume by {@code modifier} amount.
*
* @param modifier volume adjustment
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void adjustVolume(final int modifier) throws IOException, MPDException {
// calculate final volume (clip value with [0, 100])
int vol = mStatus.getVolume() + modifier;
vol = Math.max(MPDStatusMap.VOLUME_MIN, Math.min(MPDStatusMap.VOLUME_MAX, vol));
mConnection.send(MPDCommand.MPD_CMD_SET_VOLUME, Integer.toString(vol));
}
/**
* Clears error message.
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void clearError() throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_CLEARERROR);
}
/**
* Connects to the default MPD server.
* <p/>
* If there is a default password that is not included in the {@code MPD_HOST} environment
* variable, {@link #setDefaultPassword(CharSequence)} must be called prior to this method.
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public synchronized void connect() throws IOException, MPDException {
mConnection.connect();
mIdleConnection.connect();
}
/**
* Connects to a MPD server.
* <p/>
* If there is a default password, {@link #setDefaultPassword(CharSequence)} must be called
* prior to this method.
*
* @param server server address or host name
* @param port server port
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public final synchronized void connect(final InetAddress server, final int port)
throws IOException, MPDException {
if (!isConnected()) {
mConnection.connect(server, port);
mIdleConnection.connect(server, port);
}
}
/**
* Connects to a MPD server.
* <p/>
* If there is a default password, {@link #setDefaultPassword(CharSequence)} must be called
* prior to this method.
*
* @param server server address or host name
* @param port server port
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public final void connect(final String server, final int port)
throws IOException, MPDException {
final InetAddress address = InetAddress.getByName(server);
connect(address, port);
}
/**
* Connects to a MPD server.
* <p/>
* If there is a default password, {@link #setDefaultPassword(CharSequence)} must be called
* prior to this method.
*
* @param server server address or host name and port (server:port)
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public final void connect(final String server) throws IOException,
MPDException {
int port = MPDCommand.DEFAULT_MPD_PORT;
final String host;
if (server.indexOf(':') == -1) {
host = server;
} else {
host = server.substring(0, server.lastIndexOf(':'));
port = Integer.parseInt(server.substring(server.lastIndexOf(':') + 1));
}
connect(host, port);
}
public void disableOutput(final int id) throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_OUTPUTDISABLE, Integer.toString(id));
}
/**
* Disconnects from server.
*
* @throws IOException if an error occur while closing connection
*/
public synchronized void disconnect() throws IOException {
mIdleConnection.disconnect();
mConnection.cancel();
}
public void editSavedStream(final String url, final String name, final Integer pos)
throws IOException, MPDException {
removeSavedStream(pos);
saveStream(url, name);
}
public void enableOutput(final int id) throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_OUTPUTENABLE, Integer.toString(id));
}
/**
* Similar to {@code search},{@code find} looks for exact matches in the MPD database.
*
* @param type type of search. Should be one of the following constants:
* MPD_FIND_ARTIST, MPD_FIND_ALBUM
* @param locatorString case-insensitive locator locatorString. Anything that exactly matches
* {@code locatorString} will be returned in the results.
* @return a Collection of {@code Music}
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
* @see Music
*/
public List<Music> find(final String type, final String locatorString)
throws IOException, MPDException {
return genericSearch(MPDCommand.MPD_CMD_FIND, type, locatorString);
}
public List<Music> find(final String[] args) throws IOException, MPDException {
return genericSearch(MPDCommand.MPD_CMD_FIND, args);
}
/*
* For all given albums, look for album artists and create as many albums as
* there are album artists, including "" The server call can be slow for long
* album lists
*/
protected void fixAlbumArtists(final List<Album> albums) throws IOException, MPDException {
if (!albums.isEmpty()) {
final List<List<String>> albumArtists = listAlbumArtists(albums);
if (albumArtists.size() == albums.size()) {
/** Split albums are rare, let it allocate as needed. */
@SuppressWarnings("CollectionWithoutInitialCapacity")
final Collection<Album> splitAlbums = new ArrayList<>();
final AlbumBuilder albumBuilder = new AlbumBuilder();
int i = 0;
for (final Album album : albums) {
final List<String> aartists = albumArtists.get(i);
final int aartistsSize = aartists.size();
String firstArtist;
if (aartistsSize > 0) {
albumBuilder.setAlbum(album);
Collections.sort(aartists); // make sure "" is the first one
firstArtist = aartists.get(0);
if (!firstArtist.isEmpty()) {
// album
albumBuilder.setAlbumArtist(firstArtist);
albums.set(i, albumBuilder.build(false));
} // do nothing if albumartist is ""
if (aartists.size() > 1) { // it's more than one album, insert
final ListIterator<String> iterator = aartists.listIterator(1);
while (iterator.hasNext()) {
albumBuilder.setAlbumArtist(iterator.next());
splitAlbums.add(albumBuilder.build(false));
}
}
}
i++;
}
albums.addAll(splitAlbums);
}
}
}
protected List<Music> genericSearch(final CharSequence searchCommand, final String... args)
throws IOException, MPDException {
return MusicBuilder.buildMusicFromList(mConnection.send(searchCommand, args));
}
protected List<Music> genericSearch(final CharSequence searchCommand, final String type,
final String strToFind) throws IOException, MPDException {
final List<String> response = mConnection.send(searchCommand, type, strToFind);
return MusicBuilder.buildMusicFromList(response);
}
public int getAlbumCount(final Artist artist, final boolean useAlbumArtistTag)
throws IOException, MPDException {
return listAlbums(artist, useAlbumArtistTag).size();
}
public List<Album> getAlbums(final Artist artist, final boolean sortByYear,
final boolean trackCountNeeded) throws IOException, MPDException {
final List<Album> albums = getAlbums(artist, sortByYear, trackCountNeeded, false);
// 1. the null artist list already contains all albums
// 2. the "unknown artist" should not list unknown album artists
if (artist != null && !artist.isUnknown()) {
Item.merge(albums, getAlbums(artist, sortByYear, trackCountNeeded, true));
}
return albums;
}
public List<Album> getAlbums(final Artist artist, final boolean sortByYear,
final boolean trackCountNeeded, final boolean useAlbumArtist)
throws IOException, MPDException {
final List<Album> albums;
if (artist == null) {
albums = getAllAlbums();
} else {
final List<String> albumNames = listAlbums(artist, useAlbumArtist);
albums = new ArrayList<>(albumNames.size());
if (!albumNames.isEmpty()) {
final AlbumBuilder albumBuilder = new AlbumBuilder();
for (final String album : albumNames) {
albumBuilder.setBase(album, artist, useAlbumArtist);
albums.add(albumBuilder.build());
}
if (!useAlbumArtist) {
fixAlbumArtists(albums);
}
// after fixing album artists
if (trackCountNeeded || sortByYear) {
addAlbumDetails(albums);
}
if (!sortByYear) {
addAlbumSongDetails(albums);
}
}
}
return albums;
}
/**
* Get all albums (if there is no artist specified for filtering)
*
* @return A list of all albums on the connected media server.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<Album> getAllAlbums() throws IOException, MPDException {
final List<Album> albums;
// Use MPD 0.19's album grouping feature if available.
if (mConnection.isProtocolVersionSupported(0, 19)) {
albums = listAllAlbumsGrouped(false);
} else {
final List<String> albumNames = listAlbums();
if (albumNames.isEmpty()) {
albums = Collections.emptyList();
} else {
final AlbumBuilder albumBuilder = new AlbumBuilder();
albums = new ArrayList<>(albumNames.size());
for (final String album : albumNames) {
albumBuilder.setName(album);
albums.add(albumBuilder.build());
}
}
}
return albums;
}
public List<Artist> getArtists() throws IOException, MPDException {
final List<Artist> artists = getArtists(true);
Item.merge(artists, getArtists(false));
return artists;
}
public List<Artist> getArtists(final boolean useAlbumArtist) throws IOException, MPDException {
final List<String> artistNames;
final List<Artist> artists;
if (useAlbumArtist) {
artistNames = listAlbumArtists();
} else {
artistNames = listArtists();
}
artists = new ArrayList<>(artistNames.size());
if (!artistNames.isEmpty()) {
for (final String artist : artistNames) {
artists.add(new Artist(artist));
}
}
return artists;
}
public List<Artist> getArtists(final Genre genre) throws IOException, MPDException {
final List<Artist> artists = getArtists(genre, true);
Item.merge(artists, getArtists(genre, false));
return artists;
}
public List<Artist> getArtists(final Genre genre, final boolean useAlbumArtist)
throws IOException, MPDException {
final List<String> artistNames;
final List<Artist> artists;
if (useAlbumArtist) {
artistNames = listAlbumArtists(genre);
} else {
artistNames = listArtists(genre);
}
artists = new ArrayList<>(artistNames.size());
if (!artistNames.isEmpty()) {
for (final String artist : artistNames) {
artists.add(new Artist(artist));
}
}
return artists;
}
/**
* This returns the connection status of the mono connection utilized by this class.
*
* @return The MPDConnectionStatus class for the mono connection used by this class.
*/
public MPDConnectionStatus getConnectionStatus() {
return mIdleConnection.getConnectionStatus();
}
protected List<Music> getFirstTrack(final Album album) throws IOException, MPDException {
final Artist artist = album.getArtist();
final String[] args = new String[6];
if (artist == null) {
args[0] = "";
args[1] = "";
} else if (album.hasAlbumArtist()) {
args[0] = Music.TAG_ALBUM_ARTIST;
} else {
args[0] = Music.TAG_ARTIST;
}
if (artist != null) {
args[1] = artist.getName();
}
args[2] = Music.TAG_ALBUM;
args[3] = album.getName();
args[4] = Music.TAG_TRACK;
args[5] = "1";
List<Music> songs = find(args);
if (songs.isEmpty()) {
args[5] = "01";
songs = find(args);
}
if (songs.isEmpty()) {
args[5] = "1";
songs = search(args);
}
if (songs.isEmpty()) {
final String[] args2 = Arrays.copyOf(args, 4); // find all tracks
songs = find(args2);
}
return songs;
}
public List<Genre> getGenres() throws IOException, MPDException {
final List<String> genreNames = listGenres();
final List<Genre> genres;
if (genreNames.isEmpty()) {
genres = Collections.emptyList();
} else {
genres = new ArrayList<>(genreNames.size());
for (final String genre : genreNames) {
genres.add(new Genre(genre));
}
}
return genres;
}
public InetAddress getHostAddress() {
return mConnection.getHostAddress();
}
public int getHostPort() {
return mConnection.getHostPort();
}
/**
* This returns a thread safe version of the mono socket IO connection.
*
* @return A thread safe version of the mono socket IO connection.
*/
public ThreadSafeMonoConnection getIdleConnection() {
return mIdleConnection;
}
/**
* Returns MPD server version.
*
* @return MPD Server version.
*/
public String getMpdVersion() {
final int[] version = mIdleConnection.getMPDVersion();
final StringBuilder sb = new StringBuilder(version.length);
for (int i = 0; i < version.length; i++) {
sb.append(version[i]);
if (i < version.length - 1) {
sb.append('.');
}
}
return sb.toString();
}
/**
* Returns the available outputs
*
* @return List of available outputs
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public Collection<MPDOutput> getOutputs() throws IOException, MPDException {
final List<String> response = mConnection.send(MPDCommand.MPD_CMD_OUTPUTS);
return MPDOutput.buildOutputsFromList(response);
}
/**
* Retrieves {@code playlist}.
*
* @return playlist.
*/
public MPDPlaylist getPlaylist() {
return mPlaylist;
}
@SuppressWarnings("TypeMayBeWeakened")
public List<Music> getPlaylistSongs(final PlaylistFile playlist)
throws IOException, MPDException {
final String[] args = new String[1];
args[0] = playlist.getFullPath();
return genericSearch(MPDCommand.MPD_CMD_PLAYLIST_INFO, args);
}
/**
* Returns a list of all available playlists
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<PlaylistFile> getPlaylists()
throws IOException, MPDException {
final List<String> response = mConnection.send(MPDCommand.MPD_CMD_LISTPLAYLISTS);
final List<PlaylistFile> result = new ArrayList<>(response.size());
for (final String[] pair : Tools.splitResponse(response)) {
if ("playlist".equals(pair[KEY])) {
if (null != pair[VALUE] && !STREAMS_PLAYLIST.equals(pair[VALUE])) {
result.add(new PlaylistFile(pair[VALUE]));
}
}
}
return result;
}
public List<Music> getSavedStreams() throws IOException, MPDException {
final List<String> response = mConnection.send(MPDCommand.MPD_CMD_LISTPLAYLISTS);
List<Music> savedStreams = Collections.emptyList();
for (final String[] pair : Tools.splitResponse(response)) {
if ("playlist".equals(pair[KEY])) {
if (STREAMS_PLAYLIST.equals(pair[VALUE])) {
final String[] args = {pair[VALUE]};
savedStreams = genericSearch(MPDCommand.MPD_CMD_PLAYLIST_INFO, args);
break;
}
}
}
return savedStreams;
}
public List<Music> getSongs(final Album album) throws IOException, MPDException {
final List<Music> songs = MusicBuilder
.buildMusicFromList(mConnection.send(getSongsCommand(album)));
if (album.hasAlbumArtist()) {
// remove songs that don't have this album artist (mpd >=0.18 puts them in)
final Artist artist = album.getArtist();
String artistName = null;
if (artist != null) {
artistName = artist.getName();
}
for (int i = songs.size() - 1; i >= 0; i
final String albumArtist = songs.get(i).getAlbumArtistName();
if (albumArtist != null && !albumArtist.isEmpty()
&& !albumArtist.equals(artistName)) {
songs.remove(i);
}
}
}
return songs;
}
public List<Music> getSongs(final Artist artist) throws IOException, MPDException {
final List<Album> albums = getAlbums(artist, false, false);
final List<Music> songs = new ArrayList<>(albums.size());
for (final Album album : albums) {
songs.addAll(getSongs(album));
}
return songs;
}
/**
* Retrieves the current statistics for the connected server.
*
* @return statistics for the connected server.
*/
public MPDStatisticsMap getStatistics() {
return mStatistics;
}
/**
* Retrieves status of the connected server.
*
* @return status of the connected server.
*/
public MPDStatusMap getStatus() {
return mStatus;
}
public Sticker getStickerManager() {
return new Sticker(mConnection);
}
/*
* test whether given album is in given genre
*/
public boolean isAlbumInGenre(final Album album, final Genre genre)
throws IOException, MPDException {
final List<String> response;
final Artist artist = album.getArtist();
String artistName = null;
String artistType = null;
if (artist != null) {
artistName = artist.getName();
if (album.hasAlbumArtist()) {
artistType = Music.TAG_ALBUM_ARTIST;
} else {
artistType = Music.TAG_ARTIST;
}
}
response = mConnection.send(MPDCommand.create(
MPDCommand.MPD_CMD_LIST_TAG, Music.TAG_ALBUM,
Music.TAG_ALBUM, album.getName(),
artistType, artistName,
Music.TAG_GENRE, genre.getName()));
return !response.isEmpty();
}
/**
* Checks for command validity against a list of available commands generated on connection.
*
* @param command A MPD protocol command.
* @return True if the {@code command} is available for use, false otherwise.
*/
public boolean isCommandAvailable(final String command) {
return mConnection.isCommandAvailable(command);
}
/**
* Returns true when connected and false when not connected.
*
* @return true when connected and false when not connected
*/
public boolean isConnected() {
return mIdleConnection.getConnectionStatus().isConnected();
}
/**
* List all album artist names from database.
*
* @return album artist names from database.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<String> listAlbumArtists() throws IOException, MPDException {
final List<String> response = mConnection.send(MPDCommand.MPD_CMD_LIST_TAG,
Music.TAG_ALBUM_ARTIST);
Tools.parseResponse(response, Music.RESPONSE_ALBUM_ARTIST);
return response;
}
/**
* List all album artist names from database.
*
* @return album artist names from database.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<String> listAlbumArtists(final Genre genre)
throws IOException, MPDException {
final List<String> response = mConnection.send(
MPDCommand.MPD_CMD_LIST_TAG, Music.TAG_ALBUM_ARTIST,
Music.TAG_GENRE, genre.getName());
Tools.parseResponse(response, Music.RESPONSE_ALBUM_ARTIST);
return response;
}
public List<List<String>> listAlbumArtists(final List<Album> albums)
throws IOException, MPDException {
final CommandQueue commandQueue = new CommandQueue(albums.size());
final List<List<String>> responses;
for (final Album album : albums) {
final Artist artist = album.getArtist();
String artistCommand = null;
String artistName = null;
if (artist != null) {
artistCommand = Music.TAG_ARTIST;
artistName = artist.getName();
}
commandQueue.add(MPDCommand.MPD_CMD_LIST_TAG, Music.TAG_ALBUM_ARTIST,
artistCommand, artistName,
Music.TAG_ALBUM, album.getName());
}
responses = mConnection.sendSeparated(commandQueue);
if (responses.size() == albums.size()) {
final ListIterator<List<String>> iterator = responses.listIterator();
while (iterator.hasNext()) {
final List<String> response = iterator.next();
Tools.parseResponse(response, Music.RESPONSE_ALBUM_ARTIST);
iterator.set(response);
}
} else {
Log.warning(TAG, "Response and album size differ when listing album artists.");
}
return responses;
}
/**
* List all albums from database.
*
* @return {@code Collection} with all album names from database.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<String> listAlbums() throws IOException, MPDException {
return listAlbums(null, false);
}
/**
* List all albums from a given artist.
*
* @param artist artist to list albums
* @param useAlbumArtist use AlbumArtist instead of Artist
* @return {@code Collection} with all album names from the given artist present in database.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<String> listAlbums(final Artist artist, final boolean useAlbumArtist)
throws IOException, MPDException {
final MPDCommand command;
if (artist == null) {
command = listAlbumsCommand(null, useAlbumArtist);
} else {
command = listAlbumsCommand(artist.getName(), useAlbumArtist);
}
final List<String> response = mConnection.send(command);
Tools.parseResponse(response, Music.RESPONSE_ALBUM);
return response;
}
/**
* List all albums grouped by Artist/AlbumArtist This method queries both Artist/AlbumArtist
* and tries to detect if the artist is an artist or an album artist. Only the AlbumArtist
* query will be displayed so that the list is not cluttered.
*
* @param includeUnknownAlbum include an entry for albums with no artists
* @return {@code Collection} with all albums present in database, with their artist.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<Album> listAllAlbumsGrouped(final boolean includeUnknownAlbum)
throws IOException, MPDException {
final List<Album> artistAlbums = listAllAlbumsGrouped(false, includeUnknownAlbum);
final List<Album> albumArtistAlbums = listAllAlbumsGrouped(true, includeUnknownAlbum);
for (final Album artistAlbum : artistAlbums) {
final ListIterator<Album> iterator = albumArtistAlbums.listIterator();
while (iterator.hasNext()) {
final Album albumArtistAlbum = iterator.next();
if (artistAlbum.getArtist() != null &&
artistAlbum.isNameSame(albumArtistAlbum)) {
iterator.set(artistAlbum);
}
}
}
return albumArtistAlbums;
}
/**
* List all albums grouped by Artist/AlbumArtist
*
* @param useAlbumArtist use AlbumArtist instead of Artist
* @param includeUnknownAlbum include an entry for albums with no artists
* @return {@code Collection} with all albums present in database, with their artist.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<Album> listAllAlbumsGrouped(final boolean useAlbumArtist,
final boolean includeUnknownAlbum) throws IOException, MPDException {
final AlbumBuilder albumBuilder = new AlbumBuilder();
final String albumResponse = Music.RESPONSE_ALBUM;
final String artistResponse;
final List<String> response =
mConnection.send(listAllAlbumsGroupedCommand(useAlbumArtist));
final List<Album> result = new ArrayList<>(response.size() / 2);
String currentAlbum = null;
if (useAlbumArtist) {
artistResponse = Music.RESPONSE_ALBUM_ARTIST;
} else {
artistResponse = Music.RESPONSE_ARTIST;
}
for (final String[] pair : Tools.splitResponse(response)) {
if (artistResponse.equals(pair[KEY])) {
if (currentAlbum != null) {
albumBuilder.setBase(currentAlbum, pair[VALUE], useAlbumArtist);
result.add(albumBuilder.build());
currentAlbum = null;
}
} else if (albumResponse.equals(pair[KEY])) {
if (currentAlbum != null) {
albumBuilder.setName(currentAlbum);
/** There was no artist in this response, add the album alone */
result.add(albumBuilder.build());
}
if (!pair[VALUE].isEmpty() || includeUnknownAlbum) {
currentAlbum = pair[VALUE];
} else {
currentAlbum = null;
}
}
}
return result;
}
/**
* Returns a sorted listallinfo command from the media server. Use of this command is highly
* discouraged, as it can retrieve so much information the server max_output_buffer_size may be
* exceeded, which will, in turn, truncate the output to this method.
*
* @return List of all available music information.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<Music> listAllInfo() throws IOException, MPDException {
final List<String> allInfo = mConnection.send(MPDCommand.MPD_CMD_LISTALLINFO);
return MusicBuilder.buildMusicFromList(allInfo);
}
/**
* List all artist names from database.
*
* @return artist names from database.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<String> listArtists() throws IOException, MPDException {
final CommandResponse response = mConnection.submit(MPDCommand.MPD_CMD_LIST_TAG,
Music.TAG_ARTIST).get();
return response.getValues(Music.RESPONSE_ARTIST);
}
/**
* List all album artist or artist names of all given albums from database.
*
* @return list of array of artist names for each album.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<List<String>> listArtists(final List<Album> albums, final boolean useAlbumArtist)
throws IOException, MPDException {
final List<List<String>> responses = listArtistsCommand(albums, useAlbumArtist);
final List<List<String>> result = new ArrayList<>(responses.size());
final int artistLength;
List<String> albumResult = Collections.emptyList();
if (useAlbumArtist) {
artistLength = Music.RESPONSE_ALBUM_ARTIST.length() + 2;
} else {
artistLength = Music.RESPONSE_ARTIST.length() + 2;
}
for (final List<String> response : responses) {
albumResult.clear();
for (final String album : response) {
final String name = album.substring(artistLength);
/** Give the array list an approximate size. */
albumResult = new ArrayList<>(album.length() * response.size());
albumResult.add(name);
}
result.add(albumResult);
}
return result;
}
/**
* List all artist names from database.
*
* @return artist names from database.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<String> listArtists(final Genre genre) throws IOException, MPDException {
final CommandResponse response = mConnection.submit(MPDCommand.MPD_CMD_LIST_TAG,
Music.TAG_ARTIST, Music.TAG_GENRE, genre.getName()).get();
return response.getValues(Music.RESPONSE_ARTIST);
}
private List<List<String>> listArtistsCommand(final Iterable<Album> albums,
final boolean useAlbumArtist) throws IOException, MPDException {
final CommandQueue commandQueue = new CommandQueue();
for (final Album album : albums) {
final Artist artist = album.getArtist();
// When adding album artist to existing artist check that the artist matches
if (useAlbumArtist && artist != null && !artist.isUnknown()) {
commandQueue.add(MPDCommand.MPD_CMD_LIST_TAG, Music.TAG_ALBUM_ARTIST,
Music.TAG_ALBUM, album.getName(),
Music.TAG_ARTIST, artist.getName());
} else {
final String artistCommand;
if (useAlbumArtist) {
artistCommand = Music.TAG_ALBUM_ARTIST;
} else {
artistCommand = Music.TAG_ARTIST;
}
commandQueue.add(MPDCommand.MPD_CMD_LIST_TAG, artistCommand,
Music.TAG_ALBUM, album.getName());
}
}
return mConnection.sendSeparated(commandQueue);
}
/**
* List all genre names from database.
*
* @return artist names from database.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<String> listGenres() throws IOException, MPDException {
final List<String> response = mConnection.send(MPDCommand.MPD_CMD_LIST_TAG,
Music.TAG_GENRE);
Tools.parseResponse(response, Music.RESPONSE_GENRE);
return response;
}
@SuppressWarnings("TypeMayBeWeakened")
public void movePlaylistSong(final PlaylistFile playlist, final int from, final int to)
throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_PLAYLIST_MOVE, playlist.getFullPath(),
Integer.toString(from), Integer.toString(to));
}
/**
* Jumps to next playlist track.
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void next() throws IOException, MPDException {
mConnection.send(nextCommand());
}
/**
* Pauses/Resumes music playing.
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void pause() throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_PAUSE);
}
/**
* Starts playing music.
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void play() throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_PLAY);
}
/**
* Plays previous playlist music.
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void previous() throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_PREV);
}
/**
* Tells server to refresh database.
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void refreshDatabase() throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_REFRESH);
}
/**
* Tells server to refresh database.
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void refreshDatabase(final String folder) throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_REFRESH, folder);
}
public void refreshDirectory(final Directory directory)
throws IOException, MPDException {
directory.refresh(mConnection);
}
/**
* Removes a list of tracks from a playlist file, by position.
*
* @param playlist The playlist file to remove tracks from.
* @param positions The positions of the tracks to remove from the playlist file.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
@SuppressWarnings("TypeMayBeWeakened")
public void removeFromPlaylist(final PlaylistFile playlist, final List<Integer> positions)
throws IOException, MPDException {
Collections.sort(positions, Collections.reverseOrder());
final CommandQueue commandQueue = new CommandQueue(positions.size());
for (final Integer position : positions) {
commandQueue.add(MPDCommand.MPD_CMD_PLAYLIST_DEL, playlist.getFullPath(),
position.toString());
}
mConnection.send(commandQueue);
}
@SuppressWarnings("TypeMayBeWeakened")
public void removeFromPlaylist(final PlaylistFile playlist, final Integer pos)
throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_PLAYLIST_DEL, playlist.getFullPath(),
Integer.toString(pos));
}
public void removeSavedStream(final Integer pos) throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_PLAYLIST_DEL, STREAMS_PLAYLIST,
Integer.toString(pos));
}
public void saveStream(final String url, final String name) throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_PLAYLIST_ADD, STREAMS_PLAYLIST,
Stream.addStreamName(url, name));
}
/**
* Similar to {@code find},{@code search} looks for partial matches in the MPD database.
*
* @param type type of search. Should be one of the following constants:
* MPD_SEARCH_ARTIST, MPD_SEARCH_TITLE, MPD_SEARCH_ALBUM,
* MPD_SEARCH_FILENAME
* @param locatorString case-insensitive locator locatorString. Anything that contains {@code
* locatorString} will be returned in the results.
* @return a Collection of {@code Music}.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
* @see Music
*/
public List<Music> search(final String type, final String locatorString)
throws IOException, MPDException {
return genericSearch(MPDCommand.MPD_CMD_SEARCH, type, locatorString);
}
public List<Music> search(final String... args) throws IOException, MPDException {
return genericSearch(MPDCommand.MPD_CMD_SEARCH, args);
}
/**
* Seeks current music to the position.
*
* @param position song position in seconds
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void seek(final long position) throws IOException, MPDException {
seekById(mStatus.getSongId(), position);
}
/**
* Seeks music to the position.
*
* @param songId music id in playlist.
* @param position song position in seconds.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void seekById(final int songId, final long position) throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_SEEK_ID, Integer.toString(songId),
Long.toString(position));
}
/**
* Seeks music to the position.
*
* @param index music position in playlist.
* @param position song position in seconds.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void seekByIndex(final int index, final long position) throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_SEEK, Integer.toString(index),
Long.toString(position));
}
/**
* Enabled or disable consuming.
*
* @param consume if true song consuming will be enabled, if false song consuming will be
* disabled.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void setConsume(final boolean consume) throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_CONSUME, MPDCommand.booleanValue(consume));
}
/**
* Sets cross-fade.
*
* @param time cross-fade time in seconds. 0 to disable cross-fade.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void setCrossFade(final int time) throws IOException, MPDException {
mConnection
.send(MPDCommand.MPD_CMD_CROSSFADE, Integer.toString(Math.max(0, time)));
}
/**
* This sets the default password for the MPD server.
*
* @param password The default password for this MPD server.
*/
public final void setDefaultPassword(final CharSequence password) {
mConnection.setDefaultPassword(password);
mIdleConnection.setDefaultPassword(password);
}
/**
* Enabled or disable random.
*
* @param random if true random will be enabled, if false random will be disabled.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void setRandom(final boolean random) throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_RANDOM, MPDCommand.booleanValue(random));
}
/**
* Enabled or disable repeating.
*
* @param repeat if true repeating will be enabled, if false repeating will be disabled.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void setRepeat(final boolean repeat) throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_REPEAT, MPDCommand.booleanValue(repeat));
}
/**
* Enabled or disable single mode.
*
* @param single if true single mode will be enabled, if false single mode will be disabled.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void setSingle(final boolean single) throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_SINGLE, MPDCommand.booleanValue(single));
}
/**
* Sets volume to {@code volume}.
*
* @param volume new volume value, must be in 0-100 range.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void setVolume(final int volume) throws IOException, MPDException {
final int vol = Math.max(MPDStatusMap.VOLUME_MIN,
Math.min(MPDStatusMap.VOLUME_MAX, volume));
mConnection.send(MPDCommand.MPD_CMD_SET_VOLUME, Integer.toString(vol));
}
/**
* Kills server.
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void shutdown() throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_KILL);
}
/**
* Skip to song with specified {@code id}.
*
* @param id song id.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void skipToId(final int id) throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_PLAY_ID, Integer.toString(id));
}
/**
* Jumps to track {@code position} from playlist.
*
* @param position track number.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
* @see #skipToId(int)
*/
public void skipToPosition(final int position) throws IOException, MPDException {
mConnection.send(skipToPositionCommand(position));
}
/**
* Stops music playing.
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void stop() throws IOException, MPDException {
mConnection.send(MPDCommand.MPD_CMD_STOP);
}
}
|
package net.hermajan.lyrics.providers;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import net.hermajan.lyrics.Library;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Entities;
import org.jsoup.select.Elements;
public class LyricWiki extends Provider {
public LyricWiki(String artist, String track) {
super.setArtist(artist); super.setTrack(track);
this.makeURL();
}
@Override
public void makeURL() {
try {
String capitalizedTrack=Library.capitalizeFirstLetters(super.getTrack());
URI uri=new URI("http","lyrics.wikia.com","/"+super.getArtist()+":"+capitalizedTrack,null,null);
super.setURL(uri.toASCIIString());
} catch(URISyntaxException use) { System.err.println(use); }
}
@Override
public String parsing() {
String output="";
try {
Document doc=Jsoup.connect(super.getURL()).get();
doc.select(".rtMatcher").remove(); doc.select(".lyricsBreak").remove();
doc.select("script").remove(); Library.removeComments(doc);
Elements lyr=doc.select(".lyricbox");
doc.outputSettings().escapeMode(Entities.EscapeMode.xhtml);
output=lyr.html();
output=Library.replacing(output);
} catch(IOException ioe) { System.err.println(ioe); }
if(output.contains("<span") && output.contains("title=\"Instrumental\"")) {
output="This is an instrumental song with no lyrics.";
}
if(output.isEmpty()) { output+="Error: There are no lyrics for this artist and track in the database."; }
return output;
}
@Override
public String parsingText() {
String output=parsing();
output.replace("<br />","");
output.replace("<b>","").replace("</b>","");
output.replace("<i>","").replace("</i>","");
return output;
}
@Override
public String toString() {
String ts=super.toString();
return ts+", provider LyricWiki"+System.getProperty("line.separator")+parsingText();
}
}
|
package net.sf.jaer.eventprocessing;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.KeyboardFocusManager;
import java.awt.SystemColor;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import net.sf.jaer.util.EngineeringFormat;
/**
* A panel for a filter that has Integer/Float/Boolean/String/enum getter/setter
* methods (bound properties). These methods are introspected and a set of
* controls are built for them. Enclosed filters and filter chains have panels
* built for them that are enlosed inside the filter panel, hierarchically.
* <ul>
* <li>Numerical properties (ints, floats, but not currently doubles) construct
* a JTextBox control that also allows changes from mouse wheel or arrow keys.
* <li> boolean properties construct a JCheckBox control.
* <li> String properties construct a JTextField control.
* <li> enum properties construct a JComboBox control, which all the possible
* enum constant values.
* </ul>
* <p>
* If a filter wants to automatically have the GUI controls reflect what the
* property state is, then it should fire PropertyChangeEvent when the property
* changes. For example, an {@link EventFilter} can implement a setter like
* this:
* <pre>
* public void setMapEventsToLearnedTopologyEnabled(boolean mapEventsToLearnedTopologyEnabled) {
* support.firePropertyChange("mapEventsToLearnedTopologyEnabled", this.mapEventsToLearnedTopologyEnabled, mapEventsToLearnedTopologyEnabled); // property, old value, new value
* this.mapEventsToLearnedTopologyEnabled = mapEventsToLearnedTopologyEnabled;
* getPrefs().putBoolean("TopologyTracker.mapEventsToLearnedTopologyEnabled", mapEventsToLearnedTopologyEnabled);
* }
* </pre> Here, <code>support</code> is a protected field of EventFilter. The
* change event comes here to FilterPanel and the appropriate automatically
* generated control is modified.
* <p>
* Note that calling firePropertyChange as shown above will inform listeners
* <em>before</em> the property has actually been changed (this.dt has not been
* set yet).
* <p>
* A tooltip for the property can be installed using the EventFilter
* setPropertyTooltip method, for example
* <pre>
* setPropertyTooltip("sizeClassificationEnabled", "Enables coloring cluster by size threshold");
* </pre> will install a tip for the property sizeClassificationEnabled.
* <p>
* <strong>Slider controls.</strong>
*
* If you want a slider for an int or float property, then create getMin and
* getMax methods for the property, e.g., for the property <code>dt</code>:
* <pre>
* public int getDt() {
* return this.dt;
* }
*
* public void setDt(final int dt) {
* getPrefs().putInt("BackgroundActivityFilter.dt",dt);
* support.firePropertyChange("dt",this.dt,dt);
* this.dt = dt;
* }
*
* public int getMinDt(){
* return 10;
* }
*
* public int getMaxDt(){
* return 100000;
* }
* </pre>
* <strong>Button control</strong>
* <p>
* To add a button control to a panel, implement a method starting with "do",
* e.g.
* <pre>
* public void doSendParameters() {
* sendParameters();
* }
* </pre> This method will construct a button with label "SendParameters" which,
* when pressed, will call the method "doSendParameters".
* <p>
* <p>
* To add a momentary press/release button control to a panel, implement a pair
* of methods starting with "doPress" and "doRelease", e.g.
* <pre>
* public void doPressTurnOnLamp();
* public void doReleaseTurnOnLamp();
** </pre> This method will construct a button with label "TurnOnLamp" which,
* while pressed can turn on something momentarily; the doPressXXX() is called
* on press and doReleaseXXX() on release
* <p>
* <p>
* To add a toggle button control to a panel, implement a pair of methods
* starting with "doToggleOn" and "doToggleOff", e.g.
* <pre>
* public void doToggleOnLamp();
* public void doToggleOffLamp();
** </pre> This method will construct a button with label "Lamp" which, while
* pressed can turn on something momentarily; the doToggleOnLamp() is called on
* press and doToggleOffLamp() on release
* <p>
* <strong>
* Grouping parameters.</strong>
* <p>
* Properties are normally sorted alphabetically, with button controls at the
* top. If you want to group parameters, use the built in EventFilter method
* {@link net.sf.jaer.eventprocessing.EventFilter#addPropertyToGroup}. All
* properties of a given group are grouped together. Within a group the
* parameters are sorted alphabetically, and the groups will also be sorted
* alphabetically and shown before any ungrouped parameters. E.g., to Create
* groups "Sizing" and "Tracking" and add properties to each, do
* <pre>
* addPropertyToGroup("Sizing", "clusterSize");
* addPropertyToGroup("Sizing", "aspectRatio");
* addPropertyToGroup("Sizing", "highwayPerspectiveEnabled");
* addPropertyToGroup("Tracking", "mixingFactor");
* addPropertyToGroup("Tracking", "velocityMixingFactor");
* </pre> Or, even simpler, if you have already defined tooltips for your
* properties, then you can use the overloaded
* {@link net.sf.jaer.eventprocessing.EventFilter#setPropertyTooltip(java.lang.String, java.lang.String, java.lang.String) setPropertyTooltip}
* of {@link net.sf.jaer.eventprocessing.EventFilter}, as shown next. Here two
* groups "Size" and "Timing" are defined and properties are added to each (or
* to neither for "multiOriOutputEnabled").
* <pre>
* final String size="Size", tim="Timing";
*
* setPropertyTooltip(tim,"minDtThreshold", "Coincidence time, events that pass this coincidence test are considerd for orientation output");
* setPropertyTooltip(tim,"dtRejectMultiplier", "reject delta times more than this KEY_FACTOR times minDtThreshold to reduce noise");
* setPropertyTooltip(tim,"dtRejectThreshold", "reject delta times more than this time in us to reduce effect of very old events");
* setPropertyTooltip("multiOriOutputEnabled", "Enables multiple event output for all events that pass test");
* </pre>
*
*
* @author tobi
* @see
* net.sf.jaer.eventprocessing.EventFilter#setPropertyTooltip(java.lang.String,
* java.lang.String)
* @see
* net.sf.jaer.eventprocessing.EventFilter#setPropertyTooltip(java.lang.String,
* java.lang.String, java.lang.String)
* @see net.sf.jaer.eventprocessing.EventFilter
*/
public class FilterPanel extends javax.swing.JPanel implements PropertyChangeListener {
private interface HasSetter {
void set(Object o);
}
static final float LEFT_ALIGNMENT = Component.LEFT_ALIGNMENT;
private BeanInfo info;
private PropertyDescriptor[] props;
private Method[] methods;
private static Logger log = Logger.getLogger("Filters");
private EventFilter filter = null;
final float fontSize = 10f;
private Border normalBorder, redLineBorder, enclosedFilterSelectedBorder;
private TitledBorder titledBorder;
private HashMap<String, HasSetter> setterMap = new HashMap<String, HasSetter>(); // map from filter to property, to apply property change events to control
protected java.util.ArrayList<JComponent> controls = new ArrayList<JComponent>();
private HashMap<EventFilter, FilterPanel> enclosedFilterPanels = new HashMap(); // points from enclosed filter to its panel
private HashMap<String, Container> groupContainerMap = new HashMap(); // points from group name string to the panel holding the properties
private HashSet<String> populatedGroupSet = new HashSet(); // Set of all property groups that have at least one item in them
private HashMap<String, MyControl> propertyControlMap = new HashMap();
private JComponent ungroupedControls = null;
private float DEFAULT_REAL_VALUE = 0.01f; // value jumped to from zero on key or wheel up
ArrayList<AbstractButton> doButList = new ArrayList();
/**
* Creates new form FilterPanel
*/
public FilterPanel() {
initComponents();
}
public FilterPanel(EventFilter f) {
// log.info("building FilterPanel for "+f);
this.setFilter(f);
initComponents();
Dimension d = enableResetControlsHelpPanel.getPreferredSize();
enableResetControlsHelpPanel.setMaximumSize(new Dimension(1000, d.height)); // keep from stretching
String cn = getFilter().getClass().getName();
int lastdot = cn.lastIndexOf('.');
String name = cn.substring(lastdot + 1);
setName(name);
titledBorder = new TitledBorder(name);
titledBorder.getBorderInsets(this).set(1, 1, 1, 1);
setBorder(titledBorder);
normalBorder = titledBorder.getBorder();
redLineBorder = BorderFactory.createLineBorder(Color.red, 3);
enclosedFilterSelectedBorder = BorderFactory.createLineBorder(Color.orange, 3);
enabledCheckBox.setSelected(getFilter().isFilterEnabled());
addIntrospectedControls();
// when filter fires a property change event, we getString called here and we update all our controls
getFilter().getSupport().addPropertyChangeListener(this);
// // add ourselves to listen for all enclosed filter property changes as well
// EventFilter enclosed = getFilter().getEnclosedFilter();
// while (enclosed != null) {
// enclosed.getSupport().addPropertyChangeListener(this);
// enclosed = enclosed.getEnclosedFilter();
// FilterChain chain = getFilter().getEnclosedFilterChain();
// if (chain != null) {
// for (EventFilter f2 : chain) {
// EventFilter f3=f2;
// while (f3 != null) {
// f3.getSupport().addPropertyChangeListener(this);
// f3 = f3.getEnclosedFilter(); // for some very baroque arrangement
ToolTipManager.sharedInstance().setDismissDelay(10000); // to show tips
setToolTipText(f.getDescription());
// helpBut.setToolTipText("<html>" + f.getDescription() + "<p>Click to show/create wiki page");
}
// checks for group container and adds to that if needed.
private void myadd(MyControl comp, String propertyName, boolean inherited) {
// if(propertyControlMap.containsKey(propertyName)){
// log.warning("controls already has "+propertyControlMap.get(propertyName));
if (!getFilter().hasPropertyGroups()) {
ungroupedControls.add(comp);
controls.add(comp);
propertyControlMap.put(propertyName, comp);
return;
}
String groupName = getFilter().getPropertyGroup(propertyName);
if (groupName != null) {
Container container = groupContainerMap.get(groupName);
// comp.setAlignmentX(Component.LEFT_ALIGNMENT);
// if(inherited){
// JPanel inherPan=new JPanel();
// inherPan.setBorder(BorderFactory.createLineBorder(Color.yellow) );
// inherPan.add(comp,BorderLayout.WEST);
// container.add(inherPan);
// }else{
container.add(comp);
populatedGroupSet.add(groupName); // add to list of populated groups
} else {
ungroupedControls.add(comp);
}
controls.add(comp);
propertyControlMap.put(propertyName, comp);
}
// gets getter/setter methods for the filter and makes controls for them. enclosed filters are also added as submenus
private void addIntrospectedControls() {
add(Box.createVerticalStrut(0));
ungroupedControls = new MyControl();
String u = "(Ungrouped)";
ungroupedControls.setName(u);
ungroupedControls.setBorder(new TitledBorder(u));
ungroupedControls.setLayout(new GridLayout(0, 1));
controls.add(ungroupedControls);
MyControl control = null;
EventFilter filter = getFilter();
try {
info = Introspector.getBeanInfo(filter.getClass());
// TODO check if class is public, otherwise we can't access methods usually
this.props = info.getPropertyDescriptors();
this.methods = filter.getClass().getMethods();
int numDoButtons = 0;
// first add buttons when the method name starts with "do". These methods are by convention associated with actions.
// these methods, e.g. "void doDisableServo()" do an action.
// also, a pair of methods doPressXXX and doReleaseXXX will add a button that calls the first method on press and the 2nd on release
Insets butInsets = new Insets(0, 0, 0, 0);
for (Method method : methods) {
// add a button XXX that calls doPressXXX on press and doReleaseXXX on release of button
if (method.getName().startsWith("doPress")
&& (method.getParameterTypes().length == 0)
&& (method.getReturnType() == void.class)) {
for (Method releasedMethod : methods) {
String suf = method.getName().substring(7);
if (releasedMethod.getName().equals("doRelease" + suf)
&& (releasedMethod.getParameterTypes().length == 0)
&& (releasedMethod.getReturnType() == void.class)) {
//found corresponding release method, add action listeners for press and release
numDoButtons++;
JButton button = new JButton(method.getName().substring(7));
button.setMargin(butInsets);
button.setFont(button.getFont().deriveFont(9f));
final EventFilter f = filter;
final Method pressedMethodFinal = method;
final Method releasedMethodFinal = releasedMethod;
button.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
try {
pressedMethodFinal.invoke(f);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (InvocationTargetException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
}
@Override
public void mouseReleased(MouseEvent e) {
try {
releasedMethodFinal.invoke(f);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (InvocationTargetException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
}
});
addTip(f, button);
doButList.add(button);
break; // don't bother with rest of methods
}
}
}
if (method.getName().startsWith("doToggleOn")
&& (method.getParameterTypes().length == 0)
&& (method.getReturnType() == void.class)) {
for (Method toggleOffMethod : methods) {
String suf = method.getName().substring(10);
if (toggleOffMethod.getName().equals("doToggleOff" + suf)
&& (toggleOffMethod.getParameterTypes().length == 0)
&& (toggleOffMethod.getReturnType() == void.class)) {
//found corresponding release method, add action listeners for toggle on and toggle off
numDoButtons++;
final JToggleButton button = new JToggleButton(method.getName().substring(10));
button.setMargin(butInsets);
button.setFont(button.getFont().deriveFont(9f));
final EventFilter f = filter;
final Method toggleOnMethodFinal = method;
final Method toggleOffMethodFinal = toggleOffMethod;
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
if (button.isSelected()) {
toggleOnMethodFinal.invoke(f);
} else {
toggleOffMethodFinal.invoke(f);
}
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (InvocationTargetException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
}
});
addTip(f, button);
doButList.add(button);
break; // don't bother with rest of methods
}
}
}
// add a button that calls a method XXX for method void doXXX()
if (method.getName().startsWith("do") && !method.getName().startsWith("doPress") && !method.getName().startsWith("doRelease")
&& !method.getName().startsWith("doToggleOn") && !method.getName().startsWith("doToggleOff")
&& (method.getParameterTypes().length == 0)
&& (method.getReturnType() == void.class)) {
numDoButtons++;
JButton button = new JButton(method.getName().substring(2));
button.setMargin(butInsets);
button.setFont(button.getFont().deriveFont(9f));
final EventFilter f = filter;
final Method meth = method;
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
meth.invoke(f);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (InvocationTargetException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
}
});
addTip(f, button);
doButList.add(button);
}
}
Comparator<AbstractButton> butComp = new Comparator<AbstractButton>() {
@Override
public int compare(AbstractButton o1, AbstractButton o2) {
if ((o1 == null) || (o2 == null) || (o1.getText() == null) || (o2.getText() == null)) {
return 0;
}
return o1.getText().compareToIgnoreCase(o2.getText());
}
};
Collections.sort(doButList, butComp);
if (!doButList.isEmpty()) {
JPanel buttons = new JPanel() {
@Override
public Dimension getMaximumSize() {
return getPreferredSize();
}
};
for (AbstractButton b : doButList) {
buttons.add(b);
}
//if at least one button then we show the actions panel
// buttons.setMinimumSize(new Dimension(0, 0));
buttons.setLayout(new GridLayout(0, 3, 3, 3));
JPanel butPanel = new MyControl();
butPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
butPanel.add(buttons);
TitledBorder tb = new TitledBorder("Filter Actions");
tb.getBorderInsets(this).set(1, 1, 1, 1);
butPanel.setBorder(tb);
add(butPanel);
controls.add(butPanel);
}
// if (numDoButtons > 3) {
// control.setLayout(new GridLayout(0, 3, 3, 3));
// next add enclosed Filter and enclosed FilterChain so they appear at top of list (they are processed first)
for (PropertyDescriptor p : props) {
Class c = p.getPropertyType();
if (p.getName().equals("enclosedFilter")) { //if(c==EventFilter2D.class){
// if type of property is an EventFilter, check if it has either an enclosed filter
// or an enclosed filter chain. If so, construct FilterPanels for each of them.
try {
Method r = p.getReadMethod(); // getString the getter for the enclosed filter
EventFilter2D enclFilter = (EventFilter2D) (r.invoke(getFilter()));
if (enclFilter != null) {
// log.info("EventFilter "+filter.getClass().getSimpleName()+" encloses EventFilter2D "+enclFilter.getClass().getSimpleName());
FilterPanel enclPanel = new FilterPanel(enclFilter);
this.add(enclPanel);
controls.add(enclPanel);
enclosedFilterPanels.put(enclFilter, enclPanel);
((TitledBorder) enclPanel.getBorder()).setTitle("enclosed: " + enclFilter.getClass().getSimpleName());
}
// FilterChain chain=getFilter().getEnclosedFilterChain();
// if(chain!=null){
// log.info("EventFilter "+filter.getClass().getSimpleName()+" encloses filterChain "+chain);
// for(EventFilter f:chain){
// FilterPanel enclPanel=new FilterPanel(f);
// this.add(enclPanel);
// controls.add(enclPanel);
// ((TitledBorder)enclPanel.getBorder()).setTitle("enclosed: "+f.getClass().getSimpleName());
} catch (Exception e) {
e.printStackTrace();
}
} else if (p.getName().equals("enclosedFilterChain")) {
// if type of property is a FilterChain, check if it has either an enclosed filter
// or an enclosed filter chain. If so, construct FilterPanels for each of them.
try {
Method r = p.getReadMethod(); // getString the getter for the enclosed filter chain
FilterChain chain = (FilterChain) (r.invoke(getFilter()));
if (chain != null) {
// log.info("EventFilter "+filter.getClass().getSimpleName()+" encloses filterChain "+chain);
for (EventFilter f : chain) {
FilterPanel enclPanel = new FilterPanel(f);
this.add(enclPanel);
controls.add(enclPanel);
enclosedFilterPanels.put(f, enclPanel);
((TitledBorder) enclPanel.getBorder()).setTitle("enclosed: " + f.getClass().getSimpleName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
String name = p.getName();
if (control != null) {
control.setToolTipText(getFilter().getPropertyTooltip(name));
}
}
}
// next add all other properties that we can handle
// these must be saved and then sorted in case there are property groups defined.
if (getFilter().hasPropertyGroups()) {
Set<String> groupSet = getFilter().getPropertyGroupSet();
ArrayList<String> setList = new ArrayList();
setList.addAll(groupSet);
Collections.sort(setList);
for (String s : setList) {
JPanel groupPanel = new MyControl();
groupPanel.setName(s);
groupPanel.setBorder(new TitledBorder(s));
groupPanel.setLayout(new GridLayout(0, 1));
groupContainerMap.put(s, groupPanel); // point from group name to its panel container
add(groupPanel);
controls.add(groupPanel); // visibility list
}
}
// ArrayList<Component> sortedControls=new ArrayList();
// iterate over all methods, adding controls to panel for each type of property
// but only for those properties that are not marked as "hidden"
for (PropertyDescriptor p : props) {
// System.out.println("filter "+getFilter().getClass().getSimpleName()+" has property name="+p.getName()+" type="+p.getPropertyType());
// if(false){
//// System.out.println("prop "+p);
//// System.out.println("prop name="+p.getName());
//// System.out.println("prop write method="+p.getWriteMethod());
//// System.out.println("prop read method="+p.getReadMethod());
//// System.out.println("type "+p.getPropertyType());
//// System.out.println("bound: "+p.isBound());
//// System.out.println("");
try {
boolean inherited = false;
// TODO handle indexed properties
Class c = p.getPropertyType();
String name = p.getName();
// check if method comes from a superclass of this EventFilter
if ((control != null) && (p.getReadMethod() != null) && (p.getWriteMethod() != null)) {
Method m = p.getReadMethod();
if (m.getDeclaringClass() != getFilter().getClass()) {
inherited = true;
}
}
boolean hidden = filter.isPropertyHidden(p.getName());
if (hidden) {
log.info("not constructing control for " + filter.getClass().getSimpleName() + " for hidden property " + p.getName());
continue;
}
// don't show this getter/setter that is controlled by button
if (p.getName().equals("controlsVisible")) {
continue;
}
if ((c == Integer.TYPE) && (p.getReadMethod() != null) && (p.getWriteMethod() != null)) {
SliderParams params;
if ((params = isSliderType(p, filter)) != null) {
control = new IntSliderControl(getFilter(), p.getName(), p.getWriteMethod(), p.getReadMethod(), params);
} else {
control = new IntControl(getFilter(), p.getName(), p.getWriteMethod(), p.getReadMethod());
}
myadd(control, name, inherited);
} else if ((c == Float.TYPE) && (p.getReadMethod() != null) && (p.getWriteMethod() != null)) {
SliderParams params;
if ((params = isSliderType(p, filter)) != null) {
control = new FloatSliderControl(getFilter(), p.getName(), p.getWriteMethod(), p.getReadMethod(), params);
} else {
control = new FloatControl(getFilter(), p.getName(), p.getWriteMethod(), p.getReadMethod());
}
myadd(control, name, inherited);
} else if ((c == Boolean.TYPE) && (p.getReadMethod() != null) && (p.getWriteMethod() != null)) {
if (p.getName().equals("filterEnabled")) { // built in, skip
continue;
}
if (p.getName().equals("annotationEnabled")) {// built in, skip
continue;
}
if (p.getName().equals("selected")) {// built in, skip
continue;
}
control = new BooleanControl(getFilter(), p.getName(), p.getWriteMethod(), p.getReadMethod());
myadd(control, name, inherited);
} else if ((c == String.class) && (p.getReadMethod() != null) && (p.getWriteMethod() != null)) {
if (p.getName().equals("filterEnabled")) {
continue;
}
if (p.getName().equals("annotationEnabled")) {
continue;
}
control = new StringControl(getFilter(), p.getName(), p.getWriteMethod(), p.getReadMethod());
myadd(control, name, inherited);
} else if ((c != null) && c.isEnum() && (p.getReadMethod() != null) && (p.getWriteMethod() != null)) {
control = new EnumControl(c, getFilter(), p.getName(), p.getWriteMethod(), p.getReadMethod());
myadd(control, name, inherited);
} else if ((c != null) && ((c == Point2D.Float.class) || (c == Point2D.Double.class) || (c == Point2D.class)) && (p.getReadMethod() != null) && (p.getWriteMethod() != null)) {
control = new Point2DControl(getFilter(), p.getName(), p.getWriteMethod(), p.getReadMethod());
myadd(control, name, inherited);
} else {
// log.warning("unknown property type "+p.getPropertyType()+" for property "+p.getName());
}
if (control != null) {
control.setToolTipText(getFilter().getPropertyTooltip(name));
}
} catch (Exception e) {
log.warning(e + " caught on property " + p.getName() + " from EventFilter " + filter);
}
} // properties
// groupContainerMap = null;
// sortedControls=null;
} catch (Exception e) {
log.warning("on adding controls for EventFilter " + filter + " caught " + e);
e.printStackTrace();
}
// add(Box.createHorizontalGlue());
if (ungroupedControls.getComponentCount() > 0) {
add(Box.createVerticalStrut(0));
add(ungroupedControls);
}
// now remove group containers that are not populated.
for (String s : groupContainerMap.keySet()) {
if (!populatedGroupSet.contains(s)) { // remove this group
log.info("Removing emtpy container " + s + " from " + filter.getClass().getSimpleName());
controls.remove(groupContainerMap.get(s));
remove(groupContainerMap.get(s));
}
}
add(Box.createHorizontalStrut(0)); // use up vertical space to get components to top
setControlsVisible(false);
// System.out.println("added glue to "+this);
}
void addTip(EventFilter f, JLabel label) {
String s = f.getPropertyTooltip(label.getText());
if (s == null) {
return;
}
label.setToolTipText(s);
label.setForeground(Color.BLUE);
}
void addTip(EventFilter f, AbstractButton b) {
String s = f.getPropertyTooltip(b.getText());
if (s == null) {
return;
}
b.setToolTipText(s);
b.setForeground(Color.BLUE);
}
void addTip(EventFilter f, JCheckBox label) {
String s = f.getPropertyTooltip(label.getText());
if (s == null) {
return;
}
label.setToolTipText(s);
label.setForeground(Color.BLUE);
}
class MyControl extends JPanel {
@Override
public Dimension getMaximumSize() {
Dimension d = getPreferredSize();
d.setSize(1000, d.getHeight());
return d;
}
}
class EnumControl extends MyControl implements HasSetter {
Method write, read;
EventFilter filter;
boolean initValue = false, nval;
final JComboBox control;
@Override
public void set(Object o) {
control.setSelectedItem(o);
}
public EnumControl(final Class<? extends Enum> c, final EventFilter f, final String name, final Method w, final Method r) {
super();
setterMap.put(f.getClass().getSimpleName() + "." + name, this);
filter = f;
write = w;
read = r;
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setAlignmentX(LEFT_ALIGNMENT);
final JLabel label = new JLabel(name);
label.setAlignmentX(LEFT_ALIGNMENT);
label.setFont(label.getFont().deriveFont(fontSize));
addTip(f, label);
add(label);
control = new JComboBox(c.getEnumConstants());
control.setFont(control.getFont().deriveFont(fontSize));
// control.setHorizontalAlignment(SwingConstants.LEADING);
add(label);
add(control);
add(Box.createHorizontalGlue());
try {
Object x = r.invoke(filter);
if (x == null) {
log.warning("null Object returned from read method " + r);
return;
}
control.setSelectedItem(x);
} catch (Exception e) {
log.warning("cannot access the field named " + name + " is the class or method not public?");
e.printStackTrace();
}
control.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
w.invoke(filter, control.getSelectedItem());
} catch (Exception e2) {
e2.printStackTrace();
}
}
});
}
}
class StringControl extends MyControl implements HasSetter {
Method write, read;
EventFilter filter;
boolean initValue = false, nval;
final JTextField textField;
@Override
public void set(Object o) {
if (o instanceof String) {
String b = (String) o;
textField.setText(b);
}
}
public StringControl(final EventFilter f, final String name, final Method w, final Method r) {
super();
setterMap.put(f.getClass().getSimpleName() + "." + name, this);
filter = f;
write = w;
read = r;
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setAlignmentX(LEFT_ALIGNMENT);
final JLabel label = new JLabel(name);
label.setAlignmentX(LEFT_ALIGNMENT);
label.setFont(label.getFont().deriveFont(fontSize));
addTip(f, label);
add(label);
textField = new JTextField(name);
textField.setFont(textField.getFont().deriveFont(fontSize));
textField.setHorizontalAlignment(SwingConstants.LEADING);
textField.setColumns(10);
add(label);
add(textField);
add(Box.createHorizontalGlue());
try {
String x = (String) r.invoke(filter);
if (x == null) {
log.warning("null String returned from read method " + r);
return;
}
textField.setText(x);
textField.setToolTipText(x);
} catch (Exception e) {
log.warning("cannot access the field named " + name + " is the class or method not public?");
e.printStackTrace();
}
textField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
w.invoke(filter, textField.getText());
} catch (Exception e2) {
e2.printStackTrace();
}
}
});
}
}
private final float KEY_FACTOR = (float) Math.sqrt(2), WHEEL_FACTOR = (float) Math.pow(2, 1. / 16); // factors to change by with arrow and mouse wheel
class BooleanControl extends MyControl implements HasSetter {
Method write, read;
EventFilter filter;
boolean initValue = false, nval;
final JCheckBox checkBox;
public BooleanControl(final EventFilter f, final String name, final Method w, final Method r) {
super();
setterMap.put(f.getClass().getSimpleName() + "." + name, this);
filter = f;
write = w;
read = r;
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setAlignmentX(LEFT_ALIGNMENT);
// setLayout(new FlowLayout(FlowLayout.LEADING));
checkBox = new JCheckBox(name);
checkBox.setAlignmentX(LEFT_ALIGNMENT);
checkBox.setHorizontalTextPosition(SwingConstants.LEFT);
addTip(f, checkBox);
add(checkBox);
checkBox.setFont(checkBox.getFont().deriveFont(fontSize));
// add(Box.createVerticalStrut(0));
try {
Boolean x = (Boolean) r.invoke(filter);
if (x == null) {
log.warning("null Boolean returned from read method " + r);
return;
}
initValue = x.booleanValue();
checkBox.setSelected(initValue);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
log.warning("cannot access the field named " + name + " is the class or method not public?");
e.printStackTrace();
}
checkBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
w.invoke(filter, checkBox.isSelected());
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
});
}
@Override
public void set(Object o) {
if (o instanceof Boolean) {
Boolean b = (Boolean) o;
checkBox.setSelected(b);
// check if we need to set toggle button for boolean control
for(AbstractButton but:doButList){
if(but.getText().toLowerCase().equals(checkBox.getText().toLowerCase())){
but.setSelected(b);
}
}
}
}
}
class IntSliderControl extends MyControl implements HasSetter {
Method write, read;
EventFilter filter;
int initValue = 0, nval;
JSlider slider;
JTextField tf;
private boolean sliderDontProcess = false;
@Override
public void set(Object o) {
if (o instanceof Integer) {
Integer b = (Integer) o;
slider.setValue(b);
}
}
public IntSliderControl(final EventFilter f, final String name, final Method w, final Method r, SliderParams params) {
super();
setterMap.put(f.getClass().getSimpleName() + "." + name, this);
filter = f;
write = w;
read = r;
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setAlignmentX(LEFT_ALIGNMENT);
final IntControl ic = new IntControl(f, name, w, r);
tf = ic.tf;
add(ic);
slider = new JSlider(params.minIntValue, params.maxIntValue);
slider.setMaximumSize(new Dimension(300, 50));
try {
Integer x = (Integer) r.invoke(filter); // read int value
if (x == null) {
log.warning("null Integer returned from read method " + r);
return;
}
initValue = x.intValue();
slider.setValue(initValue);
} catch (Exception e) {
log.warning("cannot access the field named " + name + " is the class or method not public?");
e.printStackTrace();
}
add(slider);
slider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (sliderDontProcess) {
return;
}
try {
w.invoke(filter, new Integer(slider.getValue())); // write int value
ic.set(slider.getValue());
// tf.setText(Integer.toString(slider.getValue()));
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
});
ic.addPropertyChangeListener(ic.PROPERTY_VALUE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent pce) {
if ((pce.getNewValue() == null) || !(pce.getNewValue() instanceof Integer)) {
return;
}
sliderDontProcess = true;
slider.setValue((Integer) (pce.getNewValue()));
sliderDontProcess = false;
}
});
}
}
class FloatSliderControl extends MyControl implements HasSetter {
Method write, read;
EventFilter filter;
JSlider slider;
JTextField tf;
EngineeringFormat engFmt;
FloatControl fc;
boolean dontProcessEvent = false; // to avoid slider callback loops
float minValue, maxValue, currentValue;
@Override
public void set(Object o) {
if (o instanceof Integer) {
Integer b = (Integer) o;
slider.setValue(b);
fc.set(b);
} else if (o instanceof Float) {
float f = (Float) o;
int sv = Math.round(((f - minValue) / (maxValue - minValue)) * (slider.getMaximum() - slider.getMinimum()));
slider.setValue(sv);
}
}
public FloatSliderControl(final EventFilter f, final String name, final Method w, final Method r, SliderParams params) {
super();
setterMap.put(f.getClass().getSimpleName() + "." + name, this);
filter = f;
write = w;
read = r;
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setAlignmentX(LEFT_ALIGNMENT);
fc = new FloatControl(f, name, w, r);
add(fc);
minValue = params.minFloatValue;
maxValue = params.maxFloatValue;
slider = new JSlider();
slider.setMaximumSize(new Dimension(200, 50));
engFmt = new EngineeringFormat();
try {
Float x = (Float) r.invoke(filter); // read int value
if (x == null) {
log.warning("null Float returned from read method " + r);
return;
}
currentValue = x.floatValue();
set(new Float(currentValue));
} catch (Exception e) {
log.warning("cannot access the field named " + name + " is the class or method not public?");
e.printStackTrace();
}
add(slider);
add(Box.createHorizontalGlue());
slider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
try {
int v = slider.getValue();
currentValue = minValue + ((maxValue - minValue) * ((float) slider.getValue() / (slider.getMaximum() - slider.getMinimum())));
w.invoke(filter, new Float(currentValue)); // write int value
fc.set(new Float(currentValue));
// tf.setText(engFmt.format(currentValue));
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
});
}
}
class IntControl extends MyControl implements HasSetter {
Method write, read;
EventFilter filter;
int initValue = 0, nval;
final JTextField tf;
String PROPERTY_VALUE = "value";
@Override
public void set(Object o) {
if (o instanceof Integer) {
Integer b = (Integer) o;
String s = NumberFormat.getIntegerInstance().format(b);
tf.setText(s);
}
}
public IntControl(final EventFilter f, final String name, final Method w, final Method r) {
super();
setterMap.put(f.getClass().getSimpleName() + "." + name, this);
filter = f;
write = w;
read = r;
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setAlignmentX(LEFT_ALIGNMENT);
// setLayout(new FlowLayout(FlowLayout.LEADING));
JLabel label = new JLabel(name);
label.setAlignmentX(LEFT_ALIGNMENT);
label.setFont(label.getFont().deriveFont(fontSize));
addTip(f, label);
add(label);
tf = new JTextField("", 8);
tf.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET);
// otherwise TAB will just pass over field without entering a new value
tf.setMaximumSize(new Dimension(100, 50));
tf.setToolTipText("Integer control: use arrow keys or mouse wheel to change value by factor. Shift constrains to simple inc/dec");
try {
Integer x = (Integer) r.invoke(filter); // read int value
if (x == null) {
log.warning("null Integer returned from read method " + r);
return;
}
initValue = x.intValue();
String s = NumberFormat.getIntegerInstance().format(initValue);
// System.out.println("init value of "+name+" is "+s);
tf.setText(s);
fixIntValue(tf, r);
} catch (Exception e) {
e.printStackTrace();
}
add(tf);
tf.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Integer newValue = null;
try {
NumberFormat format = NumberFormat.getNumberInstance();
Integer oldValue = null;
try {
oldValue = (Integer) r.invoke(filter);
} catch (Exception re) {
log.warning("could not read original value: " + re.toString());
}
int y = format.parse(tf.getText()).intValue();
newValue = new Integer(y);
w.invoke(filter, newValue); // write int value
firePropertyChange(PROPERTY_VALUE, oldValue, newValue);
} catch (ParseException pe) {
//Handle exception
} catch (NumberFormatException fe) {
tf.selectAll();
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
});
tf.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
Integer newValue = null;
Integer oldValue = null;
try {
oldValue = (Integer) r.invoke(filter);
initValue = oldValue.intValue();
// System.out.println("x="+x);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
int code = evt.getKeyCode();
int mod = evt.getModifiers();
boolean shift = evt.isShiftDown();
if (!shift) {
if (code == KeyEvent.VK_UP) {
try {
nval = initValue;
if (nval == 0) {
nval = 1;
} else {
nval = Math.round(initValue * KEY_FACTOR);
}
w.invoke(filter, newValue = new Integer(nval));
tf.setText(new Integer(nval).toString());
fixIntValue(tf, r);
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
} else if (code == KeyEvent.VK_DOWN) {
try {
nval = initValue;
if (nval == 0) {
nval = 0;
} else {
nval = Math.round(initValue / KEY_FACTOR);
}
w.invoke(filter, newValue = new Integer(nval));
tf.setText(new Integer(nval).toString());
fixIntValue(tf, r);
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
} else // shifted int control just incs or decs by 1
{
if (code == KeyEvent.VK_UP) {
try {
nval = initValue + 1;
w.invoke(filter, newValue = new Integer(nval));
tf.setText(new Integer(nval).toString());
fixIntValue(tf, r);
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
} else if (code == KeyEvent.VK_DOWN) {
try {
nval = initValue - 1;
w.invoke(filter, newValue = new Integer(nval));
tf.setText(new Integer(nval).toString());
fixIntValue(tf, r);
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
}
if (evt.getKeyCode() == KeyEvent.VK_TAB) {
try {
NumberFormat format = NumberFormat.getNumberInstance();
int y = format.parse(tf.getText()).intValue();
w.invoke(filter, newValue = new Integer(y)); // write int value
fixIntValue(tf, r);
} catch (ParseException pe) {
//Handle exception
} catch (NumberFormatException fe) {
tf.selectAll();
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.focusNextComponent();
}
firePropertyChange(PROPERTY_VALUE, oldValue, newValue);
}
}
);
tf.addMouseWheelListener(new java.awt.event.MouseWheelListener() {
@Override
public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt
) {
Integer oldValue = null, newValue = null;
try {
oldValue = (Integer) r.invoke(filter);
initValue = oldValue.intValue();
// System.out.println("x="+x);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
int code = evt.getWheelRotation();
int mod = evt.getModifiers();
boolean shift = evt.isShiftDown();
if (!shift) {
if (code < 0) {
try {
nval = initValue;
if (Math.round(initValue * WHEEL_FACTOR) == initValue) {
nval++;
} else {
nval = Math.round(initValue * WHEEL_FACTOR);
}
w.invoke(filter, newValue = new Integer(nval));
tf.setText(new Integer(nval).toString());
fixIntValue(tf, r);
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
} else if (code > 0) {
try {
nval = initValue;
if (Math.round(initValue / WHEEL_FACTOR) == initValue) {
nval
} else {
nval = Math.round(initValue / WHEEL_FACTOR);
}
if (nval < 0) {
nval = 0;
}
w.invoke(filter, newValue = new Integer(nval));
tf.setText(new Integer(nval).toString());
fixIntValue(tf, r);
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
}
firePropertyChange(PROPERTY_VALUE, oldValue, newValue);
}
}
);
tf.addFocusListener(
new FocusListener() {
@Override
public void focusGained(FocusEvent e
) {
tf.setSelectionStart(0);
tf.setSelectionEnd(tf.getText().length());
}
@Override
public void focusLost(FocusEvent e
) {
}
}
);
setMaximumSize(getPreferredSize());
}
}
void fixIntValue(JTextField tf, Method r) {
// set text to actual value
try {
Integer x = (Integer) r.invoke(getFilter()); // read int value
// initValue=x.intValue();
String s = NumberFormat.getIntegerInstance().format(x);
tf.setText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
class FloatControl extends MyControl implements HasSetter {
EngineeringFormat engFmt = new EngineeringFormat();
// final String format="%.6f";
Method write, read;
EventFilter filter;
float initValue = 0, nval;
final JTextField tf;
@Override
public void set(Object o) {
if (o instanceof Float) {
Float b = (Float) o;
tf.setText(engFmt.format(b));
} else if (o instanceof Integer) {
int b = (Integer) o;
tf.setText(engFmt.format((float) b));
}
}
public FloatControl(final EventFilter f, final String name, final Method w, final Method r) {
super();
setterMap.put(f.getClass().getSimpleName() + "." + name, this);
filter = f;
write = w;
read = r;
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setAlignmentX(LEFT_ALIGNMENT);
// setLayout(new FlowLayout(FlowLayout.LEADING));
JLabel label = new JLabel(name);
label.setAlignmentX(LEFT_ALIGNMENT);
label.setFont(label.getFont().deriveFont(fontSize));
addTip(f, label);
add(label);
tf = new JTextField("", 10);
tf.setMaximumSize(new Dimension(100, 50));
tf.setToolTipText("Float control: use arrow keys or mouse wheel to change value by factor. Shift reduces factor.");
try {
Float x = (Float) r.invoke(filter);
if (x == null) {
log.warning("null Float returned from read method " + r);
return;
}
initValue = x.floatValue();
tf.setText(engFmt.format(initValue));
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
log.warning("cannot access the field named " + name + " is the class or method not public?");
e.printStackTrace();
}
add(tf);
tf.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// System.out.println(e);
try {
float y = engFmt.parseFloat(tf.getText());
w.invoke(filter, new Float(y));
Float x = (Float) r.invoke(filter); // getString the value from the getter method to constrain it
nval = x.floatValue();
tf.setText(engFmt.format(nval));
} catch (NumberFormatException fe) {
tf.selectAll();
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
});
tf.addKeyListener(new java.awt.event.KeyAdapter() {
{
}
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
try {
Float x = (Float) r.invoke(filter); // getString the value from the getter method
initValue = x.floatValue();
// System.out.println("x="+x);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
int code = evt.getKeyCode();
int mod = evt.getModifiers();
boolean shift = evt.isShiftDown();
float floatFactor = KEY_FACTOR;
if (shift) {
floatFactor = 1 + ((WHEEL_FACTOR - 1) / 4);
}
if (code == KeyEvent.VK_UP) {
try {
nval = initValue;
if (nval == 0) {
nval = DEFAULT_REAL_VALUE;
} else {
nval = (initValue * floatFactor);
}
w.invoke(filter, new Float(nval)); // setter the value
Float x = (Float) r.invoke(filter); // getString the value from the getter method to constrain it
nval = x.floatValue();
tf.setText(engFmt.format(nval));
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
} else if (code == KeyEvent.VK_DOWN) {
try {
nval = initValue;
if (nval == 0) {
nval = DEFAULT_REAL_VALUE;
} else {
nval = (initValue / floatFactor);
}
w.invoke(filter, new Float(initValue / floatFactor));
Float x = (Float) r.invoke(filter); // getString the value from the getter method to constrain it
nval = x.floatValue();
tf.setText(engFmt.format(nval));
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
}
});
tf.addMouseWheelListener(new java.awt.event.MouseWheelListener() {
@Override
public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
try {
Float x = (Float) r.invoke(filter); // getString the value from the getter method
initValue = x.floatValue();
// System.out.println("x="+x);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
int code = evt.getWheelRotation();
int mod = evt.getModifiers();
boolean shift = evt.isShiftDown();
if (!shift) {
if (code < 0) {
try {
nval = initValue;
if (nval == 0) {
nval = DEFAULT_REAL_VALUE;
} else {
nval = (initValue * WHEEL_FACTOR);
}
w.invoke(filter, new Float(nval)); // setter the value
Float x = (Float) r.invoke(filter); // getString the value from the getter method to constrain it
nval = x.floatValue();
tf.setText(engFmt.format(nval));
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
} else if (code > 0) {
try {
nval = initValue;
if (nval == 0) {
nval = DEFAULT_REAL_VALUE;
} else {
nval = (initValue / WHEEL_FACTOR);
}
w.invoke(filter, new Float(initValue / WHEEL_FACTOR));
Float x = (Float) r.invoke(filter); // getString the value from the getter method to constrain it
nval = x.floatValue();
tf.setText(engFmt.format(nval));
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
}
}
});
tf.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
tf.setSelectionStart(0);
tf.setSelectionEnd(tf.getText().length());
}
@Override
public void focusLost(FocusEvent e) {
}
});
}
}
private boolean printedSetterWarning = false;
/**
* Called when a filter calls firePropertyChange. The PropertyChangeEvent
* should send the bound property name and the old and new values. The GUI
* control is then updated by this method.
*
* @param propertyChangeEvent contains the property that has changed, e.g.
* it would be called from an EventFilter with
* <code>support.firePropertyChange("mapEventsToLearnedTopologyEnabled", mapEventsToLearnedTopologyEnabled, this.mapEventsToLearnedTopologyEnabled);</code>
*/
@Override
public void propertyChange(final PropertyChangeEvent propertyChangeEvent) {
if (propertyChangeEvent.getSource() == getFilter()) {
if (propertyChangeEvent.getPropertyName().equals("selected")) {
return; // ignore changes to "selected" for filter because these are masked out from GUI building
} else if (propertyChangeEvent.getPropertyName().equals("filterEnabled")) { // comes from EventFilter when filter is enabled or disabled
// log.info("propertyChangeEvent name="+propertyChangeEvent.getPropertyName()+" src="+propertyChangeEvent.getSource()+" oldValue="+propertyChangeEvent.getOldValue()+" newValue="+propertyChangeEvent.getNewValue());
boolean yes = (Boolean) propertyChangeEvent.getNewValue();
enabledCheckBox.setSelected(yes);
setBorderActive(yes);
// if (yes) {
// log.info("selecting checkbox from " + propertyChangeEvent);
} else if (propertyChangeEvent.getPropertyName().startsWith("doToggleOff")) {
// handle toggle off property changes to disable buttons that may have started logging, for example
for (AbstractButton b : doButList) {
if ((b instanceof JToggleButton) && b.getText().equals(propertyChangeEvent.getPropertyName().substring(11))) {
b.setSelected(false);
}
}
} else {
// we need to find the control and set it appropriately. we don't need to set the property itself since this has already been done!
try {
// log.info("PropertyChangeEvent received from " +
// propertyChangeEvent.getSource() + " for property=" +
// propertyChangeEvent.getPropertyName() +
// " newValue=" + propertyChangeEvent.getNewValue());
final HasSetter setter = setterMap.get(getFilter().getClass().getSimpleName() + "." + propertyChangeEvent.getPropertyName());
if (setter == null) {
if (!printedSetterWarning) {
log.warning("in filter " + getFilter() + " there is no setter for property change from property named " + propertyChangeEvent.getPropertyName());
printedSetterWarning = true;
}
} else {
// log.info("setting "+setter.toString()+" to "+propertyChangeEvent.getNewValue());
if (SwingUtilities.isEventDispatchThread()) {
setter.set(propertyChangeEvent.getNewValue());
} else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
setter.set(propertyChangeEvent.getNewValue());
} catch (Exception e) {
log.warning("caught exception " + propertyChangeEvent.getNewValue() + " in property change:" + e.toString());
}
}
});
}
}
// PropertyDescriptor pd=new PropertyDescriptor(propertyChangeEvent.getPropertyName(), getFilter().getClass());
// Method wm=pd.getWriteMethod();
// wm.invoke(getFilter(), propertyChangeEvent.getNewValue());
} catch (Exception e) {
log.warning(e.toString());
}
// try{
// log.info("PropertyChangeEvent received for property="+propertyChangeEvent.getPropertyName()+" newValue="+propertyChangeEvent.getNewValue());
// PropertyDescriptor pd=new PropertyDescriptor(propertyChangeEvent.getPropertyName(), getFilter().getClass());
// Method wm=pd.getWriteMethod();
// wm.invoke(getFilter(), propertyChangeEvent.getNewValue());
// }catch(Exception e){
// log.warning(e.toString());
}
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
enableResetControlsHelpPanel = new javax.swing.JPanel();
enabledCheckBox = new javax.swing.JCheckBox();
resetButton = new javax.swing.JButton();
showControlsToggleButton = new javax.swing.JToggleButton();
setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.Y_AXIS));
enableResetControlsHelpPanel.setToolTipText("Generic controls for this EventFilter");
enableResetControlsHelpPanel.setAlignmentX(1.0F);
enableResetControlsHelpPanel.setPreferredSize(new java.awt.Dimension(100, 23));
enableResetControlsHelpPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 2));
enabledCheckBox.setFont(new java.awt.Font("Tahoma", 0, 9)); // NOI18N
enabledCheckBox.setToolTipText("Enable or disable the filter");
enabledCheckBox.setMargin(new java.awt.Insets(1, 1, 1, 1));
enabledCheckBox.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
enabledCheckBoxActionPerformed(evt);
}
});
enableResetControlsHelpPanel.add(enabledCheckBox);
resetButton.setFont(new java.awt.Font("Tahoma", 0, 9)); // NOI18N
resetButton.setText("Reset");
resetButton.setToolTipText("Resets the filter");
resetButton.setMargin(new java.awt.Insets(1, 5, 1, 5));
resetButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
resetButtonActionPerformed(evt);
}
});
enableResetControlsHelpPanel.add(resetButton);
showControlsToggleButton.setFont(new java.awt.Font("Tahoma", 0, 9)); // NOI18N
showControlsToggleButton.setText("Controls");
showControlsToggleButton.setToolTipText("Show filter parameters, hides other filters. Click again to see all filters.");
showControlsToggleButton.setMargin(new java.awt.Insets(1, 5, 1, 5));
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${controlsVisible}"), showControlsToggleButton, org.jdesktop.beansbinding.BeanProperty.create("selected"));
bindingGroup.addBinding(binding);
enableResetControlsHelpPanel.add(showControlsToggleButton);
add(enableResetControlsHelpPanel);
bindingGroup.bind();
}// </editor-fold>//GEN-END:initComponents
boolean controlsVisible = false;
public boolean isControlsVisible() {
return controlsVisible;
}
/**
* Set visibility of individual filter controls; hides other filters.
*
* @param visible true to show filter parameter controls, false to hide this
* filter's controls and to show all filters in chain.
*/
public void setControlsVisible(boolean visible) {
controlsVisible = visible;
getFilter().setSelected(visible); // exposing controls 'selects' this filter
setBorderActive(visible);
for (JComponent p : controls) {
p.setVisible(visible);
p.invalidate();
}
invalidate();
Container c = getTopLevelAncestor();
if (c == null) {
return;
}
// TODO fix bug here with enclosed filters not showing up if they are enclosed in enclosed filter, unless they are declared as enclosed
if (!getFilter().isEnclosed() && ((c instanceof Window))) {
if (c instanceof FilterFrame) {
// hide all filters except one that is being modified, *unless* we are an enclosed filter
FilterFrame<FilterPanel> ff = (FilterFrame) c;
for (FilterPanel f : ff.filterPanels) {
if (f == this) { // for us and if !visible
f.setVisible(true); // always set us visible in chain since we are the one being touched
continue;
}
f.setVisible(!visible); // hide / show other filters
}
}
// if (c instanceof Window) // Redundant
// ((Window) c).pack();
}
if (controlPanel != null) {
controlPanel.setVisible(visible);
}
// if (c instanceof Window) {
// ((Window) c).pack();
if (!getFilter().isEnclosed()) { // store last selected top level filter
if (visible) {
getFilter().getChip().getPrefs().put(FilterFrame.LAST_FILTER_SELECTED_KEY, getFilter().getClass().toString());
} else {
getFilter().getChip().getPrefs().put(FilterFrame.LAST_FILTER_SELECTED_KEY, "");
}
}
if (visible) {
// Show only controls.
showControlsToggleButton.setSelected(true);
showControlsToggleButton.setText("Back to filters list");
} else {
showControlsToggleButton.setSelected(false);
showControlsToggleButton.setText("Controls");
}
}
private void setBorderActive(final boolean yes) {
if (yes) {
((TitledBorder) getBorder()).setTitleColor(SystemColor.red);
if (!getFilter().isEnclosed()) {
titledBorder.setBorder(redLineBorder);
} else {
titledBorder.setBorder(enclosedFilterSelectedBorder);
}
} else {
((TitledBorder) getBorder()).setTitleColor(SystemColor.textInactiveText);
titledBorder.setBorder(normalBorder);
}
}
void toggleControlsVisible() {
controlsVisible = !controlsVisible;
setControlsVisible(controlsVisible);
}
public EventFilter getFilter() {
return filter;
}
public void setFilter(EventFilter filter) {
this.filter = filter;
}
/**
* Returns the FilterPanel controls for enclosed filter
*
* @param filter
* @return the panel, or null if there is no panel or the filter is not
* enclosed by this filter
*/
public FilterPanel getEnclosedFilterPanel(EventFilter filter) {
return enclosedFilterPanels.get(filter);
}
private void enabledCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enabledCheckBoxActionPerformed
boolean yes = enabledCheckBox.isSelected();
if (getFilter() != null) {
getFilter().setFilterEnabled(yes);
}
if (yes) {
((TitledBorder) getBorder()).setTitleColor(SystemColor.textHighlight);
titledBorder.setBorder(redLineBorder);
} else {
((TitledBorder) getBorder()).setTitleColor(SystemColor.textInactiveText);
titledBorder.setBorder(normalBorder);
}
repaint();
getFilter().setSelected(yes);
}//GEN-LAST:event_enabledCheckBoxActionPerformed
private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetButtonActionPerformed
if (getFilter() != null) {
getFilter().resetFilter();
}
getFilter().setSelected(true);
}//GEN-LAST:event_resetButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
protected javax.swing.JPanel enableResetControlsHelpPanel;
protected javax.swing.JCheckBox enabledCheckBox;
private javax.swing.JButton resetButton;
private javax.swing.JToggleButton showControlsToggleButton;
private org.jdesktop.beansbinding.BindingGroup bindingGroup;
// End of variables declaration//GEN-END:variables
private class SliderParams {
Class paramClass = null;
int minIntValue, maxIntValue;
float minFloatValue, maxFloatValue;
SliderParams(Class clazz, int minIntValue, int maxIntValue, float minFloatValue, float maxFloatValue) {
this.minIntValue = minIntValue;
this.minFloatValue = minFloatValue;
this.maxIntValue = maxIntValue;
this.maxFloatValue = maxFloatValue;
}
}
private SliderParams isSliderType(PropertyDescriptor p, net.sf.jaer.eventprocessing.EventFilter filter) throws SecurityException {
// if(c instanceof Class) System.out.println("filter="+filter+" propertyType="+c);
//TODO add slider control type if property has getMin and getMax methods
boolean isSliderType = false;
// check for min/max methods for property, e.g. getMinDt, getMaxDt for property dt
String propCapped = p.getName().substring(0, 1).toUpperCase() + p.getName().substring(1); // eg. Dt for dt
String minMethName = "getMin" + propCapped;
String maxMethName = "getMax" + propCapped;
SliderParams params = null;
try {
Method minMethod = filter.getClass().getMethod(minMethName, (Class[]) null);
Method maxMethod = filter.getClass().getMethod(maxMethName, (Class[]) null);
isSliderType = true;
// log.info("property " + p.getName() + " for filter " + filter + " has min/max methods, constructing slider control for it");
if (p.getPropertyType() == Integer.TYPE) {
int min = (Integer) minMethod.invoke(filter);
int max = (Integer) maxMethod.invoke(filter);
params
= new SliderParams(Integer.class, min, max, 0, 0);
} else if (p.getPropertyType() == Float.TYPE) {
float min = (Float) minMethod.invoke(filter);
float max = (Float) maxMethod.invoke(filter);
params
= new SliderParams(Integer.class, 0, 0, min, max);
}
} catch (NoSuchMethodException e) {
} catch (Exception iae) {
log.warning(iae.toString() + " for property " + p + " in filter " + filter);
}
return params;
}
class Point2DControl extends MyControl implements HasSetter {
Method write, read;
EventFilter filter;
Point2D.Float point;
float initValue = 0, nval;
final JTextField tfx, tfy;
final String format = "%.1f";
final JButton nullifyButton;
@Override
final public void set(Object o) {
if (o == null) {
tfx.setText(null);
tfy.setText(null);
} else if (o instanceof Point2D) {
Point2D b = (Point2D) o;
tfx.setText(String.format(format, b.getX()));
tfy.setText(String.format(format, b.getY()));
}
}
final class PointActionListener implements ActionListener {
Method readMethod, writeMethod;
Point2D point = new Point2D.Float(0, 0);
public PointActionListener(Method readMethod, Method writeMethod) {
this.readMethod = readMethod;
this.writeMethod = writeMethod;
}
@Override
public void actionPerformed(ActionEvent e) {
// System.out.println(e);
try {
float x = Float.parseFloat(tfx.getText());
float y = Float.parseFloat(tfy.getText());
point.setLocation(x, y);
writeMethod.invoke(filter, point);
point = (Point2D) readMethod.invoke(filter); // getString the value from the getter method to constrain it
set(point);
} catch (NumberFormatException fe) {
tfx.selectAll();
tfy.selectAll();
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
}
final class PointNullifyActionListener implements ActionListener {
Method writeMethod;
public PointNullifyActionListener(Method writeMethod) {
this.writeMethod = writeMethod;
}
@Override
public void actionPerformed(ActionEvent e) {
// System.out.println(e);
try {
Object arg = null;
writeMethod.invoke(filter, arg);
set(null);
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
}
public Point2DControl(final EventFilter f, final String name, final Method w, final Method r) {
super();
setterMap.put(name, this);
filter = f;
write = w;
read = r;
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setAlignmentX(LEFT_ALIGNMENT);
// setLayout(new FlowLayout(FlowLayout.LEADING));
JLabel label = new JLabel(name);
label.setAlignmentX(LEFT_ALIGNMENT);
label.setFont(label.getFont().deriveFont(fontSize));
addTip(f, label);
add(label);
tfx = new JTextField("", 10);
tfx.setMaximumSize(new Dimension(100, 50));
tfx.setToolTipText("Point2D X: type new value here and press enter. Set blank to set null value for Point2D.");
tfy = new JTextField("", 10);
tfy.setMaximumSize(new Dimension(100, 50));
tfy.setToolTipText("Point2D Y: type new value here and press enter. Set blank to set null value for Point2D.");
nullifyButton = new JButton("Nullify");
nullifyButton.setMaximumSize(new Dimension(100, 50));
nullifyButton.setToolTipText("Sets Point2D to null value");
try {
Point2D p = (Point2D) r.invoke(filter);
// if (p == null) {
// log.warning("null object returned from read method " + r);
// return;
set(p);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
log.warning("cannot access the field named " + name + " check if the class or method is not public?");
e.printStackTrace();
}
add(tfx);
add(new JLabel(", "));
add(tfy);
add(nullifyButton);
tfx.addActionListener(new PointActionListener(r, w));
tfy.addActionListener(new PointActionListener(r, w));
nullifyButton.addActionListener(new PointNullifyActionListener(write));
tfx.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
tfx.setSelectionStart(0);
tfx.setSelectionEnd(tfx.getText().length());
}
@Override
public void focusLost(FocusEvent e) {
}
});
tfy.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
tfy.setSelectionStart(0);
tfy.setSelectionEnd(tfy.getText().length());
}
@Override
public void focusLost(FocusEvent e) {
}
});
}
}
// Addition by Peter: Allow user to add custom filter controls
// ArrayList<JPanel> customControls=new ArrayList();
JPanel controlPanel;
public void addCustomControls(JPanel control) {
if (controlPanel == null) {
controlPanel = new JPanel();
controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.Y_AXIS));
this.add(controlPanel);
}
this.controlPanel.add(control);
// this.customControls.add(controls);
setControlsVisible(true);
// this.repaint();
// this.revalidate();
}
public void removeCustomControls() {
// for (JPanel p:customControls)
// controls.remove(p);
if (controlPanel != null) {
controlPanel.removeAll();
controlPanel.repaint();
}
// customControls.clear();
}
private ArrayList<MyControl> highlightedControls = new ArrayList();
/**
* Highlights properties that match the string s
*
* @param s
*/
public void highlightProperties(String s) {
s = s.toLowerCase();
for (MyControl c : highlightedControls) {
c.setBorder(null);
c.repaint(300);
// System.out.println("cleared "+c);
}
// System.out.println("");
highlightedControls.clear();
if (s.isEmpty()) {
return;
}
for (String propName : propertyControlMap.keySet()) {
if (propName.toLowerCase().contains(s)) {
MyControl c = propertyControlMap.get(propName);
// System.out.println("highlighted " + propName);
if (c != null) {
c.setBorder(new LineBorder(Color.red));
c.repaint(300);
highlightedControls.add(c);
}
}
}
}
// public class ShowControlsAction extends AbstractAction{
// public ShowControlsAction() {
// super("Show controls");
// putValue(SELECTED_KEY, "Hide controls");
// putValue(SHORT_DESCRIPTION,"Toggles visibility of controls of this EventFilter");
// @Override
// public void actionPerformed(ActionEvent e) {
// setControlsVisible(enabled);
}
|
package nl.sense_os.service.storage;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import nl.sense_os.service.constants.SensorData.DataPoint;
/**
* Hacky solution for parsing SQL-like queries on the LocalStorage. Normal ContentProviders will not
* need this class because they can handle these queries themselves, but our {@link LocalStorage}
* class does not.
*
* @author Steven Mulder <steven@sense-os.nl>
* @see LocalStorage
*/
public class ParserUtils {
@SuppressWarnings("unused")
private static final String TAG = "ParserUtils";
private static String fixCompareSigns(String s) {
String result = s.replaceAll(" = ", "=");
result = result.replaceAll("= ", "=");
result = result.replaceAll(" =", "=");
result = result.replaceAll(" > ", ">");
result = result.replaceAll("> ", ">");
result = result.replaceAll(" >", ">");
result = result.replaceAll(" < ", "<");
result = result.replaceAll("< ", "<");
result = result.replaceAll(" <", "<");
result = result.replaceAll(" != ", "!=");
result = result.replaceAll("!= ", "!=");
result = result.replaceAll(" !=", "!=");
return result;
}
public static String getSelectedDeviceUuid(String selection, String[] selectionArgs) {
String deviceUuid = null;
if (selection != null && selection.contains(DataPoint.DEVICE_UUID)) {
// preprocess the selection string a bit
selection = fixCompareSigns(selection);
int eqKeyStart = selection.indexOf(DataPoint.DEVICE_UUID + "='");
if (-1 != eqKeyStart) {
// selection contains "device_uuid='"
int uuidStart = eqKeyStart + (DataPoint.DEVICE_UUID + "='").length();
int uuidEnd = selection.indexOf("'", uuidStart);
uuidEnd = uuidEnd == -1 ? selection.length() - 1 : uuidEnd;
deviceUuid = selection.substring(uuidStart, uuidEnd);
}
}
return deviceUuid;
}
/**
* Tries to parse the selection String to see which data has to be returned for the query. Looks
* for occurrences of {@link DataPoint#SENSOR_NAME} and {@link DataPoint#SENSOR_DESCRIPTION} in
* the selection String.
*
* @param allSensors
* Set of all possible sensors, used to form the selection from.
* @param selection
* Selection string from the query.
* @param selectionArgs
* Selection arguments. Not used yet.
* @return List of sensor names that are included in the query.
*/
public static List<String> getSelectedSensors(Set<String> allSensors, String selection,
String[] selectionArgs) {
List<String> sensorNameMatches = getSensorNameMatches(allSensors, selection);
List<String> result = getSensorDescriptionMatches(new HashSet<String>(sensorNameMatches),
selection);
return result;
}
/**
* Tries to parse the selection String to see which data has to be returned for the query. Looks
* for occurrences of "timestamp" in the selection String.
*
* @param selection
* Selection string from the query.
* @param selectionArgs
* Selection arguments. Not used yet.
* @return Array with minimum and maximum time stamp for the query result.
*/
public static long[] getSelectedTimeRange(String selection, String[] selectionArgs) {
long minTimestamp = Long.MIN_VALUE;
long maxTimestamp = Long.MAX_VALUE;
if (selection != null && selection.contains(DataPoint.TIMESTAMP)) {
// preprocess the selection string a bit
selection = fixCompareSigns(selection);
int eqKeyStart = selection.indexOf(DataPoint.TIMESTAMP + "=");
int neqKeyStart = selection.indexOf(DataPoint.TIMESTAMP + "!=");
int leqKeyStart = selection.indexOf(DataPoint.TIMESTAMP + "<=");
int ltKeyStart = selection.indexOf(DataPoint.TIMESTAMP + "<");
int geqKeyStart = selection.indexOf(DataPoint.TIMESTAMP + ">=");
int gtKeyStart = selection.indexOf(DataPoint.TIMESTAMP + ">");
if (-1 != eqKeyStart) {
// selection contains "timestamp='"
int timestampStart = eqKeyStart + (DataPoint.TIMESTAMP + "=").length();
int timestampEnd = selection.indexOf(" ", timestampStart);
timestampEnd = timestampEnd == -1 ? selection.length() : timestampEnd;
String timestamp = selection.substring(timestampStart, timestampEnd);
if (timestamp.equals("?")) {
throw new IllegalArgumentException(
"LocalStorage cannot handle queries with arguments array, sorry...");
}
// Log.v(TAG, "Query contains: " + DataPoint.TIMESTAMP + " = " + timestamp);
minTimestamp = maxTimestamp = Long.parseLong(timestamp);
} else if (-1 != neqKeyStart) {
// selection contains "timestamp!='"
int timestampStart = neqKeyStart + (DataPoint.TIMESTAMP + "!=").length();
int timestampEnd = selection.indexOf(" ", timestampStart);
timestampEnd = timestampEnd == -1 ? selection.length() : timestampEnd;
String timestamp = selection.substring(timestampStart, timestampEnd);
if (timestamp.equals("?")) {
throw new IllegalArgumentException(
"LocalStorage cannot handle queries with arguments array, sorry...");
}
// Log.v(TAG, "Query contains: " + DataPoint.TIMESTAMP + " != " + timestamp);
// use default timestamps
}
if (-1 != geqKeyStart) {
// selection contains "timestamp>='"
int timestampStart = geqKeyStart + (DataPoint.TIMESTAMP + ">=").length();
int timestampEnd = selection.indexOf(" ", timestampStart);
timestampEnd = timestampEnd == -1 ? selection.length() : timestampEnd;
String timestamp = selection.substring(timestampStart, timestampEnd);
if (timestamp.equals("?")) {
throw new IllegalArgumentException(
"LocalStorage cannot handle queries with arguments array, sorry...");
}
// Log.v(TAG, "Query contains: " + DataPoint.TIMESTAMP + " >= " + timestamp);
minTimestamp = Long.parseLong(timestamp);
} else if (-1 != gtKeyStart) {
// selection contains "timestamp>'"
int timestampStart = gtKeyStart + (DataPoint.TIMESTAMP + ">").length();
int timestampEnd = selection.indexOf(" ", timestampStart);
timestampEnd = timestampEnd == -1 ? selection.length() : timestampEnd;
String timestamp = selection.substring(timestampStart, timestampEnd);
if (timestamp.equals("?")) {
throw new IllegalArgumentException(
"LocalStorage cannot handle queries with arguments array, sorry...");
}
// Log.v(TAG, "Query contains: " + DataPoint.TIMESTAMP + " > " + timestamp);
minTimestamp = Long.parseLong(timestamp) - 1;
}
if (-1 != leqKeyStart) {
// selection contains "timestamp<='"
int timestampStart = leqKeyStart + (DataPoint.TIMESTAMP + "<=").length();
int timestampEnd = selection.indexOf(" ", timestampStart);
timestampEnd = timestampEnd == -1 ? selection.length() : timestampEnd;
String timestamp = selection.substring(timestampStart, timestampEnd);
if (timestamp.equals("?")) {
throw new IllegalArgumentException(
"LocalStorage cannot handle queries with arguments array, sorry...");
}
// Log.v(TAG, "Query contains: " + DataPoint.TIMESTAMP + " <= " + timestamp);
maxTimestamp = Long.parseLong(timestamp);
} else if (-1 != ltKeyStart) {
// selection contains "timestamp<'"
int timestampStart = ltKeyStart + (DataPoint.TIMESTAMP + "<").length();
int timestampEnd = selection.indexOf(" ", timestampStart);
timestampEnd = timestampEnd == -1 ? selection.length() : timestampEnd;
String timestamp = selection.substring(timestampStart, timestampEnd);
if (timestamp.equals("?")) {
throw new IllegalArgumentException(
"LocalStorage cannot handle queries with arguments array, sorry...");
}
// Log.v(TAG, "Query contains: " + DataPoint.TIMESTAMP + " < " + timestamp);
maxTimestamp = Long.parseLong(timestamp) - 1;
}
} else {
// no selection: return all times
return new long[] { Long.MIN_VALUE, Long.MAX_VALUE };
}
return new long[] { minTimestamp, maxTimestamp };
}
public static int getSelectedTransmitState(String selection, String[] selectionArgs) {
int result = -1;
if (selection != null && selection.contains(DataPoint.TRANSMIT_STATE)) {
// preprocess the selection a bit
selection = selection.replaceAll(" = ", "=");
selection = selection.replaceAll("= ", "=");
selection = selection.replaceAll(" =", "=");
selection = selection.replaceAll(" != ", "!=");
selection = selection.replaceAll("!= ", "!=");
selection = selection.replaceAll(" !=", "!=");
int eqKeyStart = selection.indexOf(DataPoint.TRANSMIT_STATE + "=");
int neqKeyStart = selection.indexOf(DataPoint.TRANSMIT_STATE + "!=")
+ (DataPoint.TRANSMIT_STATE + "!=").length();
if (-1 != eqKeyStart) {
// selection contains "sensor_name='"
int stateStart = eqKeyStart + (DataPoint.TRANSMIT_STATE + "=").length();
int stateEnd = selection.indexOf(" ", stateStart);
stateEnd = stateEnd == -1 ? selection.length() - 1 : stateEnd;
String state = selection.substring(stateStart, stateEnd);
if (state.equals("?")) {
throw new IllegalArgumentException(
"LocalStorage cannot handle queries with arguments array, sorry...");
}
// Log.v(TAG, "Query contains: " + DataPoint.TRANSMIT_STATE + " = " + state + "");
result = state.equals("1") ? 1 : 0;
} else if (-1 != neqKeyStart) {
// selection contains "sensor_name!='"
int stateStart = neqKeyStart + (DataPoint.TRANSMIT_STATE + "!=").length();
int stateEnd = selection.indexOf(" ", stateStart);
stateEnd = stateEnd == -1 ? selection.length() - 1 : stateEnd;
String notState = selection.substring(stateStart, stateEnd);
if (notState.equals("?")) {
throw new IllegalArgumentException(
"LocalStorage cannot handle queries with arguments array, sorry...");
}
// Log.v(TAG, "Query contains: " + DataPoint.TRANSMIT_STATE + " != " + notState +
result = notState.equals("1") ? 0 : 1;
} else {
throw new IllegalArgumentException("Parser cannot handle selection query: "
+ selection);
}
}
return result;
}
/**
* Returns list of sensors that have match the selected sensor description. If the selection
* String does not contain {@link DataPoint#SENSOR_DESCRIPTION}, the complete list of sensors is
* returned.
*
* @param allSensors
* @param selection
* @return
*/
private static List<String> getSensorDescriptionMatches(Set<String> allSensors, String selection) {
List<String> result = new ArrayList<String>();
if (selection != null && selection.contains(DataPoint.SENSOR_DESCRIPTION)) {
// preprocess the selection string a bit
selection = fixCompareSigns(selection);
int eqKeyStart = selection.indexOf(DataPoint.SENSOR_DESCRIPTION + "='");
int neqKeyStart = selection.indexOf(DataPoint.SENSOR_DESCRIPTION + "!='")
+ (DataPoint.SENSOR_DESCRIPTION + "!='").length();
if (-1 != eqKeyStart) {
// selection contains "sensor_description='"
int descriptionStart = eqKeyStart + (DataPoint.SENSOR_DESCRIPTION + "='").length();
int descriptionEnd = selection.indexOf("'", descriptionStart);
descriptionEnd = descriptionEnd == -1 ? selection.length() - 1 : descriptionEnd;
String description = selection.substring(descriptionStart, descriptionEnd);
if (description.equals("?")) {
throw new IllegalArgumentException(
"LocalStorage cannot handle queries with arguments array, sorry...");
}
// Log.v(TAG, "Query contains: " + DataPoint.SENSOR_DESCRIPTION + " = '" +
// description + "'");
for (String key : allSensors) {
if (key.endsWith("(" + description + ")") || key.equals(description)) {
result.add(key);
}
}
} else if (-1 != neqKeyStart) {
// selection contains "sensor_description!='"
int descriptionStart = neqKeyStart
+ (DataPoint.SENSOR_DESCRIPTION + "!='").length();
int descriptionEnd = selection.indexOf("'", descriptionStart);
descriptionEnd = descriptionEnd == -1 ? selection.length() - 1 : descriptionEnd;
String notDescription = selection.substring(descriptionStart, descriptionEnd);
if (notDescription.equals("?")) {
throw new IllegalArgumentException(
"LocalStorage cannot handle queries with arguments array, sorry...");
}
// Log.v(TAG, "Query contains: " + DataPoint.SENSOR_DESCRIPTION + "!= '" +
// notDescription + "'");
for (String key : allSensors) {
if (!(key.endsWith("(" + notDescription + ")") || key.equals(notDescription))) {
result.add(key);
}
}
} else {
throw new IllegalArgumentException("Parser cannot handle selection query: "
+ selection);
}
} else {
// no selection: return all sensor names
result.addAll(allSensors);
}
// return a copy of the list of names
return new ArrayList<String>(result);
}
/**
* Returns list of sensors that have match the selected sensor name. If the selection String
* does not contain {@link DataPoint#SENSOR_NAME}, the complete list of sensors is returned.
*
* @param allSensors
* @param selection
* @return
*/
private static List<String> getSensorNameMatches(Set<String> allSensors, String selection) {
List<String> result = new ArrayList<String>();
if (selection != null && selection.contains(DataPoint.SENSOR_NAME)) {
// preprocess the selection string a bit
selection = fixCompareSigns(selection);
int eqKeyStart = selection.indexOf(DataPoint.SENSOR_NAME + "='");
int neqKeyStart = selection.indexOf(DataPoint.SENSOR_NAME + "!='")
+ (DataPoint.SENSOR_NAME + "!='").length();
if (-1 != eqKeyStart) {
// selection contains "sensor_name='"
int sensorNameStart = eqKeyStart + (DataPoint.SENSOR_NAME + "='").length();
int sensorNameEnd = selection.indexOf("'", sensorNameStart);
sensorNameEnd = sensorNameEnd == -1 ? selection.length() - 1 : sensorNameEnd;
String sensorName = selection.substring(sensorNameStart, sensorNameEnd);
if (sensorName.equals("?")) {
throw new IllegalArgumentException(
"LocalStorage cannot handle queries with arguments array, sorry...");
}
// Log.v(TAG, "Query contains: " + DataPoint.SENSOR_NAME + " = '" + sensorName +
boolean inStorage = false;
for (String key : allSensors) {
if (key.startsWith(sensorName)) {
result.add(key);
inStorage = true;
}
}
// sometimes we want to select sensors that are not currently in the storage
if (!inStorage) {
result.add(sensorName);
}
} else if (-1 != neqKeyStart) {
// selection contains "sensor_name!='"
int sensorNameStart = neqKeyStart + (DataPoint.SENSOR_NAME + "!='").length();
int sensorNameEnd = selection.indexOf("'", sensorNameStart);
sensorNameEnd = sensorNameEnd == -1 ? selection.length() - 1 : sensorNameEnd;
String notSensorName = selection.substring(sensorNameStart, sensorNameEnd);
if (notSensorName.equals("?")) {
throw new IllegalArgumentException(
"LocalStorage cannot handle queries with arguments array, sorry...");
}
// Log.v(TAG, "Query contains: " + DataPoint.SENSOR_NAME + " != '" + notSensorName +
for (String key : allSensors) {
if (!key.startsWith(notSensorName)) {
result.add(key);
}
}
} else {
throw new IllegalArgumentException("Parser cannot handle selection query: "
+ selection);
}
} else {
// no selection: return all sensor names
result.addAll(allSensors);
}
// return a copy of the list of names
return new ArrayList<String>(result);
}
private ParserUtils() {
// class should not be instantiated
}
}
|
package org.bdgp.OpenHiCAMM.Modules;
import java.awt.Component;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.prefs.Preferences;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import mmcorej.CMMCore;
import mmcorej.TaggedImage;
import org.bdgp.OpenHiCAMM.Dao;
import org.bdgp.OpenHiCAMM.ImageLog.ImageLogRecord;
import org.bdgp.OpenHiCAMM.ImageLog.ImageLogRunner;
import org.bdgp.OpenHiCAMM.Logger;
import org.bdgp.OpenHiCAMM.OpenHiCAMM;
import org.bdgp.OpenHiCAMM.Util;
import org.bdgp.OpenHiCAMM.ValidationError;
import org.bdgp.OpenHiCAMM.WorkflowRunner;
import org.bdgp.OpenHiCAMM.DB.Acquisition;
import org.bdgp.OpenHiCAMM.DB.Config;
import org.bdgp.OpenHiCAMM.DB.Image;
import org.bdgp.OpenHiCAMM.DB.ModuleConfig;
import org.bdgp.OpenHiCAMM.DB.PoolSlide;
import org.bdgp.OpenHiCAMM.DB.Slide;
import org.bdgp.OpenHiCAMM.DB.SlidePosList;
import org.bdgp.OpenHiCAMM.DB.Task;
import org.bdgp.OpenHiCAMM.DB.Task.Status;
import org.bdgp.OpenHiCAMM.DB.TaskConfig;
import org.bdgp.OpenHiCAMM.DB.TaskDispatch;
import org.bdgp.OpenHiCAMM.DB.WorkflowModule;
import org.bdgp.OpenHiCAMM.Modules.Interfaces.Configuration;
import org.bdgp.OpenHiCAMM.Modules.Interfaces.ImageLogger;
import org.bdgp.OpenHiCAMM.Modules.Interfaces.Module;
import org.json.JSONException;
import org.json.JSONObject;
import org.micromanager.dialogs.AcqControlDlg;
import org.micromanager.events.DisplayCreatedEvent;
import org.micromanager.events.EventManager;
import org.micromanager.MMOptions;
import org.micromanager.MMStudio;
import org.micromanager.acquisition.AcquisitionWrapperEngine;
import org.micromanager.acquisition.MMAcquisition;
import org.micromanager.api.Autofocus;
import org.micromanager.api.ImageCache;
import org.micromanager.api.ImageCacheListener;
import org.micromanager.api.MultiStagePosition;
import org.micromanager.api.PositionList;
import org.micromanager.api.ScriptInterface;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.MMException;
import org.micromanager.utils.MMScriptException;
import org.micromanager.utils.MMSerializationException;
import com.google.common.eventbus.Subscribe;
import static org.bdgp.OpenHiCAMM.Util.set;
import static org.bdgp.OpenHiCAMM.Util.where;
public class SlideImager implements Module, ImageLogger {
private static final long DUMMY_SLEEP = 500;
private static final boolean SANITY_CHECK = false;
WorkflowRunner workflowRunner;
WorkflowModule workflowModule;
AcqControlDlg acqControlDlg;
ScriptInterface script;
AcquisitionWrapperEngine engine;
@Override
public void initialize(WorkflowRunner workflowRunner, WorkflowModule workflowModule) {
this.workflowRunner = workflowRunner;
this.workflowModule = workflowModule;
OpenHiCAMM openhicamm = workflowRunner.getOpenHiCAMM();
this.script = openhicamm.getApp();
Preferences prefs = Preferences.userNodeForPackage(this.script.getClass());
MMOptions options = new MMOptions();
options.loadSettings();
if (this.script != null) {
this.engine = MMStudio.getInstance().getAcquisitionEngine();
this.acqControlDlg = new AcqControlDlg(this.engine, prefs, this.script, options);
}
// set initial configs
workflowRunner.getModuleConfig().insertOrUpdate(
new ModuleConfig(this.workflowModule.getId(), "canImageSlides", "yes"),
"id", "key");
}
/**
* Load the acquisition settings and get the position list from the DB
* @param conf The module configuration
* @param logger The logging module
* @return the position list, or null if no position list was found
*/
public PositionList loadPositionList(Map<String,Config> conf, Logger logger) {
Dao<Task> taskDao = this.workflowRunner.getTaskStatus();
// first try to load a position list from the posListId conf
// otherwise, try loading from the posListModuleId conf
PositionList positionList;
if (conf.containsKey("posListModule")) {
// get a sorted list of all the SlidePosList records for the posListModuleId module
Config posListModuleConf = conf.get("posListModule");
Dao<SlidePosList> posListDao = workflowRunner.getWorkflowDb().table(SlidePosList.class);
Integer slideId = new Integer(conf.get("slideId").getValue());
WorkflowModule posListModule = this.workflowRunner.getWorkflow().selectOneOrDie(
where("name",posListModuleConf.getValue()));
// get the list of slide position lists with valid task IDs or where task ID is null
List<SlidePosList> posLists = new ArrayList<>();
for (SlidePosList posList : posListDao.select(
where("slideId", slideId).
and("moduleId", posListModule.getId())))
{
if (posList.getTaskId() != null) {
Task checkTask = taskDao.selectOne(where("id",posList.getTaskId()));
if (checkTask == null) continue;
}
posLists.add(posList);
}
if (posLists.isEmpty()) {
return null;
}
// Merge the list of PositionLists into a single positionList
Collections.sort(posLists, (a,b)->a.getId()-b.getId());
positionList = posLists.get(0).getPositionList();
for (int i=1; i<posLists.size(); ++i) {
SlidePosList spl = posLists.get(i);
PositionList pl = spl.getPositionList();
for (int j=0; j<pl.getNumberOfPositions(); ++j) {
MultiStagePosition msp = pl.getPosition(j);
// sanitize the MSP label. This will be used as the directory name for each image
String label = msp.getLabel().replaceAll("[ ():,]+", ".").replaceAll("[=]+", "");
msp.setLabel(label);
positionList.addPosition(msp);
}
}
// log the position list to the console
try {
logger.fine(String.format("%s: Read position list from module %s:%n%s",
this.workflowModule.getName(), conf.get("posListModule"), positionList.serialize()));
}
catch (MMSerializationException e) {throw new RuntimeException(e);}
// load the position list into the acquisition engine
try { this.script.setPositionList(positionList); }
catch (MMScriptException e) {throw new RuntimeException(e);}
this.engine.setPositionList(positionList);
}
// otherwise, load a position list from a file
else if (conf.containsKey("posListFile")) {
Config posList = conf.get("posListFile");
logger.fine(String.format("%s: Loading position list from file: %s", this.workflowModule.getName(), Util.escape(posList.getValue())));
File posListFile = new File(posList.getValue());
if (!posListFile.exists()) {
throw new RuntimeException("Cannot find position list file "+posListFile.getPath());
}
try {
positionList = new PositionList();
positionList.load(posListFile.getPath());
try { this.script.setPositionList(positionList); }
catch (MMScriptException e) {throw new RuntimeException(e);}
this.engine.setPositionList(positionList);
}
catch (MMException e) {throw new RuntimeException(e);}
}
else {
throw new RuntimeException("No position list was given!");
}
// Load the settings and position list from the settings files
if (conf.containsKey("acqSettingsFile")) {
Config acqSettings = conf.get("acqSettingsFile");
logger.fine(String.format("%s: Loading acquisition settings from file: %s", this.workflowModule.getName(), Util.escape(acqSettings.getValue())));
File acqSettingsFile = new File(acqSettings.getValue());
if (!acqSettingsFile.exists()) {
throw new RuntimeException("Cannot find acquisition settings file "+acqSettingsFile.getPath());
}
try { acqControlDlg.loadAcqSettingsFromFile(acqSettingsFile.getPath()); }
catch (MMScriptException e) {throw new RuntimeException(e);}
}
return positionList;
}
@Subscribe public void showDisplay(DisplayCreatedEvent e) {
e.getDisplayWindow().setVisible(true);
}
@Override
public Status run(Task task, Map<String,Config> conf, Logger logger) {
// Get Dao objects ready for use
Dao<Task> taskDao = this.workflowRunner.getTaskStatus();
Dao<TaskDispatch> taskDispatchDao = this.workflowRunner.getTaskDispatch();
Dao<TaskConfig> taskConfigDao = workflowRunner.getWorkflowDb().table(TaskConfig.class);
Dao<Acquisition> acqDao = workflowRunner.getWorkflowDb().table(Acquisition.class);
Dao<Image> imageDao = workflowRunner.getWorkflowDb().table(Image.class);
Dao<Slide> slideDao = workflowRunner.getWorkflowDb().table(Slide.class);
logger.fine(String.format("Running task: %s", task));
for (Config c : conf.values()) {
logger.fine(String.format("Using configuration: %s", c));
}
// get the list of parent tasks for this task
List<Task> siblingTasks = this.workflowRunner.getTaskStatus().select(where("dispatchUUID",task.getDispatchUUID()));
Set<Task> parentTaskSet = new HashSet<>();
for (Task siblingTask : siblingTasks) {
for (TaskDispatch td : this.workflowRunner.getTaskDispatch().select(where("taskId",siblingTask.getId()))) {
parentTaskSet.addAll(this.workflowRunner.getTaskStatus().select(where("id",td.getParentTaskId())));
}
}
List<Task> parentTasks = parentTaskSet.stream().collect(Collectors.toList());
// get the slide ID
Config slideIdConf = conf.get("slideId");
Integer slideId = slideIdConf != null? new Integer(conf.get("slideId").getValue()) : null;
Slide slide = slideId != null? slideDao.selectOne(where("id", slideId)) : null;
// if this is the loadDynamicTaskRecords task, then we need to dynamically create the task records now
Config loadDynamicTaskRecordsConf = conf.get("loadDynamicTaskRecords");
if (loadDynamicTaskRecordsConf != null && loadDynamicTaskRecordsConf.getValue().equals("yes")) {
conf.put("dispatchUUID", new Config(task.getId(), "dispatchUUID", task.getDispatchUUID()));
// remove old tasks
for (Task t : taskDao.select(where("moduleId", this.workflowModule.getId()))) {
TaskConfig tc = taskConfigDao.selectOne(
where("id",t.getId()).
and("key","slideId").
and("value",slideId));
if (tc != null && t.getId() != task.getId()) {
this.workflowRunner.deleteTaskRecords(t);
}
}
workflowRunner.createTaskRecords(this.workflowModule, parentTasks, conf, logger);
return Status.SUCCESS;
}
Config imageLabelConf = conf.get("imageLabel");
if (imageLabelConf == null) throw new RuntimeException(String.format(
"Could not find imageLabel conf for task %s!", task));
String imageLabel = imageLabelConf.getValue();
logger.fine(String.format("Using imageLabel: %s", imageLabel));
int[] indices = MDUtils.getIndices(imageLabel);
if (indices == null || indices.length < 4) throw new RuntimeException(String.format(
"Invalid indices parsed from imageLabel %s", imageLabel));
// If this is the acqusition task 0_0_0_0, start the acquisition engine
if (indices[0] == 0 && indices[1] == 0 && indices[2] == 0 && indices[3] == 0) {
logger.info(String.format("Using slideId: %d", slideId));
// Make sure the acquisition control dialog was initialized
if (this.acqControlDlg == null) {
throw new RuntimeException("acqControlDlg is not initialized!");
}
// load the position list and acquistion settings
PositionList posList = this.loadPositionList(conf, logger);
if (posList == null) {
throw new RuntimeException("Could not load position list!");
}
VerboseSummary verboseSummary = getVerboseSummary();
logger.info(String.format("Verbose summary:"));
for (String line : verboseSummary.summary.split("\n")) workflowRunner.getLogger().info(String.format(" %s", line));
int totalImages = verboseSummary.channels * verboseSummary.slices * verboseSummary.frames * verboseSummary.positions;
Date startAcquisition = new Date();
// get the slide ID from the config
if (slide == null) throw new RuntimeException("No slideId found for image!");
String experimentId = slide != null? slide.getExperimentId() : null;
// get the poolSlide record if it exists
Dao<PoolSlide> poolSlideDao = this.workflowRunner.getWorkflowDb().table(PoolSlide.class);
PoolSlide poolSlide = null;
if (conf.containsKey("loadPoolSlideId")) {
poolSlide = poolSlideDao.selectOneOrDie(where("id", new Integer(conf.get("loadPoolSlideId").getValue())));
}
// set the acquisition name
// Set rootDir and acqName
String rootDir = workflowRunner.getWorkflowDir().getPath();
String acqName = String.format("acquisition_%s_%s%s%s",
new SimpleDateFormat("yyyyMMddHHmmss").format(startAcquisition),
this.workflowModule.getName(),
poolSlide != null? String.format("_C%dS%02d", poolSlide.getCartridgePosition(), poolSlide.getSlidePosition()) : "",
slide != null? String.format("_%s", slide.getName()) : "",
experimentId != null? String.format("_%s", experimentId.replaceAll("[\\/ :]+","_")) : "");
CMMCore core = this.script.getMMCore();
logger.fine(String.format("This task is the acquisition task"));
logger.info(String.format("Using rootDir: %s", rootDir));
logger.info(String.format("Requesting to use acqName: %s", acqName));
// Move stage to starting position and take some dummy pictures to adjust the camera
if (conf.containsKey("dummyImageCount") &&
posList.getNumberOfPositions() > 0)
{
Integer dummyImageCount = new Integer(conf.get("dummyImageCount").getValue());
logger.info("Moving stage to starting position");
MultiStagePosition pos = posList.getPosition(0);
SlideImager.moveStage(workflowModule.getName(), core, pos.getX(), pos.getY(), logger);
// Acquire N dummy images to calibrate the camera
for (int i=0; i<dummyImageCount; ++i) {
// Take a picture but don't save it
try { core.snapImage(); }
catch (Exception e) {throw new RuntimeException(e);}
logger.info(String.format("Acquired %d dummy images to calibrate the camera...", i+1));
// wait a second before taking the next one.
try { Thread.sleep(DUMMY_SLEEP); }
catch (InterruptedException e) {logger.info("Sleep thread was interrupted");}
}
}
// build a map of imageLabel -> sibling task record
List<TaskDispatch> tds = new ArrayList<>();
for (Task t : taskDao.select(where("moduleId", this.workflowModule.getId()))) {
TaskConfig tc = this.workflowRunner.getTaskConfig().selectOne(
where("id", t.getId()).
and("key", "slideId").
and("value", slideId));
if (tc != null) {
tds.addAll(taskDispatchDao.select(where("taskId", t.getId())));
}
}
Map<String,Task> tasks = new LinkedHashMap<String,Task>();
if (!tds.isEmpty()) {
Collections.sort(tds, new Comparator<TaskDispatch>() {
@Override public int compare(TaskDispatch a, TaskDispatch b) {
return a.getTaskId() - b.getTaskId();
}});
for (TaskDispatch t : tds) {
Task tt = taskDao.selectOneOrDie(where("id", t.getTaskId()));
TaskConfig imageLabelConf2 = taskConfigDao.selectOneOrDie(
where("id", tt.getId()).
and("key", "imageLabel"));
tasks.put(imageLabelConf2.getValue(), tt);
}
}
else {
List<Task> tts = taskDao.select(where("moduleId", this.workflowModule.getId()));
Collections.sort(tts, new Comparator<Task>() {
@Override public int compare(Task a, Task b) {
return a.getId() - b.getId();
}});
for (Task tt : tts) {
TaskConfig imageLabelConf2 = taskConfigDao.selectOneOrDie(
where("id", tt.getId()).
and("key", "imageLabel"));
tasks.put(imageLabelConf2.getValue(), tt);
}
}
// close all open acquisition windows
for (String name : MMStudio.getInstance().getAcquisitionNames()) {
try { MMStudio.getInstance().closeAcquisitionWindow(name); }
catch (MMScriptException e) { /* do nothing */ }
}
// set the initial Z Position
if (conf.containsKey("initialZPos")) {
Double initialZPos = new Double(conf.get("initialZPos").getValue());
logger.info(String.format("Setting initial Z Position to: %.02f", initialZPos));
String focusDevice = core.getFocusDevice();
final double EPSILON = 1.0;
try {
Double currentPos = core.getPosition(focusDevice);
while (Math.abs(currentPos-initialZPos) > EPSILON) {
core.setPosition(focusDevice, initialZPos);
core.waitForDevice(focusDevice);
Thread.sleep(500);
currentPos = core.getPosition(focusDevice);
}
}
catch (Exception e1) {throw new RuntimeException(e1);}
}
// Start the acquisition engine. This runs asynchronously.
try {
EventManager.register(this);
this.workflowRunner.getTaskConfig().insertOrUpdate(
new TaskConfig(task.getId(),
"startAcquisition",
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(startAcquisition)),
"id", "key");
logger.info(String.format("Now running the image acquisition sequence, please wait..."));
String returnAcqName = acqControlDlg.runAcquisition(acqName, rootDir);
if (returnAcqName == null) {
throw new RuntimeException("acqControlDlg.runAcquisition returned null acquisition name");
}
// get the prefix name and log it
JSONObject summaryMetadata = this.engine.getSummaryMetadata();
String prefix;
try { prefix = summaryMetadata.getString("Prefix"); }
catch (JSONException e) { throw new RuntimeException(e); }
logger.info(String.format("Acquisition was saved to root directory %s, prefix %s",
Util.escape(rootDir), Util.escape(prefix)));
// Write the acquisition record
Acquisition acquisition = new Acquisition(returnAcqName, prefix, rootDir);
acqDao.insertOrUpdate(acquisition,"prefix","directory");
acqDao.reload(acquisition);
logger.info(String.format("Using acquisition record: %s", acquisition));
// add an image cache listener to eagerly kick off downstream processing after each image
// is received.
ImageCache acqImageCache = this.engine.getImageCache();
acqImageCache.addImageCacheListener(new ImageCacheListener() {
@Override public void imageReceived(TaggedImage taggedImage) {
// Log how many images have been acquired so far
Set<String> taggedImages = new HashSet<String>(acqImageCache.imageKeys());
String label = MDUtils.getLabel(taggedImage.tags);
// Get the task record that should be eagerly dispatched.
Task dispatchTask = tasks.get(label);
if (dispatchTask == null) throw new RuntimeException(String.format(
"No SlideImager task was created for image with label %s!", label));
try {
if (taggedImage.pix == null) throw new RuntimeException(String.format(
"%s: taggedImage.pix is null!", label));
String positionName = null;
try { positionName = MDUtils.getPositionName(taggedImage.tags); }
catch (JSONException e) {}
taggedImages.add(label);
logger.info(String.format("Acquired image: %s [%d/%d images]",
positionName != null?
String.format("%s (%s)", positionName, label) :
label,
taggedImages.size(),
totalImages));
int[] indices = MDUtils.getIndices(label);
if (indices == null || indices.length < 4) throw new RuntimeException(String.format(
"Bad image label from MDUtils.getIndices(): %s", label));
// Don't eagerly dispatch the acquisition thread. This thread must not be set to success
// until the acquisition has finished, so the downstream processing for this task
// must wait until the acquisition has finished.
if (!(indices[0] == 0 && indices[1] == 0 && indices[2] == 0 && indices[3] == 0)) {
// Make sure the position name of this image's metadata matches what we expected
// from the Task configuration.
TaskConfig positionNameConf = taskConfigDao.selectOneOrDie(
where("id", dispatchTask.getId()).and("key", "positionName"));
if (!positionName.equals(positionNameConf.getValue())) {
throw new RuntimeException(String.format(
"Position name mismatch! TaskConfig=%s, MDUtils.getPositionName=%s",
positionNameConf, positionName));
}
// Write the image record and kick off downstream processing.
// create the image record
Image image = new Image(slideId, acquisition, indices[0], indices[1], indices[2], indices[3]);
imageDao.insertOrUpdate(image,"acquisitionId","channel","slice","frame","position");
logger.fine(String.format("Inserted/Updated image: %s", image));
imageDao.reload(image, "acquisitionId","channel","slice","frame","position");
// Store the Image ID as a Task Config variable
TaskConfig imageId = new TaskConfig(
dispatchTask.getId(),
"imageId",
new Integer(image.getId()).toString());
taskConfigDao.insertOrUpdate(imageId,"id","key");
conf.put("imageId", imageId);
logger.fine(String.format("Inserted/Updated imageId config: %s", imageId));
// eagerly run the Slide Imager task in order to dispatch downstream processing
logger.fine(String.format("Eagerly dispatching sibling task: %s", dispatchTask));
new Thread(new Runnable() {
@Override public void run() {
SlideImager.this.workflowRunner.run(dispatchTask, conf);
}}).start();
}
}
catch (Throwable e) {
dispatchTask.setStatus(Status.ERROR);
taskDao.update(dispatchTask, "id");
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
if (logger != null) logger.severe(String.format("Error working on task %s: %s",
task.toString(), sw.toString()));
throw new RuntimeException(e);
}
}
@Override public void imagingFinished(String path) { }
});
// wait until the current acquisition finishes
while (acqControlDlg.isAcquisitionRunning()) {
try { Thread.sleep(1000); }
catch (InterruptedException e) {
// if the thread is interrupted, abort the acquisition.
if (this.engine != null && this.engine.isAcquisitionRunning()) {
logger.warning("Aborting the acquisition...");
//this.engine.abortRequest();
this.engine.stop(true);
return Status.ERROR;
}
}
}
// Get the ImageCache object for this acquisition
MMAcquisition mmacquisition = acquisition.getAcquisition(acqDao);
ImageCache imageCache = mmacquisition.getImageCache();
if (imageCache == null) throw new RuntimeException("MMAcquisition object was not initialized; imageCache is null!");
// Wait for the image cache to finish...
while (!imageCache.isFinished()) {
try {
logger.info("Waiting for the ImageCache to finish...");
Thread.sleep(1000);
}
catch (InterruptedException e) {
logger.warning("Thread was interrupted while waiting for the Image Cache to finish");
return Status.ERROR;
}
}
if (!imageCache.isFinished()) throw new RuntimeException("ImageCache is not finished!");
Date endAcquisition = new Date();
this.workflowRunner.getTaskConfig().insertOrUpdate(
new TaskConfig(task.getId(),
"endAcquisition",
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(endAcquisition)),
"id", "key");
this.workflowRunner.getTaskConfig().insertOrUpdate(
new TaskConfig(task.getId(),
"acquisitionDuration",
new Long(endAcquisition.getTime() - startAcquisition.getTime()).toString()),
"id", "key");
// get the autofocus duration from the autofocus object
Autofocus autofocus = this.script.getAutofocus();
if (new HashSet<String>(Arrays.asList(autofocus.getPropertyNames())).contains("autofocusDuration")) {
try {
this.workflowRunner.getTaskConfig().insertOrUpdate(
new TaskConfig(task.getId(),
"autofocusDuration",
autofocus.getPropertyValue("autofocusDuration")),
"id", "key");
}
catch (MMException e) { throw new RuntimeException(e); }
}
// reset the autofocus settings back to defaults
autofocus.applySettings();
// Get the set of taggedImage labels from the acquisition
Set<String> taggedImages = imageCache.imageKeys();
logger.info(String.format("Found %d taggedImages: %s", taggedImages.size(), taggedImages.toString()));
// Make sure the set of acquisition image labels matches what we expected.
if (!taggedImages.equals(tasks.keySet())) {
throw new RuntimeException(String.format(
"Error: Unexpected image set from acquisition! acquisition image count is %d, expected %d!%n"+
"Verbose summary: %s%nFrom acquisition: %s%nFrom task config: %s",
taggedImages.size(), tasks.size(),
totalImages,
taggedImages, tasks.keySet()));
}
// Add any missing Image record for e.g. the acquisition task. This is also important because
// the ImageListener above is added *after* the acquisition is started, so there's a chance
// we may have missed the first few imageReceived events. This race condition is currently
// unavoidable due to the way that MMAcquisition is implemented. Any remaining SlideImager tasks
// that weren't eagerly dispatched will be dispatched normally by the workflowRunner after this
// task completes.
for (String label : taggedImages) {
// make sure none of the taggedImage.pix values are null
int[] idx = MDUtils.getIndices(label);
if (idx == null || idx.length < 4) throw new RuntimeException(String.format(
"Bad image label from MDUtils.getIndices(): %s", label));
Task t = tasks.get(label);
if (t == null) throw new RuntimeException(String.format(
"Could not get task record for image with label %s!", label));
// The following sanity checks are very time-consuming and don't seem
// to be necessary, so I've disabled them by default using the SANITY_CHECK flag.
if (SANITY_CHECK) {
TaggedImage taggedImage = imageCache.getImage(idx[0], idx[1], idx[2], idx[3]);
if (taggedImage.pix == null) throw new RuntimeException(String.format(
"%s: taggedImage.pix is null!", label));
// get the positionName
String positionName;
try { positionName = MDUtils.getPositionName(taggedImage.tags); }
catch (JSONException e) {throw new RuntimeException(e);}
// Make sure the position name of this image's metadata matches what we expected
// from the Task configuration.
TaskConfig positionNameConf = taskConfigDao.selectOneOrDie(
where("id", t.getId()).and("key", "positionName"));
if (!positionName.equals(positionNameConf.getValue())) {
throw new RuntimeException(String.format(
"Position name mismatch! TaskConfig=%s, MDUtils.getPositionName=%s",
positionNameConf, positionName));
}
}
// Insert/Update image DB record
Image image = new Image(slideId, acquisition, idx[0], idx[1], idx[2], idx[3]);
imageDao.insertOrUpdate(image,"acquisitionId","channel","slice","frame","position");
logger.fine(String.format("Inserted image: %s", image));
imageDao.reload(image, "acquisitionId","channel","slice","frame","position");
// Store the Image ID as a Task Config variable
TaskConfig imageId = new TaskConfig(
t.getId(),
"imageId",
new Integer(image.getId()).toString());
taskConfigDao.insertOrUpdate(imageId,"id","key");
conf.put(imageId.getKey(), imageId);
logger.fine(String.format("Inserted/Updated imageId config: %s", imageId));
}
}
finally {
EventManager.unregister(this);
}
}
return Status.SUCCESS;
}
@Override
public String getTitle() {
return this.getClass().getName();
}
@Override
public String getDescription() {
return this.getClass().getName();
}
@Override
public Configuration configure() {
return new Configuration() {
SlideImagerDialog slideImagerDialog = new SlideImagerDialog(acqControlDlg, SlideImager.this.workflowRunner);
@Override
public Config[] retrieve() {
List<Config> configs = new ArrayList<Config>();
if (slideImagerDialog.acqSettingsText.getText().length()>0) {
configs.add(new Config(workflowModule.getId(),
"acqSettingsFile",
slideImagerDialog.acqSettingsText.getText()));
}
if (slideImagerDialog.posListText.getText().length()>0) {
configs.add(new Config(workflowModule.getId(),
"posListFile",
slideImagerDialog.posListText.getText()));
}
if (slideImagerDialog.moduleName.getSelectedIndex()>0) {
configs.add(new Config(workflowModule.getId(),
"posListModule",
slideImagerDialog.moduleName.getSelectedItem().toString()));
}
if (slideImagerDialog.dummyImageCount.getValue() != null) {
configs.add(new Config(workflowModule.getId(),
"dummyImageCount",
slideImagerDialog.dummyImageCount.getValue().toString()));
}
if (((Double)slideImagerDialog.pixelSize.getValue()).doubleValue() != 0.0) {
configs.add(new Config(workflowModule.getId(), "pixelSize", slideImagerDialog.pixelSize.getValue().toString()));
}
if (slideImagerDialog.invertXAxisYes.isSelected()) {
configs.add(new Config(workflowModule.getId(), "invertXAxis", "yes"));
}
else if (slideImagerDialog.invertXAxisNo.isSelected()) {
configs.add(new Config(workflowModule.getId(), "invertXAxis", "no"));
}
if (slideImagerDialog.invertYAxisYes.isSelected()) {
configs.add(new Config(workflowModule.getId(), "invertYAxis", "yes"));
}
else if (slideImagerDialog.invertYAxisNo.isSelected()) {
configs.add(new Config(workflowModule.getId(), "invertYAxis", "no"));
}
if (slideImagerDialog.setInitZPosYes.isSelected()) {
configs.add(new Config(workflowModule.getId(), "initialZPos", slideImagerDialog.initialZPos.getValue().toString()));
}
return configs.toArray(new Config[0]);
}
@Override
public Component display(Config[] configs) {
Map<String,Config> conf = new HashMap<String,Config>();
for (Config config : configs) {
conf.put(config.getKey(), config);
}
if (conf.containsKey("acqSettingsFile")) {
Config acqDlgSettings = conf.get("acqSettingsFile");
slideImagerDialog.acqSettingsText.setText(acqDlgSettings.getValue());
}
if (conf.containsKey("posListFile")) {
Config posList = conf.get("posListFile");
slideImagerDialog.posListText.setText(posList.getValue());
}
if (conf.containsKey("posListModule")) {
Config posListModuleConf = conf.get("posListModule");
slideImagerDialog.moduleName.setSelectedItem(posListModuleConf.getValue());
}
if (conf.containsKey("dummyImageCount")) {
Config dummyImageCount = conf.get("dummyImageCount");
slideImagerDialog.dummyImageCount.setValue(new Integer(dummyImageCount.getValue()));
}
if (conf.containsKey("pixelSize")) {
slideImagerDialog.pixelSize.setValue(new Double(conf.get("pixelSize").getValue()));
}
if (conf.containsKey("invertXAxis")) {
if (conf.get("invertXAxis").getValue().equals("yes")) {
slideImagerDialog.invertXAxisYes.setSelected(true);
slideImagerDialog.invertXAxisNo.setSelected(false);
}
else if (conf.get("invertXAxis").getValue().equals("no")) {
slideImagerDialog.invertXAxisYes.setSelected(false);
slideImagerDialog.invertXAxisNo.setSelected(true);
}
}
if (conf.containsKey("invertYAxis")) {
if (conf.get("invertYAxis").getValue().equals("yes")) {
slideImagerDialog.invertYAxisYes.setSelected(true);
slideImagerDialog.invertYAxisNo.setSelected(false);
}
else if (conf.get("invertYAxis").getValue().equals("no")) {
slideImagerDialog.invertYAxisYes.setSelected(false);
slideImagerDialog.invertYAxisNo.setSelected(true);
}
}
if (conf.containsKey("initialZPos")) {
slideImagerDialog.setInitZPosYes.setSelected(true);
slideImagerDialog.initialZPos.setValue(new Double(conf.get("initialZPos").getValue()));
}
else {
slideImagerDialog.setInitZPosNo.setSelected(true);
slideImagerDialog.initialZPos.setValue(new Double(0.0));
}
return slideImagerDialog;
}
@Override
public ValidationError[] validate() {
List<ValidationError> errors = new ArrayList<ValidationError>();
File acqSettingsFile = new File(slideImagerDialog.acqSettingsText.getText());
if (!acqSettingsFile.exists()) {
errors.add(new ValidationError(workflowModule.getName(), "Acquisition settings file "+acqSettingsFile.toString()+" not found."));
}
if (slideImagerDialog.posListText.getText().length()>0) {
File posListFile = new File(slideImagerDialog.posListText.getText());
if (!posListFile.exists()) {
errors.add(new ValidationError(workflowModule.getName(), "Position list file "+posListFile.toString()+" not found."));
}
}
if (!((slideImagerDialog.posListText.getText().length()>0? 1: 0)
+ (slideImagerDialog.moduleName.getSelectedIndex()>0? 1: 0) == 1))
{
errors.add(new ValidationError(workflowModule.getName(),
"You must enter one of either a position list file, or a position list name."));
}
if ((Double)slideImagerDialog.pixelSize.getValue() <= 0.0) {
errors.add(new ValidationError(workflowModule.getName(),
"Pixel size must be greater than zero."));
}
return errors.toArray(new ValidationError[0]);
}
};
}
@Override
public List<Task> createTaskRecords(List<Task> parentTasks, Map<String,Config> config, Logger logger) {
Dao<Slide> slideDao = workflowRunner.getWorkflowDb().table(Slide.class);
Dao<ModuleConfig> moduleConfig = workflowRunner.getModuleConfig();
Dao<TaskConfig> taskConfigDao = workflowRunner.getTaskConfig();
// Load all the module configuration into a HashMap
Map<String,Config> moduleConf = new HashMap<String,Config>();
for (ModuleConfig c : moduleConfig.select(where("id",this.workflowModule.getId()))) {
moduleConf.put(c.getKey(), c);
workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Using module config: %s",
this.workflowModule.getName(), c));
}
// Create task records and connect to parent tasks
// If no parent tasks were defined, then just create a single task instance.
List<Task> tasks = new ArrayList<Task>();
for (Task parentTask : parentTasks.size()>0? parentTasks.toArray(new Task[]{}) : new Task[]{null})
{
workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Connecting parent task %s",
this.workflowModule.getName(), Util.escape(parentTask)));
// get the parent task configuration
Map<String,TaskConfig> parentTaskConf = new HashMap<String,TaskConfig>();
if (parentTask != null) {
for (TaskConfig c : taskConfigDao.select(where("id",parentTask.getId()))) {
parentTaskConf.put(c.getKey(), c);
workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Using task config: %s",
this.workflowModule.getName(), c));
}
}
// Get the associated slide.
Slide slide;
if (parentTaskConf.containsKey("slideId")) {
slide = slideDao.selectOneOrDie(where("id",new Integer(parentTaskConf.get("slideId").getValue())));
workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Inherited slideId %s", this.workflowModule.getName(), parentTaskConf.get("slideId")));
}
// if posListModule is set, use the most recent slide
else if (moduleConf.containsKey("posListModule")) {
List<Slide> slides = slideDao.select();
Collections.sort(slides, (a,b)->b.getId()-a.getId());
if (slides.size() > 0) {
slide = slides.get(0);
}
else {
throw new RuntimeException("No slides were found!");
}
}
// If no associated slide is registered, create a slide to represent this task
else {
String uuid = UUID.randomUUID().toString();
slide = new Slide(uuid);
slideDao.insertOrUpdate(slide,"experimentId");
slideDao.reload(slide, "experimentId");
workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created new slide: %s", this.workflowModule.getName(), slide.toString()));
}
config.put("slideId", new Config(this.workflowModule.getId(), "slideId", new Integer(slide.getId()).toString()));
// Load the position list and set the acquisition settings.
// If the position list is not yet loaded, then it will be determined at runtime.
// We will add more task records when run() is called, since the position
// list isn't ready yet.
PositionList positionList = loadPositionList(config, workflowRunner.getLogger());
if (positionList == null) {
Task task = new Task(this.workflowModule.getId(), Status.NEW);
workflowRunner.getTaskStatus().insert(task);
TaskConfig loadDynamicTaskRecordsConf = new TaskConfig(
task.getId(),
"loadDynamicTaskRecords",
"yes");
taskConfigDao.insert(loadDynamicTaskRecordsConf);
TaskConfig slideIdConf = new TaskConfig(
task.getId(),
"slideId",
new Integer(slide.getId()).toString());
taskConfigDao.insert(slideIdConf);
if (parentTask != null) {
TaskDispatch dispatch = new TaskDispatch(task.getId(), parentTask.getId());
workflowRunner.getTaskDispatch().insert(dispatch);
}
continue;
}
// count the number of ROIs
Set<String> rois = new HashSet<>();
for (MultiStagePosition msp : positionList.getPositions()) {
if (msp.getProperty("ROI") != null) {
rois.add(msp.getProperty("ROI"));
}
}
// get the total images
VerboseSummary verboseSummary = getVerboseSummary();
workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Verbose summary:", this.workflowModule.getName()));
for (String line : verboseSummary.summary.split("\n")) workflowRunner.getLogger().fine(String.format(" %s", line));
int totalImages = verboseSummary.channels * verboseSummary.slices * verboseSummary.frames * verboseSummary.positions;
workflowRunner.getLogger().fine(String.format("%s: getTotalImages: Will create %d images",
this.workflowModule.getName(), totalImages));
Config dispatchUUIDConf = config.get("dispatchUUID");
String dispatchUUID = dispatchUUIDConf != null? dispatchUUIDConf.getValue() : null;
// Create the task records
for (int c=0; c<verboseSummary.channels; ++c) {
for (int s=0; s<verboseSummary.slices; ++s) {
for (int f=0; f<verboseSummary.frames; ++f) {
for (int p=0; p<verboseSummary.positions; ++p) {
MultiStagePosition msp = positionList.getPosition(p);
if (msp == null) continue;
// Create task record
Task task = new Task(this.workflowModule.getId(), Status.NEW);
// setting the dispatch UUID is required for dynamically created
// tasks to be picked up by the workflow runner
task.setDispatchUUID(dispatchUUID);
workflowRunner.getTaskStatus().insert(task);
tasks.add(task);
workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created task record: %s",
this.workflowModule.getName(), task));
// Create taskConfig record for the image label
TaskConfig imageLabel = new TaskConfig(
task.getId(),
"imageLabel",
MDUtils.generateLabel(c, s, f, p));
taskConfigDao.insert(imageLabel);
workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created task config: %s",
this.workflowModule.getName(), imageLabel));
// Create taskConfig record for the MSP label (positionName)
TaskConfig positionName = new TaskConfig(
task.getId(),
"positionName",
msp.getLabel());
taskConfigDao.insert(positionName);
workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created task config: %s",
this.workflowModule.getName(), positionName));
// Store the MSP value as a JSON string
try {
PositionList mspPosList = new PositionList();
mspPosList.addPosition(msp);
String mspJson = new JSONObject(mspPosList.serialize()).
getJSONArray("POSITIONS").getJSONObject(0).toString();
TaskConfig mspConf = new TaskConfig(
task.getId(), "MSP", mspJson);
taskConfigDao.insert(mspConf);
moduleConf.put("MSP", mspConf);
workflowRunner.getLogger().fine(String.format(
"Inserted MultiStagePosition config: %s", mspJson));
}
catch (MMSerializationException e) {throw new RuntimeException(e);}
catch (JSONException e) {throw new RuntimeException(e);}
// Transfer MultiStagePosition property values to the task's configuration
for (String propName : msp.getPropertyNames()) {
String property = msp.getProperty(propName);
TaskConfig prop = new TaskConfig(
task.getId(), propName, property);
taskConfigDao.insert(prop);
moduleConf.put(property, prop);
workflowRunner.getLogger().fine(String.format(
"Inserted MultiStagePosition config: %s", prop));
}
// create taskConfig record for the slide ID
TaskConfig slideId = new TaskConfig(
task.getId(),
"slideId",
new Integer(slide.getId()).toString());
taskConfigDao.insert(slideId);
workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created task config: %s",
this.workflowModule.getName(), slideId));
// add some task configs to the first imaging task to assist in calculating metrics
if (c==0 && s==0 && f==0 && p==0) {
TaskConfig positionsConf = new TaskConfig(
task.getId(),
"positions",
new Integer(verboseSummary.positions).toString());
taskConfigDao.insert(positionsConf);
TaskConfig roisConf = new TaskConfig(
task.getId(),
"ROIs",
new Integer(rois.size()).toString());
taskConfigDao.insert(roisConf);
TaskConfig verboseSummaryConf = new TaskConfig(
task.getId(),
"verboseSummary",
verboseSummary.summary);
taskConfigDao.insert(verboseSummaryConf);
}
// Create task dispatch record
if (parentTask != null) {
TaskDispatch dispatch = new TaskDispatch(task.getId(), parentTask.getId());
workflowRunner.getTaskDispatch().insert(dispatch);
workflowRunner.getLogger().fine(String.format("%s: createTaskRecords: Created task dispatch record: %s",
this.workflowModule.getName(), dispatch));
}
}
}
}
}
}
return tasks;
}
public static class VerboseSummary {
public String summary;
public int frames;
public int positions;
public int slices;
public int channels;
public int totalImages;
public String totalMemory;
public String duration;
public String[] order;
}
/**
* Parse the verbose summary text returned by the AcqusitionWrapperEngine.
* Sadly, this is the only way to get some needed information since the getNumSlices(), etc.
* methods are private.
* @return the VerboseSummary object
*/
public VerboseSummary getVerboseSummary() {
String summary = this.engine.getVerboseSummary();
VerboseSummary verboseSummary = new VerboseSummary();
verboseSummary.summary = summary;
Pattern pattern = Pattern.compile("^Number of time points: ([0-9]+)$", Pattern.MULTILINE);
Matcher matcher = pattern.matcher(summary);
if (!matcher.find()) throw new RuntimeException(String.format(
"Could not parse frames field from summary:%n%s", summary));
verboseSummary.frames = new Integer(matcher.group(1));
pattern = Pattern.compile("^Number of positions: ([0-9]+)$", Pattern.MULTILINE);
matcher = pattern.matcher(summary);
if (!matcher.find()) throw new RuntimeException(String.format(
"Could not parse positions field from summary:%n%s", summary));
verboseSummary.positions = new Integer(matcher.group(1));
pattern = Pattern.compile("^Number of slices: ([0-9]+)$", Pattern.MULTILINE);
matcher = pattern.matcher(summary);
if (!matcher.find()) throw new RuntimeException(String.format(
"Could not parse slices field from summary:%n%s", summary));
verboseSummary.slices = new Integer(matcher.group(1));
pattern = Pattern.compile("^Number of channels: ([0-9]+)$", Pattern.MULTILINE);
matcher = pattern.matcher(summary);
if (!matcher.find()) throw new RuntimeException(String.format(
"Could not parse channels field from summary:%n%s", summary));
verboseSummary.channels = new Integer(matcher.group(1));
pattern = Pattern.compile("^Total images: ([0-9]+)$", Pattern.MULTILINE);
matcher = pattern.matcher(summary);
if (!matcher.find()) throw new RuntimeException(String.format(
"Could not parse total images field from summary:%n%s", summary));
verboseSummary.totalImages = new Integer(matcher.group(1));
pattern = Pattern.compile("^Total memory: ([^\\n]+)$", Pattern.MULTILINE);
matcher = pattern.matcher(summary);
if (!matcher.find()) throw new RuntimeException(String.format(
"Could not parse total memory field from summary:%n%s", summary));
verboseSummary.totalMemory = matcher.group(1).trim();
pattern = Pattern.compile("^Duration: ([^\\n]+)$", Pattern.MULTILINE);
matcher = pattern.matcher(summary);
if (!matcher.find()) throw new RuntimeException(String.format(
"Could not parse duration field from summary:%n%s", summary));
verboseSummary.duration = matcher.group(1).trim();
pattern = Pattern.compile("^Order: ([^\\n]+)$", Pattern.MULTILINE);
matcher = pattern.matcher(summary);
if (matcher.find()) {
verboseSummary.order = matcher.group(1).trim().split(",\\s*");
}
else {
this.workflowRunner.getLogger().info(String.format(
"Could not parse order field from summary:%n%s", summary));
}
return verboseSummary;
}
@Override
public TaskType getTaskType() {
return Module.TaskType.SERIAL;
}
@Override public void cleanup(Task task, Map<String,Config> config, Logger logger) { }
@Override
public List<ImageLogRecord> logImages(Task task, Map<String,Config> config, Logger logger) {
List<ImageLogRecord> imageLogRecords = new ArrayList<ImageLogRecord>();
// Add an image logger instance to the workflow runner for this module
imageLogRecords.add(new ImageLogRecord(task.getName(workflowRunner.getWorkflow()), task.getName(workflowRunner.getWorkflow()),
new FutureTask<ImageLogRunner>(new Callable<ImageLogRunner>() {
@Override public ImageLogRunner call() throws Exception {
// Get the Image record
Config imageIdConf = config.get("imageId");
if (imageIdConf != null) {
Integer imageId = new Integer(imageIdConf.getValue());
logger.info(String.format("Using image ID: %d", imageId));
Dao<Image> imageDao = workflowRunner.getWorkflowDb().table(Image.class);
Image image = imageDao.selectOneOrDie(where("id",imageId));
logger.info(String.format("Using image: %s", image));
// Initialize the acquisition
Dao<Acquisition> acqDao = workflowRunner.getWorkflowDb().table(Acquisition.class);
Acquisition acquisition = acqDao.selectOneOrDie(where("id",image.getAcquisitionId()));
logger.info(String.format("Using acquisition: %s", acquisition));
MMAcquisition mmacquisition = acquisition.getAcquisition(acqDao);
// Get the image cache object
ImageCache imageCache = mmacquisition.getImageCache();
if (imageCache == null) throw new RuntimeException("Acquisition was not initialized; imageCache is null!");
// Get the tagged image from the image cache
TaggedImage taggedImage = image.getImage(imageCache);
logger.info(String.format("Got taggedImage from ImageCache: %s", taggedImage));
ImageLogRunner imageLogRunner = new ImageLogRunner(task.getName(workflowRunner.getWorkflow()));
imageLogRunner.addImage(taggedImage, "The image");
return imageLogRunner;
}
return null;
}
})));
return imageLogRecords;
}
@Override
public void runInitialize() { }
public synchronized static double[] moveStage(String moduleId, CMMCore core, double x, double y, Logger logger) {
core.setTimeoutMs(10000);
String xyStage = core.getXYStageDevice();
int move_tries = 0;
final int MOVE_MAX_TRIES = 10;
Throwable err = new RuntimeException("Unknown exception");
while (move_tries++ < MOVE_MAX_TRIES) {
try {
if (logger != null) logger.fine(String.format("%s: Moving stage to position: (%f,%f)", moduleId, x, y));
// get the stage coordinates
// sometimes moving the stage throws, try at least 10 times
double[] x_stage = new double[] {0.0};
double[] y_stage = new double[] {0.0};
int tries = 0;
final int MAX_TRIES = 10;
while(tries <= MAX_TRIES) {
try {
core.getXYPosition(xyStage, x_stage, y_stage);
break;
}
catch (Throwable e) {
if (tries >= MAX_TRIES) throw new RuntimeException(e);
}
Thread.sleep(500);
++tries;
}
if (logger != null) logger.fine(String.format("%s: Current stage position: (%f,%f)", moduleId, x_stage[0], y_stage[0]));
// set the stage coordinates
tries = 0;
while(tries <= MAX_TRIES) {
try {
core.setXYPosition(xyStage, x, y);
break;
}
catch (Throwable e) {
if (tries >= MAX_TRIES) throw new RuntimeException(e);
}
Thread.sleep(500);
++tries;
}
// wait for the stage to finish moving
final long MAX_WAIT = 10000000000L; // 10 seconds
long startTime = System.nanoTime();
while (core.deviceBusy(xyStage)) {
if (MAX_WAIT < System.nanoTime() - startTime) {
// If it's taking too long to move the stage,
// try re-sending the stage movement command.
if (logger != null) logger.warning(String.format("%s: Stage is taking too long to move, re-sending stage move commands...", moduleId));
core.stop(xyStage);
Thread.sleep(500);
startTime = System.nanoTime();
core.setXYPosition(xyStage, x, y);
}
Thread.sleep(5);
}
// get the new stage coordinates
double[] x_stage_new = new double[] {0.0};
double[] y_stage_new = new double[] {0.0};
tries = 0;
while(tries <= MAX_TRIES) {
try {
core.getXYPosition(xyStage, x_stage_new, y_stage_new);
break;
}
catch (Throwable e) {
if (tries >= MAX_TRIES) throw new RuntimeException(e);
}
Thread.sleep(500);
++tries;
}
// make sure the stage moved to the correct coordinates
if (logger != null) logger.fine(String.format("%s: New stage position: (%f,%f)", moduleId, x_stage_new[0], y_stage_new[0]));
final double EPSILON = 1000;
if (!(Math.abs(x_stage_new[0]-x) < EPSILON && Math.abs(y_stage_new[0]-y) < EPSILON)) {
throw new RuntimeException(String.format("%s: Stage moved to wrong coordinates: (%.2f,%.2f)",
moduleId, x_stage_new[0], y_stage_new[0]));
}
// return the new stage coordinates
return new double[]{x_stage_new[0], y_stage_new[0]};
}
catch (Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
if (logger != null) logger.severe(String.format("%s: Failed to move stage to position (%.2f,%.2f): %s", moduleId, x,y, sw.toString()));
err = e;
}
try { Thread.sleep(1000); }
catch (InterruptedException e) { /* do nothing */ }
}
throw new RuntimeException(err);
}
public Status setTaskStatusOnResume(Task task) {
// if this is the dummy loadDynamicTaskRecords task, check if this imaging needs to be redone.
// Check the associated ROI finder module's task statuses for this slide
TaskConfig loadDynamicTaskRecordsConf = this.workflowRunner.getTaskConfig().selectOne(
where("id", task.getId()).
and("key", "loadDynamicTaskRecords").
and("value","yes"));
if (loadDynamicTaskRecordsConf != null) {
ModuleConfig posListModuleConf = this.workflowRunner.getModuleConfig().selectOne(
where("id", this.workflowModule.getId()).
and("key", "posListModule"));
if (posListModuleConf != null) {
WorkflowModule posListModule = this.workflowRunner.getWorkflow().selectOneOrDie(
where("name", posListModuleConf.getValue()));
TaskConfig slideIdConf = this.workflowRunner.getTaskConfig().selectOneOrDie(
where("id", task.getId()).
and("key", "slideId"));
Integer slideId = new Integer(slideIdConf.getValue());
for (Task t : this.workflowRunner.getTaskStatus().select(where("moduleId", posListModule.getId()))) {
if (this.workflowRunner.getTaskConfig().selectOne(
where("id", t.getId()).
and("key", "slideId").
and("value", slideId)) != null)
{
if (t.getStatus() != Status.SUCCESS) {
return Status.NEW;
}
}
}
}
return null;
}
// Handle normal tasks
TaskConfig imageLabelConf = this.workflowRunner.getTaskConfig().selectOne(
where("id", task.getId()).
and("key", "imageLabel"));
if (imageLabelConf == null) throw new RuntimeException(String.format(
"Could not find imageLabel conf for task %s!", task));
String imageLabel = imageLabelConf.getValue();
int[] indices = MDUtils.getIndices(imageLabel);
if (indices == null || indices.length < 4) throw new RuntimeException(String.format(
"Invalid indices parsed from imageLabel %s", imageLabel));
if (indices[0] == 0 && indices[1] == 0 && indices[2] == 0 && indices[3] == 0) {
// get this slide ID
TaskConfig slideIdConf = this.workflowRunner.getTaskConfig().selectOne(
where("id", task.getId()).
and("key", "slideId"));
Integer slideId = slideIdConf != null? new Integer(slideIdConf.getValue()) : null;
// if this task has a slide ID
if (slideId != null) {
// get all tasks with same slide ID as this one
List<TaskConfig> sameSlideId = this.workflowRunner.getTaskConfig().select(
where("key", "slideId").
and("value", slideId));
List<Task> tasks = new ArrayList<>();
for (TaskConfig tc : sameSlideId) {
tasks.addAll(this.workflowRunner.getTaskStatus().select(
where("id", tc.getId()).
and("moduleId", task.getModuleId())));
}
for (Task t : tasks) {
if (this.workflowRunner.getTaskConfig().selectOne(
where("id", t.getId()).
and("key", "loadDynamicTaskRecords").
and("value", "yes")) == null)
{
if (t.getStatus() != Status.SUCCESS ||
this.workflowRunner.getTaskConfig().selectOne(
where("id", t.getId()).
and("key", "imageId")) == null)
{
for (Task t2 : tasks) {
this.workflowRunner.getTaskStatus().update(
set("status", Status.NEW).
and("dispatchUUID", null),
where("id", t2.getId()));
}
return Status.NEW;
}
}
}
}
else {
// get all tasks without a defined slide ID
List<Task> tasks = new ArrayList<>();
for (Task t : this.workflowRunner.getTaskStatus().select(where("moduleId", task.getModuleId()))) {
TaskConfig tc = this.workflowRunner.getTaskConfig().selectOne(
where("id", t.getId()).
and("key", "slideId"));
if (tc == null) tasks.add(t);
}
for (Task t : tasks) {
if (t.getStatus() != Status.SUCCESS) {
for (Task t2 : tasks) {
this.workflowRunner.getTaskStatus().update(
set("status", Status.NEW).
and("dispatchUUID", null),
where("id", t2.getId()));
}
return Status.NEW;
}
}
}
}
return null;
}
}
|
package org.beanmaker.util;
import org.dbbeans.util.Pair;
import org.dbbeans.util.Strings;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.List;
public abstract class BeanMakerBaseServlet extends HttpServlet {
@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
abstract protected void processRequest(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException;
protected String getRootPath() {
return getServletContext().getRealPath("/");
}
protected String getErrorsInJson(final List<ErrorMessage> errorMessages) {
final StringBuilder buf = new StringBuilder();
buf.append("{ \"ok\": false, \"errors\": [ ");
for (ErrorMessage errorMessage: errorMessages)
buf.append(errorMessage.toJson()).append(", ");
buf.delete(buf.length() - 2, buf.length());
buf.append(" ] }");
return buf.toString();
}
protected long getBeanId(final HttpServletRequest request, final String parameterName) {
return Strings.getLongVal(request.getParameter(parameterName));
}
protected String getJsonSimpleStatus(final String status) {
return "{ \"status\": \"" + status + "\" }";
}
protected String getJsonOk() {
return getJsonSimpleStatus("ok");
}
protected String getJsonNoSession() {
return getJsonSimpleStatus("no session");
}
protected String getStartJsonErrors() {
return "{ \"status\": \"errors\", ";
}
protected Pair<String, Long> getSubmittedFormAndId(final HttpServletRequest request) throws ServletException {
String form = null;
long id = 0;
int count = 0;
final Enumeration<String> params = request.getParameterNames();
while (params.hasMoreElements()) {
final String param = params.nextElement();
if (param.startsWith("submitted")) {
++count;
form = param.substring(9, param.length());
id = Strings.getLongVal(request.getParameter(param));
}
}
if (count > 1)
throw new ServletException("More than one submittedXXX parameter.");
return new Pair<String, Long>(form, id);
}
protected String processBean(final HttpServletRequest request, final DbBeanHTMLViewInterface htmlView) {
htmlView.setAllFields(request);
if (htmlView.isDataOK()) {
htmlView.updateDB();
return getJsonOk();
}
return getStartJsonErrors() + ErrorMessage.toJson(htmlView.getErrorMessages()) + " }";
}
protected Pair<String, Long> getBeanAndId(final HttpServletRequest request) throws ServletException {
final String beanName = getBeanName(request);
final long id = getBeanId(request, "id");
if (id == 0)
throw new ServletException("Missing id parameter or id == 0");
return new Pair<String, Long>(beanName, id);
}
protected Pair<String, String> getBeanAndCode(final HttpServletRequest request) throws ServletException {
final String beanName = getBeanName(request);
final String code = request.getParameter("id");
if (code == null)
throw new ServletException("Missing id parameter");
return new Pair<String, String>(beanName, code);
}
private String getBeanName(final HttpServletRequest request) throws ServletException {
final String beanName = request.getParameter("bean");
if (beanName == null)
throw new ServletException("Missing bean parameter.");
return beanName;
}
protected String deleteBean(final DbBeanInterface bean) {
bean.delete();
return getJsonOk();
}
protected void disableCaching(final HttpServletResponse response) {
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
}
protected int getItemOrderDirectionChangeParameter(HttpServletRequest request) throws ServletException {
final String direction = request.getParameter("direction");
if (direction == null)
throw new ServletException("Missing direction parameter");
return Strings.getIntVal(direction);
}
protected String singleStepItemOrderChangeFor(final DbBeanWithItemOrderInterface bean, final int direction) {
if (direction == 0)
throw new IllegalArgumentException(
"Illegal direction parameter value: must be a non zero positive or negative integer.");
if (direction > 0)
bean.itemOrderMoveUp();
else
bean.itemOrderMoveDown();
return getJsonOk();
}
protected String getErrorMessageContainerHtml(final String idContainer) {
return getErrorMessageContainerHtml(idContainer, "error-message-container");
}
protected String getErrorMessageContainerHtml(final String idContainer, final String cssClass) {
return "<div id='" + idContainer + "' class='" + cssClass + "'></div>";
}
}
|
package com.yhy.tpg.adapter;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import com.yhy.tpg.config.PagerConfig;
import com.yhy.tpg.pager.TpgFragment;
import com.yhy.tpg.cache.PagerCache;
import com.yhy.tpg.widget.TpgView;
public abstract class TpgAdapter extends FragmentStatePagerAdapter {
private PagerConfig mConfig;
private PagerCache mCache;
private TpgView mTpgView;
/**
*
*
* @param fm FragmentManager
*/
public TpgAdapter(FragmentManager fm) {
this(fm, null);
}
/**
*
*
* @param fm FragmentManager
* @param config
*/
public TpgAdapter(FragmentManager fm, PagerConfig config) {
super(fm);
mConfig = config;
mCache = new PagerCache();
}
public void bindTpgView(TpgView tpgView) {
mTpgView = tpgView;
}
public void retryLoadDataForCurrentPager() {
if (null != mCache && null != mTpgView) {
TpgFragment pager = mCache.getPager(mTpgView.getCurrentPager());
if (null != pager) {
pager.shouldLoadData();
}
}
}
@Override
public abstract CharSequence getPageTitle(int position);
@Override
public TpgFragment getItem(int position) {
TpgFragment pager = null;
if (null != mCache) {
pager = mCache.getPager(position);
if (null != pager) {
return pager;
}
}
pager = getPager(position);
mCache.savePager(position, pager);
pager.setPagerConfig(mConfig);
return pager;
}
@Override
public abstract int getCount();
@Override
public int getItemPosition(Object object) {
//POSITION_NONEnotifyDataSetChanged()ViewPager
return POSITION_NONE;
}
/**
*
*
* @param position
* @return
*/
public abstract TpgFragment getPager(int position);
/**
*
*
* @return
*/
public PagerCache getPagerCache() {
return mCache;
}
/**
*
*
* @param index
* @param args
*/
public void reloadDataForPager(int index, Object... args) {
TpgFragment pager = mCache.getPager(index);
if (null != pager) {
pager.reloadDate(args);
}
}
/**
*
*
* @param args
*/
public void reloadDataForCurrentPager(Object... args) {
reloadDataForPager(mTpgView.getCurrentPager(), args);
}
}
|
package demo;
import demo.HandGui;
import demo.Fallen.SimpleColorTableModel;
import demo.DeckGui;
import demo.CardGui;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.LinearGradientPaint;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Ellipse2D;
import java.beans.PropertyVetoException;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.swing.border.CompoundBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.SoftBevelBorder;
import data.LoadData;
import javax.swing.border.BevelBorder;
import javax.swing.UIManager;
import javax.swing.border.MatteBorder;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.FontMetrics;
import javax.swing.SwingConstants;
import javax.swing.JSlider;
import java.awt.Canvas;
import javax.swing.border.EtchedBorder;
import javax.swing.JTextPane;
import java.awt.Rectangle;
import javax.swing.JLayeredPane;
public class PlayerGui extends JLayeredPane implements ActionListener, MouseListener {
public Barriers barriers;
public Drained powers;
public static DeckGui deck;
public Previewpane preview;
public HandGui hand;
public fieldGui field;
public AIGui ai;
int turn;
int acampo=-1;
int i=0;
private Fallen fallen ;
private LoadData cartas;
JInternalFrame pane;
private Phases phases;
public JButton changePhase;
public int getPhaseActual(){
return phases.actual;
}
public PlayerGui(int x , int y, String name) throws IOException {
setBorder(null);
preview= new Previewpane();
setBackground(UIManager.getColor("Button.disabledShadow"));
hand= new HandGui (0,0);
hand.setLocation(179, 510);
hand.addMouseListener(this);
setOpaque(false);
setLayout(null);
setBounds(x,y, 1024, 768);
JLabel name_1 = new JLabel("Player : "+ name);
add(name_1);
name_1.setForeground(new Color(255, 248, 220));
name_1.setBackground(Color.WHITE);
name_1.setHorizontalAlignment(SwingConstants.CENTER);
name_1.setFont(new Font("Showcard Gothic", Font.BOLD | Font.ITALIC, 11));
name_1.setBounds(780, 450, 176, 64);
pane = new JInternalFrame("THE FALLEN");
phases=new Phases(200,290);
add(phases);
this.add(hand);
field = new fieldGui(220,350);
ai = new AIGui();
field.addMouseListener(this);
this.add(field);
add(ai);
powers=new Drained(15,320);
add(powers);
deck = new DeckGui(0,0);
deck.setSize(250, 343);
deck.setLocation(770, 361);
this.add(deck);
this.add(preview);
barriers =new Barriers(179,500);
add(barriers);
barriers.addMouseListener(this);
for(int i=1;i<=5;i++)
{
int pos= hand.draw(deck.Deck.extraerR());
//hand.handgui[pos-1].addMouseListener(this); //DE HAND A FIELD
deck.textField.setText("cards left "+ deck.Deck.cardsLeft());
deck.textField.repaint();
repaint();
}
for (int i=0;i<5;i++)
//barriers.barriers[i].addMouseListener(this); //DE BARRIERS A HAND
fallen=new Fallen();
add(fallen);
juego();
}
//este sera nuestro manejador de juego, aca estara todas las condiciones y cosas de las phases
public void juego()
{
this.changePhase = new JButton("cambiar");
this.changePhase.setBounds(450, 80, 90, 20);
this.changePhase.setVisible(true);
this.add(this.changePhase);
this.changePhase.addActionListener(this);
/*
* por defecto se desabilitaran todos los eventos del clic del juego y acciones
* (esto esta pensado sin la integracion del modulo de eventos, eso se agrega aca en las phases necesarias y ya)
*
* lo que se puede hacer en el juego es lo siguiente
* sacar card a barrier
* sacar card a hand
* colocar cartas
* atacar
* pasar de turno
*
* en cada phase se ira habilitando cada una de estas funcionalidades, para que el jugagor disponga de ellas
*
* y esta secuencia de phases se elaborara en un cliclo infinito hasta que uno o los dos players
* tengan una lp <= 0
* */
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==deck.btnNewButton_1)
{
fallen.setVisible(true);
moveToFront(fallen);
}
if(e.getSource()==changePhase){
if(phases.actual<5)
phases.change(phases.actual+1);
else
phases.change(0);
switch(phases.actual){
//setup
case 0:
//enable deck
//disable barriers
for (int i=0;i<5;i++)
barriers.barriers[i].removeMouseListener(this);
//disable hand
for(int i=0;i<5;i++)
hand.handgui[i].removeMouseListener(this);
//disable field
//disable battle phase
//disable end turn
break;
//draw
case 1:
//disable deck: done
//enable barriers
for (int i=0;i<5;i++)
barriers.barriers[i].addMouseListener(this);
//disable hand
for(int i=0;i<5;i++)
hand.handgui[i].removeMouseListener(this);
//disable field
//disable battle phase
//disable end turn
break;
//action
case 2:
//disable deck: done
//disable barriers
for (int i=0;i<5;i++)
barriers.barriers[i].removeMouseListener(this);
//enable hand
for(int i=0;i<5;i++)
hand.handgui[i].addMouseListener(this);
//enable field
//disable battle phase
//disable end turn
break;
//attack
case 3:
//disable deck: done
//disable barriers
for (int i=0;i<5;i++)
barriers.barriers[i].removeMouseListener(this);
//disable hand
for(int i=0;i<5;i++)
hand.handgui[i].removeMouseListener(this);
//enable field
//enable battle phase
//disable end turn
break;
//end turn
case 4:
//disable deck: done
//disable barriers
for (int i=0;i<5;i++)
barriers.barriers[i].removeMouseListener(this);
//disable hand
for(int i=0;i<5;i++)
hand.handgui[i].removeMouseListener(this);
//disable field
//disable battle phase
//enable end turn
break;
}
repaint();
}
}
public class CirclePanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
g.drawOval(0, 0, g.getClipBounds().width, g.getClipBounds().height);
}
}
public DeckGui getDeck() {
return deck;
}
public void mouseClicked(MouseEvent e)
{
int where;
if(e.getButton() == MouseEvent.BUTTON1)
{if(e.getClickCount()==1)
{
if(e.getSource()==barriers.barriers[0])
{
int pos= hand.draw(barriers.cards[0]);
hand.handgui[pos-1].addMouseListener(this);
barriers.removebarrier(0);
repaint();
}
if(e.getSource()==barriers.barriers[1])
{
int pos= hand.draw(barriers.cards[1]);
hand.handgui[pos-1].addMouseListener(this);
barriers.removebarrier(1);
repaint();
}
if(e.getSource()==barriers.barriers[2])
{
int pos= hand.draw(barriers.cards[2]);
hand.handgui[pos-1].addMouseListener(this);
barriers.removebarrier(2);
repaint();
}
if(e.getSource()==barriers.barriers[3])
{
int pos= hand.draw(barriers.cards[3]);
hand.handgui[pos-1].addMouseListener(this);
barriers.removebarrier(3);
repaint();
}
if(e.getSource()==barriers.barriers[4])
{
int pos= hand.draw(barriers.cards[4]);
hand.handgui[pos-1].addMouseListener(this);
barriers.removebarrier(4);
repaint();
}
}
if(e.getClickCount()==2)
{
if(e.getSource()==hand.handgui[0])
{
acampo=0;
}
else if(e.getSource()==hand.handgui[1])
{
acampo=1;
}
else if(e.getSource()==hand.handgui[2])
{
acampo=2;
}
else if(e.getSource()==hand.handgui[3])
{
acampo=3;
}else if(e.getSource()==hand.handgui[4])
{
acampo=4;
}
if(acampo!=-1)
{
where=field.findwhere();
if(where!=-1)
{
SmallCard carta;
Reverse volteada;
try {
Random randomGenerator = new Random();
int test=randomGenerator.nextInt(10);
if(test % 2==0)
{
carta = new SmallCard(true,hand.handgui[acampo].getcard());
volteada=new Reverse(true,hand.handgui[acampo].getcard());
}else{
carta = new SmallCard(false,hand.handgui[acampo].getcard());
volteada=new Reverse(false,hand.handgui[acampo].getcard());
}
powers.undrain(hand.handgui[acampo].getcard().GetCost());
repaint();
carta.addMouseListener(this);
volteada.addMouseListener(this);
field.poner(carta,where);
hand.discard(acampo+1);
ai.aifield.poner(volteada, where);
repaint();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
acampo=-1;
}
}
}
}
else if(e.getButton() == MouseEvent.BUTTON3)
{
if(e.getClickCount()==1)
{
if(e.getSource()==hand.handgui[0])
{
fallen.populate((SimpleColorTableModel) fallen.leftTable.getModel(),hand.cards[0]);
hand.discard(1);
}
if(e.getSource()==hand.handgui[1])
{
fallen.populate((SimpleColorTableModel) fallen.leftTable.getModel(),hand.cards[1]);
hand.discard(2);
}
if(e.getSource()==hand.handgui[2])
{
fallen.populate((SimpleColorTableModel) fallen.leftTable.getModel(),hand.cards[2]);
hand.discard(3);
}
if(e.getSource()==hand.handgui[3])
{
fallen.populate((SimpleColorTableModel) fallen.leftTable.getModel(),hand.cards[3]);
hand.discard(4);
}
if(e.getSource()==hand.handgui[4])
{
fallen.populate((SimpleColorTableModel) fallen.leftTable.getModel(),hand.cards[4]);
hand.discard(5);
}
if(e.getSource()==field.cards[0])
{
powers.drain(field.cards[0].getcard().GetCost());
fallen.populate((SimpleColorTableModel) fallen.leftTable.getModel(),field.cards[0].getcard());
field.quitar(0);
}
if(e.getSource()==field.cards[1])
{
fallen.populate((SimpleColorTableModel) fallen.leftTable.getModel(),field.cards[1].getcard());
powers.drain(field.cards[1].getcard().GetCost());
field.quitar(1);
}
if(e.getSource()==field.cards[2])
{
fallen.populate((SimpleColorTableModel) fallen.leftTable.getModel(),field.cards[2].getcard());
powers.drain(field.cards[2].getcard().GetCost());
field.quitar(2);
}
if(e.getSource()==field.cards[3])
{
fallen.populate((SimpleColorTableModel) fallen.leftTable.getModel(),field.cards[3].getcard());
powers.drain(field.cards[3].getcard().GetCost());
field.quitar(3);
}if(e.getSource()==field.cards[4])
{
fallen.populate((SimpleColorTableModel) fallen.leftTable.getModel(),field.cards[4].getcard());
powers.drain(field.cards[4].getcard().GetCost());
field.quitar(4);
}
}
}
}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e) {
}
public void mouseDragged(MouseEvent e)
{
}
public void mouseExited(MouseEvent e) {
if(e.getSource()==hand.handgui[0])
{
hand.handgui[0].setBounds(0, 20, 124, 186);
preview.Remove();
}
else if(e.getSource()==hand.handgui[1])
{
hand.handgui[1].setBounds(124, 20, 124, 186);
preview.Remove();
}
else if(e.getSource()==hand.handgui[2])
{
hand.handgui[2].setBounds(248, 20, 124, 186);
preview.Remove();
}
else if(e.getSource()==hand.handgui[3])
{
hand.handgui[3].setBounds(372, 20, 124, 186);
preview.Remove();
}else if(e.getSource()==hand.handgui[4])
{
hand.handgui[4].setBounds(496, 20, 124, 186);
preview.Remove();
}
}
public void mouseMoved(MouseEvent e) {
}
public void mouseEntered(MouseEvent e)
{
if(e.getSource()==hand.handgui[0])
{
hand.handgui[0].setBounds(0, 0, 124, 186);
preview.addCard(new BigCard(hand.handgui[0].getcard(),0,0));
}
else if(e.getSource()==hand.handgui[1])
{
hand.handgui[1].setBounds(124, 0, 124, 186);
preview.addCard(new BigCard(hand.handgui[1].getcard(),0,0));
}
else if(e.getSource()==hand.handgui[2])
{
hand.handgui[2].setBounds(248, 0, 124, 186);
preview.addCard(new BigCard(hand.handgui[2].getcard(),0,0));
}
else if(e.getSource()==hand.handgui[3])
{
hand.handgui[3].setBounds(372, 0, 124, 186);
preview.addCard(new BigCard(hand.handgui[0].getcard(),0,0));
}else if(e.getSource()==hand.handgui[4])
{
hand.handgui[4].setBounds(496, 0, 124, 186);
preview.addCard(new BigCard(hand.handgui[4].getcard(),0,0));
}
}
}
|
package org.biojava.bio.dist;
import java.util.*;
import java.io.*;
import org.biojava.utils.*;
import org.biojava.bio.*;
import org.biojava.bio.symbol.*;
/**
* A simple implementation of a distribution, which works with any finite alphabet.
*
* @author Matthew Pocock
* @author Thomas Down
* @author Mark Schreiber
* @serial WARNING serilized versions of this class may not be compatible with later versions of BioJava
*/
public class SimpleDistribution
extends AbstractDistribution implements Serializable{
private transient AlphabetIndex indexer;
private transient double[] weights = null;//because indexer is transient.
private Distribution nullModel;
private FiniteAlphabet alpha;
//Change this value if you change this class substantially
private static final long serialVersionUID = 899744356;
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException{
stream.defaultReadObject();
indexer = AlphabetManager.getAlphabetIndex(alpha);
indexer.addChangeListener(
new ChangeAdapter(){
public void preChange(ChangeEvent ce) throws ChangeVetoException{
if(hasWeights()){
throw new ChangeVetoException(
ce,
"Can't allow the index to change as we have probabilities."
);
}
}
},AlphabetIndex.INDEX
);
weights = new double[alpha.size()];
for (int i = 0; i < weights.length; i++) {
String s = indexer.symbolForIndex(i).getName();
if(symbolIndices.get(s)!=null){
weights[i] = ((Double)symbolIndices.get(s)).doubleValue();
}else{
weights[i] = 0.0;
}
}
}
public Alphabet getAlphabet() {
return indexer.getAlphabet();
}
public Distribution getNullModel() {
return this.nullModel;
}
protected void setNullModelImpl(Distribution nullModel)
throws IllegalAlphabetException, ChangeVetoException {
this.nullModel = nullModel;
}
protected boolean hasWeights() {
return weights != null;
}
protected double[] getWeights() {
if(weights == null) {
weights = new double[((FiniteAlphabet)getAlphabet()).size()];
for(int i = 0; i < weights.length; i++) {
weights[i] = Double.NaN;
}
}
return weights;
}
public double getWeightImpl(AtomicSymbol s)
throws IllegalSymbolException {
if(!hasWeights()) {
return Double.NaN;
} else {
int index = indexer.indexForSymbol(s);
return weights[index];
}
}
protected void setWeightImpl(AtomicSymbol s, double w)
throws IllegalSymbolException, ChangeVetoException {
double[] weights = getWeights();
if(w < 0.0) {
throw new IllegalArgumentException(
"Can't set weight to negative score: " +
s.getName() + " -> " + w
);
}
weights[indexer.indexForSymbol(s)] = w;
}
public SimpleDistribution(FiniteAlphabet alphabet) {
this.alpha = alphabet;
this.indexer = AlphabetManager.getAlphabetIndex(alphabet);
indexer.addChangeListener(
new ChangeAdapter() {
public void preChange(ChangeEvent ce) throws ChangeVetoException {
if(hasWeights()) {
throw new ChangeVetoException(
ce,
"Can't allow the index to change as we have probabilities."
);
}
}
},
AlphabetIndex.INDEX
);
try {
setNullModel(new UniformDistribution(alphabet));
} catch (Exception e) {
throw new BioError(e, "This should never fail. Something is screwed!");
}
}
/**
* Register a simple trainer for this distribution.
*/
public void registerWithTrainer(DistributionTrainerContext dtc) {
dtc.registerTrainer(this, new Trainer());
}
protected class Trainer implements DistributionTrainer {
private final Count counts;
public Trainer() {
counts = new IndexedCount(indexer);
}
public void addCount(DistributionTrainerContext dtc, AtomicSymbol sym, double times)
throws IllegalSymbolException {
try {
counts.increaseCount(sym, times);
} catch (ChangeVetoException cve) {
throw new BioError(
cve, "Assertion Failure: Change to Count object vetoed"
);
}
}
public double getCount(DistributionTrainerContext dtc, AtomicSymbol sym)
throws IllegalSymbolException {
return counts.getCount(sym);
}
public void clearCounts(DistributionTrainerContext dtc) {
try {
int size = ((FiniteAlphabet) counts.getAlphabet()).size();
for(int i = 0; i < size; i++) {
counts.zeroCounts();
}
} catch (ChangeVetoException cve) {
throw new BioError(
cve, "Assertion Failure: Change to Count object vetoed"
);
}
}
public void train(DistributionTrainerContext dtc, double weight)
throws ChangeVetoException {
if(!hasListeners()) {
trainImpl(dtc, weight);
} else {
ChangeSupport changeSupport = getChangeSupport(Distribution.WEIGHTS);
synchronized(changeSupport) {
ChangeEvent ce = new ChangeEvent(
SimpleDistribution.this,
Distribution.WEIGHTS
);
changeSupport.firePreChangeEvent(ce);
trainImpl(dtc, weight);
changeSupport.firePostChangeEvent(ce);
}
}
}
protected void trainImpl(DistributionTrainerContext dtc, double weight) {
//System.out.println("Training");
try {
Distribution nullModel = getNullModel();
double[] weights = getWeights();
double[] total = new double[weights.length];
double sum = 0.0;
for(int i = 0; i < total.length; i++) {
AtomicSymbol s = (AtomicSymbol) indexer.symbolForIndex(i);
sum +=
total[i] =
getCount(dtc, s) +
nullModel.getWeight(s) * weight;
}
double sum_inv = 1.0 / sum;
for(int i = 0; i < total.length; i++) {
//System.out.println("\t" + weights[i] + "\t" + total[i] * sum_inv);
weights[i] = total[i] * sum_inv;
}
} catch (IllegalSymbolException ise) {
throw new BioError(ise,
"Assertion Failure: Should be impossible to mess up the symbols."
);
}
}
}
}
|
package org.biojava.bio.program.das;
import java.util.*;
import java.util.zip.*;
import java.net.*;
import java.io.*;
import org.biojava.utils.*;
import org.biojava.utils.cache.*;
import org.biojava.bio.*;
import org.biojava.bio.seq.*;
import org.biojava.bio.seq.io.*;
import org.biojava.bio.seq.db.*;
import org.biojava.bio.seq.impl.*;
import org.biojava.bio.symbol.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import org.w3c.dom.*;
import org.biojava.utils.stax.*;
/**
* Sequence reflecting a DAS reference sequence, possibly
* decorated with one of more annotation sets.
*
* <p>
* This is an first-pass implementation. In future, I hope
* to add query optimization for better performance on large
* sequences, and pluggable transducers to parameterize the
* creation of BioJava features.
* </p>
*
* @since 1.1
* @author Thomas Down
* @author Matthew Pocock
* @author David Huen
*/
public class DASSequence implements Sequence, RealizingFeatureHolder {
/**
* Change type which indicates that the set of annotation servers used
* by this DASSequence has been changed. This extends Feature.FEATURES as
* the addition and removal of annotation servers adds and removes features.
*/
public static final ChangeType ANNOTATIONS = new ChangeType(
"Annotation sets have been added or removed from the DAS sequence",
"org.biojava.bio.program.das.DASSequence",
"ANNOTATIONS",
Feature.FEATURES
);
public static final String PROPERTY_ANNOTATIONSERVER = "org.biojava.bio.program.das.annotation_server";
public static final String PROPERTY_FEATUREID = "org.biojava.bio.program.das.feature_id";
public static final String PROPERTY_FEATURELABEL = "org.biojava.bio.program.das.feature_label";
public static final String PROPERTY_LINKS = "org.biojava.bio.program.das.links";
public static final String PROPERTY_SEQUENCEVERSION = "org.biojava.bio.program.das.sequence_version";
public static final int SIZE_THRESHOLD = 500000;
private DASSequenceDB parentdb;
private Alphabet alphabet = DNATools.getDNA();
private URL dataSourceURL;
private String seqID;
private String version = null;
private FeatureRealizer featureRealizer = FeatureImpl.DEFAULT;
private FeatureRequestManager.Ticket structureTicket;
private CacheReference refSymbols;
private int length = -1;
private Map featureSets;
private FeatureHolder structure;
private MergeFeatureHolder features;
protected transient ChangeSupport changeSupport = null;
{
featureSets = new HashMap();
features = new MergeFeatureHolder();
}
DASSequence(DASSequenceDB db, URL dataSourceURL, String seqID, Set dataSources)
throws BioException, IllegalIDException
{
this.parentdb = db;
this.dataSourceURL = dataSourceURL;
this.seqID = seqID;
// Check for deep structure. This also checks that the sequence
// really exists, and hopefully picks up the length along the way.
SeqIOListener listener = new SkeletonListener();
FeatureRequestManager frm = getParentDB().getFeatureRequestManager();
this.structureTicket = frm.requestFeatures(dataSourceURL, seqID, listener, null, "component");
// Pick up some annotations
for (Iterator dsi = dataSources.iterator(); dsi.hasNext(); ) {
URL annoURL = (URL) dsi.next();
FeatureHolder newFeatureSet = new DASFeatureSet(this, annoURL, seqID);
featureSets.put(annoURL, newFeatureSet);
features.addFeatureHolder(newFeatureSet);
}
}
private class SkeletonListener extends SeqIOAdapter {
private SimpleFeatureHolder structureF;
public void startSequence() {
structureF = new SimpleFeatureHolder();
}
public void endSequence() {
structure = structureF;
if (structure.countFeatures() > 0) {
features.addFeatureHolder(structure);
}
}
public void addSequenceProperty(Object key, Object value)
throws ParseException
{
try {
if (key.equals("sequence.start")) {
int start = Integer.parseInt(value.toString());
if (start != 1) {
throw new ParseException("Server doesn't think sequence starts at 1. Wierd.");
}
} else if (key.equals("sequence.stop")) {
length = Integer.parseInt(value.toString());
} else if (key.equals("sequence.version")) {
version = value.toString();
}
} catch (NumberFormatException ex) {
throw new ParseException(ex, "Expect numbers for segment start and stop");
}
}
public void startFeature(Feature.Template temp)
throws ParseException
{
if (temp instanceof ComponentFeature.Template) {
String id = (String) temp.annotation.getProperty("sequence.id");
try {
ComponentFeature.Template ctemp = (ComponentFeature.Template) temp;
ComponentFeature cf = new DASComponentFeature(DASSequence.this,
ctemp);
structureF.addFeature(cf);
length = Math.max(length, ctemp.location.getMax());
} catch (BioException ex) {
throw new ParseException(ex, "Error instantiating DASComponent");
} catch (ChangeVetoException ex) {
throw new BioError(ex, "Immutable FeatureHolder when trying to build structure");
}
} else {
// Server seems not to honour category=
// This hurts performance, but we can just elide the unwanted
// features on the client side.
}
}
}
URL getDataSourceURL() {
return dataSourceURL;
}
DASSequenceDB getParentDB() {
return parentdb;
}
FeatureHolder getStructure() throws BioException {
if(!this.structureTicket.isFetched()) {
this.structureTicket.doFetch();
}
return this.structure;
}
private void _addAnnotationSource(URL dataSourceURL)
throws BioException, ChangeVetoException
{
FeatureHolder structure = getStructure();
for (Iterator i = structure.features(); i.hasNext(); ) {
DASComponentFeature dcf = (DASComponentFeature) i.next();
DASSequence seq = dcf.getSequenceLazy();
if (seq != null) {
seq.addAnnotationSource(dataSourceURL);
}
}
FeatureHolder fs = new DASFeatureSet(this, dataSourceURL, this.seqID);
featureSets.put(dataSourceURL, fs);
features.addFeatureHolder(fs);
}
public Set dataSourceURLs() {
return Collections.unmodifiableSet(featureSets.keySet());
}
public void addAnnotationSource(URL dataSourceURL)
throws BioException, ChangeVetoException
{
if(!featureSets.containsKey(dataSourceURL)) {
if (changeSupport == null) {
_addAnnotationSource(dataSourceURL);
} else {
synchronized (changeSupport) {
ChangeEvent ce = new ChangeEvent(
this,
ANNOTATIONS,
null,
null
) ;
changeSupport.firePreChangeEvent(ce);
_addAnnotationSource(dataSourceURL);
changeSupport.firePostChangeEvent(ce);
}
}
}
}
private void _removeAnnotationSource(URL dataSourceURL)
throws ChangeVetoException, BioException
{
FeatureHolder structure = getStructure();
FeatureHolder fh = (FeatureHolder) featureSets.get(dataSourceURL);
if (fh != null) {
for (Iterator i = structure.features(); i.hasNext(); ) {
DASComponentFeature dcf = (DASComponentFeature) i.next();
DASSequence seq = dcf.getSequenceLazy();
if (seq != null) {
seq.removeAnnotationSource(dataSourceURL);
}
}
features.removeFeatureHolder(fh);
featureSets.remove(dataSourceURL);
}
}
public void removeAnnotationSource(URL dataSourceURL)
throws ChangeVetoException, BioException
{
if (featureSets.containsKey(dataSourceURL)) {
if (changeSupport == null) {
_removeAnnotationSource(dataSourceURL);
} else {
synchronized (changeSupport) {
ChangeEvent ce = new ChangeEvent(
this,
ANNOTATIONS,
null,
null
) ;
changeSupport.firePreChangeEvent(ce);
_removeAnnotationSource(dataSourceURL);
changeSupport.firePostChangeEvent(ce);
}
}
}
}
private int registerLocalFeatureFetchers() {
// System.err.println(getName() + ": registerLocalFeatureFetchers()");
for (Iterator i = featureSets.values().iterator(); i.hasNext(); ) {
DASFeatureSet dfs = (DASFeatureSet) i.next();
dfs.registerFeatureFetcher();
}
return featureSets.size();
}
private int registerLocalFeatureFetchers(Location l) {
// System.err.println(getName() + ": registerLocalFeatureFetchers(" + l.toString() + ")");
for (Iterator i = featureSets.values().iterator(); i.hasNext(); ) {
DASFeatureSet dfs = (DASFeatureSet) i.next();
dfs.registerFeatureFetcher(l);
}
return featureSets.size();
}
int registerFeatureFetchers() throws BioException {
// System.err.println(getName() + ": registerFeatureFetchers()");
for (Iterator i = featureSets.values().iterator(); i.hasNext(); ) {
DASFeatureSet dfs = (DASFeatureSet) i.next();
dfs.registerFeatureFetcher();
}
int num = featureSets.size();
FeatureHolder structure = getStructure();
if (length() < SIZE_THRESHOLD && structure.countFeatures() > 0) {
List sequences = new ArrayList();
for (Iterator fi = structure.features(); fi.hasNext(); ) {
ComponentFeature cf = (ComponentFeature) fi.next();
DASSequence cseq = (DASSequence) cf.getComponentSequence();
sequences.add(cseq);
}
for (Iterator si = sequences.iterator(); si.hasNext(); ) {
DASSequence cseq = (DASSequence) si.next();
num += cseq.registerFeatureFetchers();
}
}
return num;
}
int registerFeatureFetchers(Location l) throws BioException {
// System.err.println(getName() + ": registerFeatureFetchers(" + l.toString() + ")");
for (Iterator i = featureSets.values().iterator(); i.hasNext(); ) {
DASFeatureSet dfs = (DASFeatureSet) i.next();
dfs.registerFeatureFetcher(l);
}
int num = featureSets.size();
FeatureHolder structure = getStructure();
if (structure.countFeatures() > 0) {
FeatureHolder componentsBelow = structure.filter(new FeatureFilter.OverlapsLocation(l), false);
Map sequencesToRegions = new HashMap();
for (Iterator fi = componentsBelow.features(); fi.hasNext(); ) {
ComponentFeature cf = (ComponentFeature) fi.next();
DASSequence cseq = (DASSequence) cf.getComponentSequence();
if (l.contains(cf.getLocation())) {
sequencesToRegions.put(cseq, null);
} else {
Location partNeeded = l.intersection(cf.getLocation());
if (cf.getStrand() == StrandedFeature.POSITIVE) {
partNeeded = partNeeded.translate(cf.getComponentLocation().getMin() - cf.getLocation().getMin());
sequencesToRegions.put(cseq, partNeeded);
} else {
sequencesToRegions.put(cseq, null);
}
}
}
for (Iterator sri = sequencesToRegions.entrySet().iterator(); sri.hasNext(); ) {
Map.Entry srme = (Map.Entry) sri.next();
DASSequence cseq = (DASSequence) srme.getKey();
Location partNeeded = (Location) srme.getValue();
if (partNeeded != null) {
num += cseq.registerFeatureFetchers(partNeeded);
} else {
num += cseq.registerFeatureFetchers();
}
}
}
return num;
}
// SymbolList stuff
public Alphabet getAlphabet() {
return alphabet;
}
public Iterator iterator() {
try {
return getSymbols().iterator();
} catch (BioException be) {
throw new BioError(be, "Can't iterate over symbols");
}
}
public int length() {
try {
if (length < 0 && !structureTicket.isFetched()) {
// Hope that the length is set when we get the structure
structureTicket.doFetch();
}
if (length < 0) {
// Nasty fallback
length = getSymbols().length();
}
return length;
} catch (BioException be) {
throw new BioError(be, "Can't calculate length");
}
}
public String seqString() {
try {
return getSymbols().seqString();
} catch (BioException be) {
throw new BioError(be, "Can't create seqString");
}
}
public String subStr(int start, int end) {
try {
return getSymbols().subStr(start, end);
} catch (BioException be) {
throw new BioError(be, "Can't create substring");
}
}
public SymbolList subList(int start, int end) {
try {
return getSymbols().subList(start, end);
} catch (BioException be) {
throw new BioError(be, "Can't create subList");
}
}
public Symbol symbolAt(int pos) {
try {
return getSymbols().symbolAt(pos);
} catch (BioException be) {
throw new BioError(be, "Can't fetch symbol");
}
}
public List toList() {
try {
return getSymbols().toList();
} catch (BioException be) {
throw new BioError(be, "Can't create list");
}
}
public void edit(Edit e)
throws ChangeVetoException
{
throw new ChangeVetoException("/You/ try implementing read-write DAS");
}
// DNA fetching stuff
protected SymbolList getSymbols() throws BioException {
SymbolList sl = null;
if (refSymbols != null) {
sl = (SymbolList) refSymbols.get();
}
if (sl == null) {
FeatureHolder structure = getStructure();
if (structure.countFeatures() == 0) {
sl = getTrueSymbols();
} else {
// VERY, VERY, naive approach to identifying canonical components. FIXME
Location coverage = Location.empty;
AssembledSymbolList asl = new AssembledSymbolList();
asl.setLength(length);
for (Iterator i = structure.features(); i.hasNext(); ) {
ComponentFeature cf = (ComponentFeature) i.next();
Location loc = cf.getLocation();
if (LocationTools.overlaps(loc, coverage)) {
// Assume that this is non-cannonical. Maybe not a great thing to
// do, but...
} else {
asl.putComponent(loc, cf);
coverage = LocationTools.union(coverage, loc);
}
}
sl = asl;
}
refSymbols = parentdb.getSymbolsCache().makeReference(sl);
}
return sl;
}
protected SymbolList getTrueSymbols() {
long startGet = (new Date()).getTime();
try {
DAS.startedActivity(this);
URL epURL = new URL(dataSourceURL, "dna?ref=" + seqID);
HttpURLConnection huc = (HttpURLConnection) epURL.openConnection();
huc.setRequestProperty("Accept-Encoding", "gzip");
huc.connect();
// int status = huc.getHeaderFieldInt("X-DAS-Status", 0);
int status = DASSequenceDB.tolerantIntHeader(huc, "X-DAS-Status");
if (status == 0)
throw new BioError("Not a DAS server");
else if (status != 200)
throw new BioError("DAS error (status code = " + status + ")");
SequenceBuilder sb = new SimpleSequenceBuilder();
sb.setURI(epURL.toString());
sb.setName(getName());
SymbolParser sparser = DNATools.getDNA().getParser("token");
StreamParser ssparser = sparser.parseStream(sb);
StAXContentHandler dnaHandler = new DNAHandler(ssparser);
// determine if I'm getting a gzipped reply
String contentEncoding = huc.getContentEncoding();
InputStream inStream = huc.getInputStream();
if (contentEncoding != null) {
if (contentEncoding.indexOf("gzip") != -1) {
// we have gzip encoding
inStream = new GZIPInputStream(inStream);
// System.out.println("gzip encoded dna!");
}
}
InputSource is = new InputSource(inStream);
is.setSystemId(epURL.toString());
XMLReader parser = nonvalidatingSAXParser();
parser.setContentHandler(new SAX2StAXAdaptor(dnaHandler));
parser.parse(is);
SymbolList sl = sb.makeSequence();
return sl;
} catch (SAXException ex) {
throw new BioError(ex, "Exception parsing DAS XML");
} catch (IOException ex) {
throw new BioError(ex, "Error connecting to DAS server");
} catch (BioException ex) {
throw new BioError(ex);
} finally {
DAS.completedActivity(this);
}
}
private class DNAHandler extends StAXContentHandlerBase {
private StreamParser ssparser;
DNAHandler(StreamParser ssparser) {
this.ssparser = ssparser;
}
public void startElement(String nsURI,
String localName,
String qName,
Attributes attrs,
DelegationManager dm)
throws SAXException
{
if (localName.equals("DNA")) {
dm.delegate(new SymbolsHandler(ssparser));
}
}
}
private class SymbolsHandler extends StAXContentHandlerBase {
private StreamParser ssparser;
SymbolsHandler(StreamParser ssparser) {
this.ssparser = ssparser;
}
public void endElement(String nsURI,
String localName,
String qName,
StAXContentHandler handler)
throws SAXException
{
try {
ssparser.close();
} catch (IllegalSymbolException ex) {
throw new SAXException(ex);
}
}
public void characters(char[] ch, int start, int length)
throws SAXException
{
try {
int parseStart = start;
int parseEnd = start;
int blockEnd = start + length;
while (parseStart < blockEnd) {
while (parseStart < blockEnd && Character.isSpace(ch[parseStart])) {
++parseStart;
}
if (parseStart >= blockEnd) {
return;
}
parseEnd = parseStart + 1;
while (parseEnd < blockEnd && !Character.isSpace(ch[parseEnd])) {
++parseEnd;
}
ssparser.characters(ch, parseStart, parseEnd - parseStart);
parseStart = parseEnd;
}
} catch (IllegalSymbolException ex) {
throw new SAXException(ex);
}
}
}
// Identification stuff
public String getName() {
return seqID;
}
public String getURN() {
try {
return new URL(dataSourceURL, "?ref=" + seqID).toString();
} catch (MalformedURLException ex) {
throw new BioError(ex);
}
}
// FeatureHolder stuff
public Iterator features() {
try {
registerFeatureFetchers();
return features.features();
} catch (BioException be) {
throw new BioError(be, "Couldn't create features iterator");
}
}
public boolean containsFeature(Feature f) {
return features.containsFeature(f);
}
public FeatureHolder filter(FeatureFilter ff, boolean recurse) {
try {
// We optimise for the case of just wanting `structural' features,
// which improves the scalability of the Dazzle server (and probably
// other applications, too)
FeatureHolder structure = getStructure();
FeatureFilter structureMembershipFilter = new FeatureFilter.ByClass(ComponentFeature.class);
if (FilterUtils.areProperSubset(ff, structureMembershipFilter)) {
if (recurse) {
for (Iterator fi = structure.features(); fi.hasNext(); ) {
ComponentFeature cf = (ComponentFeature) fi.next();
Sequence cseq = cf.getComponentSequence();
// Just ensuring that the sequence is instantiated should be sufficient.
}
}
return structure.filter(ff, recurse);
}
// Otherwise they want /real/ features, I'm afraid...
Location ffl = extractInterestingLocation(ff);
if (recurse) {
int numComponents = 1;
if (ffl != null) {
numComponents = registerFeatureFetchers(ffl);
} else {
numComponents = registerFeatureFetchers();
}
getParentDB().ensureFeaturesCacheCapacity(numComponents * 3);
} else {
if (ffl != null) {
registerLocalFeatureFetchers(ffl);
} else {
new Exception("Hmmm, this is dangerous...").printStackTrace();
registerLocalFeatureFetchers();
}
}
return features.filter(ff, recurse);
} catch (BioException be) {
throw new BioError(be, "Can't filter");
}
}
private Location extractInterestingLocation(FeatureFilter ff) {
if (ff instanceof FeatureFilter.OverlapsLocation) {
return ((FeatureFilter.OverlapsLocation) ff).getLocation();
} else if (ff instanceof FeatureFilter.ContainedByLocation) {
return ((FeatureFilter.ContainedByLocation) ff).getLocation();
} else if (ff instanceof FeatureFilter.And) {
FeatureFilter.And ffa = (FeatureFilter.And) ff;
Location l1 = extractInterestingLocation(ffa.getChild1());
Location l2 = extractInterestingLocation(ffa.getChild2());
if (l1 != null) {
if (l2 != null) {
return l1.intersection(l2);
} else {
return l1;
}
} else {
if (l2 != null) {
return l2;
} else {
return null;
}
}
}
// Don't know how this filter relates to location.
return null;
}
public int countFeatures() {
return features.countFeatures();
}
public Feature createFeature(Feature.Template temp)
throws ChangeVetoException
{
throw new ChangeVetoException("Can't create features on DAS sequences.");
}
public void removeFeature(Feature f)
throws ChangeVetoException
{
throw new ChangeVetoException("Can't remove features from DAS sequences.");
}
// Feature realization stuff
public Feature realizeFeature(FeatureHolder dest,
Feature.Template temp)
throws BioException
{
return featureRealizer.realizeFeature(this, dest, temp);
}
// Annotatable stuff
public Annotation getAnnotation() {
try {
Annotation anno = new SmallAnnotation();
anno.setProperty(PROPERTY_SEQUENCEVERSION, version);
return anno;
} catch (ChangeVetoException ex) {
throw new BioError("Expected to be able to modify annotation");
}
}
// Changeable stuff (which, unfortunately, we are. Drat)
protected void generateChangeSupport(ChangeType changeType) {
if(changeSupport == null) {
changeSupport = new ChangeSupport();
}
}
public void addChangeListener(ChangeListener cl) {
generateChangeSupport(null);
synchronized(changeSupport) {
changeSupport.addChangeListener(cl);
}
}
public void addChangeListener(ChangeListener cl, ChangeType ct) {
generateChangeSupport(ct);
synchronized(changeSupport) {
changeSupport.addChangeListener(cl, ct);
}
}
public void removeChangeListener(ChangeListener cl) {
if(changeSupport != null) {
synchronized(changeSupport) {
changeSupport.removeChangeListener(cl);
}
}
}
public void removeChangeListener(ChangeListener cl, ChangeType ct) {
if(changeSupport != null) {
synchronized(changeSupport) {
changeSupport.removeChangeListener(cl, ct);
}
}
}
// Utility method to turn of the awkward bits of Xerces-J
static DocumentBuilder nonvalidatingParser() {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
return dbf.newDocumentBuilder();
} catch (Exception ex) {
throw new BioError(ex);
}
}
static XMLReader nonvalidatingSAXParser() {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating(false);
spf.setNamespaceAware(true);
return spf.newSAXParser().getXMLReader();
} catch (Exception ex) {
throw new BioError(ex);
}
}
}
|
package org.bootstrapjsp.support;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.DynamicAttributes;
import org.bootstrapjsp.util.UidGenerator;
public class SgmlTagSupport extends NestedTagSupport implements DynamicAttributes {
private Map<String, String> attributes = new HashMap<String, String>();
private String element;
private int evaluation;
private String body;
public SgmlTagSupport(String element, int evaluation) {
this.element = element;
this.evaluation = evaluation;
}
@Override
public void doTag() throws JspException, IOException {
final JspWriter writer = super.getJspContext().getOut();
writer.print("<");
writer.print(this.element);
for (Entry<String, String> attribute : this.attributes.entrySet()) {
final String value = attribute.getValue();
if (value != null && value.length() > 0) {
writer.print(" ");
writer.print(attribute.getKey());
writer.print("=\"");
writer.print(value);
writer.print("\"");
}
}
writer.println(">");
if (this.body != null) {
writer.println(this.body);
} else {
super.doTag();
}
writer.print("</");
writer.print(this.element);
writer.println(">");
}
@Override
public void setDynamicAttribute(String uri, String localName, Object value) throws JspException {
if ("attributes".equals(localName) && value instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> attributes = (Map<String, Object>) value;
for (Entry<String, Object> attribute : attributes.entrySet()) {
this.setAttribute(attribute.getKey(), attribute.getValue());
}
} else if ("element".equals(localName) && value instanceof String) {
this.setElement((String) value);
} else if (value != null) {
this.setAttribute(localName, value);
}
}
public void setAttribute(String name, Object value) {
this.attributes.put(name, value.toString());
}
public String getAttribute(String name) {
return this.attributes.get(name);
}
public void setEvaluation(int evaluation) {
this.evaluation = evaluation;
}
public int getEvaluation() {
return evaluation;
}
public void setElement(String element) {
this.element = element;
}
public String getElement() {
return element;
}
public void setBody(String body) {
this.body = body;
}
public String getId(boolean create) {
String uid = this.getAttribute("id");
if (uid == null) {
uid = UidGenerator.getUid(super.getJspContext());
this.setAttribute("id", uid);
}
return uid;
}
}
|
package org.mockito.internal.stubbing;
public class DontThrow extends RuntimeException {
private static final long serialVersionUID = 1L;
public static final DontThrow DONT_THROW = new DontThrow();
}
|
package org.objectweb.asm.commons;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.objectweb.asm.Handle;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
/**
* A {@link org.objectweb.asm.MethodVisitor} to insert before, after and around
* advices in methods and constructors.
* <p>
* The behavior for constructors is like this:
* <ol>
*
* <li>as long as the INVOKESPECIAL for the object initialization has not been
* reached, every bytecode instruction is dispatched in the ctor code visitor</li>
*
* <li>when this one is reached, it is only added in the ctor code visitor and a
* JP invoke is added</li>
*
* <li>after that, only the other code visitor receives the instructions</li>
*
* </ol>
*
* @author Eugene Kuleshov
* @author Eric Bruneton
*/
public abstract class AdviceAdapter extends GeneratorAdapter implements Opcodes {
private static final Object THIS = new Object();
private static final Object OTHER = new Object();
protected int methodAccess;
protected String methodDesc;
private boolean constructor;
private boolean superInitialized;
private List<Object> stackFrame;
private Map<Label, List<Object>> branches;
/**
* Creates a new {@link AdviceAdapter}.
*
* @param api
* the ASM API version implemented by this visitor. Must be one
* of {@link Opcodes#ASM4} or {@link Opcodes#ASM5}.
* @param mv
* the method visitor to which this adapter delegates calls.
* @param access
* the method's access flags (see {@link Opcodes}).
* @param name
* the method's name.
* @param desc
* the method's descriptor (see {@link Type Type}).
*/
protected AdviceAdapter(final int api, final MethodVisitor mv,
final int access, final String name, final String desc) {
super(api, mv, access, name, desc);
methodAccess = access;
methodDesc = desc;
constructor = "<init>".equals(name);
}
@Override
public void visitCode() {
mv.visitCode();
if (constructor) {
stackFrame = new ArrayList<Object>();
branches = new HashMap<Label, List<Object>>();
} else {
superInitialized = true;
onMethodEnter();
}
}
@Override
public void visitLabel(final Label label) {
mv.visitLabel(label);
if (constructor && branches != null) {
List<Object> frame = branches.get(label);
if (frame != null) {
stackFrame = frame;
branches.remove(label);
}
}
}
@Override
public void visitInsn(final int opcode) {
if (constructor) {
int s;
switch (opcode) {
case RETURN: // empty stack
onMethodExit(opcode);
break;
case IRETURN: // 1 before n/a after
case FRETURN: // 1 before n/a after
case ARETURN: // 1 before n/a after
case ATHROW: // 1 before n/a after
popValue();
onMethodExit(opcode);
break;
case LRETURN: // 2 before n/a after
case DRETURN: // 2 before n/a after
popValue();
popValue();
onMethodExit(opcode);
break;
case NOP:
case LALOAD: // remove 2 add 2
case DALOAD: // remove 2 add 2
case LNEG:
case DNEG:
case FNEG:
case INEG:
case L2D:
case D2L:
case F2I:
case I2B:
case I2C:
case I2S:
case I2F:
case ARRAYLENGTH:
break;
case ACONST_NULL:
case ICONST_M1:
case ICONST_0:
case ICONST_1:
case ICONST_2:
case ICONST_3:
case ICONST_4:
case ICONST_5:
case FCONST_0:
case FCONST_1:
case FCONST_2:
case F2L: // 1 before 2 after
case F2D:
case I2L:
case I2D:
pushValue(OTHER);
break;
case LCONST_0:
case LCONST_1:
case DCONST_0:
case DCONST_1:
pushValue(OTHER);
pushValue(OTHER);
break;
case IALOAD: // remove 2 add 1
case FALOAD: // remove 2 add 1
case AALOAD: // remove 2 add 1
case BALOAD: // remove 2 add 1
case CALOAD: // remove 2 add 1
case SALOAD: // remove 2 add 1
case POP:
case IADD:
case FADD:
case ISUB:
case LSHL: // 3 before 2 after
case LSHR: // 3 before 2 after
case LUSHR: // 3 before 2 after
case L2I: // 2 before 1 after
case L2F: // 2 before 1 after
case D2I: // 2 before 1 after
case D2F: // 2 before 1 after
case FSUB:
case FMUL:
case FDIV:
case FREM:
case FCMPL: // 2 before 1 after
case FCMPG: // 2 before 1 after
case IMUL:
case IDIV:
case IREM:
case ISHL:
case ISHR:
case IUSHR:
case IAND:
case IOR:
case IXOR:
case MONITORENTER:
case MONITOREXIT:
popValue();
break;
case POP2:
case LSUB:
case LMUL:
case LDIV:
case LREM:
case LADD:
case LAND:
case LOR:
case LXOR:
case DADD:
case DMUL:
case DSUB:
case DDIV:
case DREM:
popValue();
popValue();
break;
case IASTORE:
case FASTORE:
case AASTORE:
case BASTORE:
case CASTORE:
case SASTORE:
case LCMP: // 4 before 1 after
case DCMPL:
case DCMPG:
popValue();
popValue();
popValue();
break;
case LASTORE:
case DASTORE:
popValue();
popValue();
popValue();
popValue();
break;
case DUP:
pushValue(peekValue());
break;
case DUP_X1:
s = stackFrame.size();
stackFrame.add(s - 2, stackFrame.get(s - 1));
break;
case DUP_X2:
s = stackFrame.size();
stackFrame.add(s - 3, stackFrame.get(s - 1));
break;
case DUP2:
s = stackFrame.size();
stackFrame.add(s - 2, stackFrame.get(s - 1));
stackFrame.add(s - 2, stackFrame.get(s - 1));
break;
case DUP2_X1:
s = stackFrame.size();
stackFrame.add(s - 3, stackFrame.get(s - 1));
stackFrame.add(s - 3, stackFrame.get(s - 1));
break;
case DUP2_X2:
s = stackFrame.size();
stackFrame.add(s - 4, stackFrame.get(s - 1));
stackFrame.add(s - 4, stackFrame.get(s - 1));
break;
case SWAP:
s = stackFrame.size();
stackFrame.add(s - 2, stackFrame.get(s - 1));
stackFrame.remove(s);
break;
}
} else {
switch (opcode) {
case RETURN:
case IRETURN:
case FRETURN:
case ARETURN:
case LRETURN:
case DRETURN:
case ATHROW:
onMethodExit(opcode);
break;
}
}
mv.visitInsn(opcode);
}
@Override
public void visitVarInsn(final int opcode, final int var) {
super.visitVarInsn(opcode, var);
if (constructor) {
switch (opcode) {
case ILOAD:
case FLOAD:
pushValue(OTHER);
break;
case LLOAD:
case DLOAD:
pushValue(OTHER);
pushValue(OTHER);
break;
case ALOAD:
pushValue(var == 0 ? THIS : OTHER);
break;
case ASTORE:
case ISTORE:
case FSTORE:
popValue();
break;
case LSTORE:
case DSTORE:
popValue();
popValue();
break;
}
}
}
@Override
public void visitFieldInsn(final int opcode, final String owner,
final String name, final String desc) {
mv.visitFieldInsn(opcode, owner, name, desc);
if (constructor) {
char c = desc.charAt(0);
boolean longOrDouble = c == 'J' || c == 'D';
switch (opcode) {
case GETSTATIC:
pushValue(OTHER);
if (longOrDouble) {
pushValue(OTHER);
}
break;
case PUTSTATIC:
popValue();
if (longOrDouble) {
popValue();
}
break;
case PUTFIELD:
popValue();
if (longOrDouble) {
popValue();
popValue();
}
break;
// case GETFIELD:
default:
if (longOrDouble) {
pushValue(OTHER);
}
}
}
}
@Override
public void visitIntInsn(final int opcode, final int operand) {
mv.visitIntInsn(opcode, operand);
if (constructor && opcode != NEWARRAY) {
pushValue(OTHER);
}
}
@Override
public void visitLdcInsn(final Object cst) {
mv.visitLdcInsn(cst);
if (constructor) {
pushValue(OTHER);
if (cst instanceof Double || cst instanceof Long) {
pushValue(OTHER);
}
}
}
@Override
public void visitMultiANewArrayInsn(final String desc, final int dims) {
mv.visitMultiANewArrayInsn(desc, dims);
if (constructor) {
for (int i = 0; i < dims; i++) {
popValue();
}
pushValue(OTHER);
}
}
@Override
public void visitTypeInsn(final int opcode, final String type) {
mv.visitTypeInsn(opcode, type);
// ANEWARRAY, CHECKCAST or INSTANCEOF don't change stack
if (constructor && opcode == NEW) {
pushValue(OTHER);
}
}
@Deprecated
@Override
public void visitMethodInsn(final int opcode, final String owner,
final String name, final String desc) {
if (api >= Opcodes.ASM5) {
super.visitMethodInsn(opcode, owner, name, desc);
return;
}
doVisitMethodInsn(opcode, owner, name, desc,
opcode == Opcodes.INVOKEINTERFACE);
}
@Override
public void visitMethodInsn(final int opcode, final String owner,
final String name, final String desc, final boolean itf) {
if (api < Opcodes.ASM5) {
super.visitMethodInsn(opcode, owner, name, desc, itf);
return;
}
doVisitMethodInsn(opcode, owner, name, desc, itf);
}
private void doVisitMethodInsn(int opcode, final String owner,
final String name, final String desc, final boolean itf) {
mv.visitMethodInsn(opcode, owner, name, desc, itf);
if (constructor) {
Type[] types = Type.getArgumentTypes(desc);
for (int i = 0; i < types.length; i++) {
popValue();
if (types[i].getSize() == 2) {
popValue();
}
}
switch (opcode) {
// case INVOKESTATIC:
// break;
case INVOKEINTERFACE:
case INVOKEVIRTUAL:
popValue(); // objectref
break;
case INVOKESPECIAL:
Object type = popValue(); // objectref
if (type == THIS && !superInitialized) {
onMethodEnter();
superInitialized = true;
// once super has been initialized it is no longer
// necessary to keep track of stack state
constructor = false;
}
break;
}
Type returnType = Type.getReturnType(desc);
if (returnType != Type.VOID_TYPE) {
pushValue(OTHER);
if (returnType.getSize() == 2) {
pushValue(OTHER);
}
}
}
}
@Override
public void visitInvokeDynamicInsn(String name, String desc, Handle bsm,
Object... bsmArgs) {
mv.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs);
if (constructor) {
Type[] types = Type.getArgumentTypes(desc);
for (int i = 0; i < types.length; i++) {
popValue();
if (types[i].getSize() == 2) {
popValue();
}
}
Type returnType = Type.getReturnType(desc);
if (returnType != Type.VOID_TYPE) {
pushValue(OTHER);
if (returnType.getSize() == 2) {
pushValue(OTHER);
}
}
}
}
@Override
public void visitJumpInsn(final int opcode, final Label label) {
mv.visitJumpInsn(opcode, label);
if (constructor) {
switch (opcode) {
case IFEQ:
case IFNE:
case IFLT:
case IFGE:
case IFGT:
case IFLE:
case IFNULL:
case IFNONNULL:
popValue();
break;
case IF_ICMPEQ:
case IF_ICMPNE:
case IF_ICMPLT:
case IF_ICMPGE:
case IF_ICMPGT:
case IF_ICMPLE:
case IF_ACMPEQ:
case IF_ACMPNE:
popValue();
popValue();
break;
case JSR:
pushValue(OTHER);
break;
}
addBranch(label);
}
}
@Override
public void visitLookupSwitchInsn(final Label dflt, final int[] keys,
final Label[] labels) {
mv.visitLookupSwitchInsn(dflt, keys, labels);
if (constructor) {
popValue();
addBranches(dflt, labels);
}
}
@Override
public void visitTableSwitchInsn(final int min, final int max,
final Label dflt, final Label... labels) {
mv.visitTableSwitchInsn(min, max, dflt, labels);
if (constructor) {
popValue();
addBranches(dflt, labels);
}
}
@Override
public void visitTryCatchBlock(Label start, Label end, Label handler,
String type) {
super.visitTryCatchBlock(start, end, handler, type);
if (constructor && !branches.containsKey(handler)) {
List<Object> stackFrame = new ArrayList<Object>();
stackFrame.add(OTHER);
branches.put(handler, stackFrame);
}
}
private void addBranches(final Label dflt, final Label[] labels) {
addBranch(dflt);
for (int i = 0; i < labels.length; i++) {
addBranch(labels[i]);
}
}
private void addBranch(final Label label) {
if (branches.containsKey(label)) {
return;
}
branches.put(label, new ArrayList<Object>(stackFrame));
}
private Object popValue() {
return stackFrame.remove(stackFrame.size() - 1);
}
private Object peekValue() {
return stackFrame.get(stackFrame.size() - 1);
}
private void pushValue(final Object o) {
stackFrame.add(o);
}
/**
* Called at the beginning of the method or after super class call in
* the constructor. <br>
* <br>
*
* <i>Custom code can use or change all the local variables, but should not
* change state of the stack.</i>
*/
protected void onMethodEnter() {
}
/**
* Called before explicit exit from the method using either return or throw.
* Top element on the stack contains the return value or exception instance.
* For example:
*
* <pre>
* public void onMethodExit(int opcode) {
* if(opcode==RETURN) {
* visitInsn(ACONST_NULL);
* } else if(opcode==ARETURN || opcode==ATHROW) {
* dup();
* } else {
* if(opcode==LRETURN || opcode==DRETURN) {
* dup2();
* } else {
* dup();
* }
* box(Type.getReturnType(this.methodDesc));
* }
* visitIntInsn(SIPUSH, opcode);
* visitMethodInsn(INVOKESTATIC, owner, "onExit", "(Ljava/lang/Object;I)V");
* }
*
* // an actual call back method
* public static void onExit(Object param, int opcode) {
* ...
* </pre>
*
* <br>
* <br>
*
* <i>Custom code can use or change all the local variables, but should not
* change state of the stack.</i>
*
* @param opcode
* one of the RETURN, IRETURN, FRETURN, ARETURN, LRETURN, DRETURN
* or ATHROW
*
*/
protected void onMethodExit(int opcode) {
}
// TODO onException, onMethodCall
}
|
package org.olap4j.driver.xmla;
import org.olap4j.OlapException;
import org.olap4j.impl.*;
import org.olap4j.mdx.ParseTreeNode;
import org.olap4j.metadata.*;
import java.util.*;
/**
* Implementation of {@link org.olap4j.metadata.Member}
* for XML/A providers.
*
* <p>TODO:<ol>
* <li>create members with a pointer to their parent member (not the name)</li>
* <li>implement a member cache (by unique name, belongs to cube, soft)</li>
* <li>implement Hierarchy.getRootMembers</li>
* </ol>
*
* @author jhyde
* @version $Id$
* @since Dec 5, 2007
*/
class XmlaOlap4jMember
extends XmlaOlap4jElement
implements XmlaOlap4jMemberBase, Member, Named
{
private final XmlaOlap4jLevel olap4jLevel;
// TODO: We would rather have a refernce to the parent member, but it is
// tricky to populate
/*
private final XmlaOlap4jMember parentMember;
*/
private final String parentMemberUniqueName;
private final Type type;
private XmlaOlap4jMember parentMember;
private final int childMemberCount;
private final int ordinal;
private final Map<Property, Object> propertyValueMap;
/**
* Creates an XmlaOlap4jMember.
*
* @param olap4jLevel Level
* @param uniqueName Unique name
* @param name Name
* @param caption Caption
* @param description Description
* @param parentMemberUniqueName Unique name of parent, or null if no parent
* @param type Type
* @param childMemberCount Number of children
* @param ordinal Ordinal in its hierarchy
* @param propertyValueMap Property values
*/
XmlaOlap4jMember(
XmlaOlap4jLevel olap4jLevel,
String uniqueName,
String name,
String caption,
String description,
String parentMemberUniqueName,
Type type,
int childMemberCount,
int ordinal,
Map<Property, Object> propertyValueMap)
{
super(uniqueName, name, caption, description);
this.ordinal = ordinal;
assert olap4jLevel != null;
assert type != null;
this.olap4jLevel = olap4jLevel;
this.parentMemberUniqueName = parentMemberUniqueName;
this.type = type;
this.childMemberCount = childMemberCount;
this.propertyValueMap = UnmodifiableArrayMap.of(propertyValueMap);
}
public int hashCode() {
return uniqueName.hashCode();
}
public boolean equals(Object obj) {
return obj instanceof XmlaOlap4jMember
&& ((XmlaOlap4jMember) obj).uniqueName.equals(uniqueName);
}
public NamedList<? extends Member> getChildMembers() throws OlapException {
final NamedList<XmlaOlap4jMember> list =
new NamedListImpl<XmlaOlap4jMember>();
getCube()
.getMetadataReader()
.lookupMemberRelatives(
Olap4jUtil.enumSetOf(TreeOp.CHILDREN),
uniqueName,
list);
return list;
}
public int getChildMemberCount() {
return childMemberCount;
}
public XmlaOlap4jMember getParentMember() {
if (parentMemberUniqueName == null) {
return null;
}
if (parentMember == null) {
try {
parentMember =
getCube().getMetadataReader()
.lookupMemberByUniqueName(parentMemberUniqueName);
} catch (OlapException e) {
throw new RuntimeException("yuck!"); // FIXME
}
}
return parentMember;
}
public XmlaOlap4jLevel getLevel() {
return olap4jLevel;
}
public XmlaOlap4jHierarchy getHierarchy() {
return olap4jLevel.olap4jHierarchy;
}
public XmlaOlap4jDimension getDimension() {
return olap4jLevel.olap4jHierarchy.olap4jDimension;
}
public Type getMemberType() {
return type;
}
public boolean isAll() {
return type == Type.ALL;
}
public boolean isChildOrEqualTo(Member member) {
throw new UnsupportedOperationException();
}
public boolean isCalculated() {
return type == Type.FORMULA;
}
public int getSolveOrder() {
throw new UnsupportedOperationException();
}
public ParseTreeNode getExpression() {
throw new UnsupportedOperationException();
}
public List<Member> getAncestorMembers() {
final List<Member> list = new ArrayList<Member>();
XmlaOlap4jMember m = getParentMember();
while (m != null) {
list.add(m);
m = m.getParentMember();
}
return list;
}
public boolean isCalculatedInQuery() {
throw new UnsupportedOperationException();
}
public Object getPropertyValue(Property property) throws OlapException {
return getPropertyValue(
property,
this,
propertyValueMap);
}
/**
* Helper method to retrieve the value of a property from a member.
*
* @param property Property
* @param member Member
* @param propertyValueMap Map of property-value pairs
* @return Property value
*
* @throws OlapException if database error occurs while evaluating
* CHILDREN_CARDINALITY; no other property throws
*/
static Object getPropertyValue(
Property property,
XmlaOlap4jMemberBase member,
Map<Property, Object> propertyValueMap)
throws OlapException
{
// If property map contains a value for this property (even if that
// value is null), that overrides.
final Object value = propertyValueMap.get(property);
if (value != null || propertyValueMap.containsKey(property)) {
return value;
}
if (property instanceof Property.StandardMemberProperty) {
Property.StandardMemberProperty o =
(Property.StandardMemberProperty) property;
switch (o) {
case MEMBER_CAPTION:
return member.getCaption();
case MEMBER_NAME:
return member.getName();
case MEMBER_UNIQUE_NAME:
return member.getUniqueName();
case CATALOG_NAME:
return member.getCatalog().getName();
case CHILDREN_CARDINALITY:
return member.getChildMemberCount();
case CUBE_NAME:
return member.getCube().getName();
case DEPTH:
return member.getDepth();
case DESCRIPTION:
return member.getDescription();
case DIMENSION_UNIQUE_NAME:
return member.getDimension().getUniqueName();
case DISPLAY_INFO:
// TODO:
return null;
case HIERARCHY_UNIQUE_NAME:
return member.getHierarchy().getUniqueName();
case LEVEL_NUMBER:
return member.getLevel().getDepth();
case LEVEL_UNIQUE_NAME:
return member.getLevel().getUniqueName();
case MEMBER_GUID:
// TODO:
return null;
case MEMBER_ORDINAL:
return member.getOrdinal();
case MEMBER_TYPE:
return member.getMemberType();
case PARENT_COUNT:
return 1;
case PARENT_LEVEL:
return member.getParentMember() == null
? 0
: member.getParentMember().getLevel().getDepth();
case PARENT_UNIQUE_NAME:
return member.getParentMember() == null
? null
: member.getParentMember().getUniqueName();
case SCHEMA_NAME:
return member.getCube().olap4jSchema.getName();
case VALUE:
// TODO:
return null;
}
}
return null;
}
// convenience method - not part of olap4j API
public XmlaOlap4jCube getCube() {
return olap4jLevel.olap4jHierarchy.olap4jDimension.olap4jCube;
}
// convenience method - not part of olap4j API
public XmlaOlap4jCatalog getCatalog() {
return olap4jLevel.olap4jHierarchy.olap4jDimension.olap4jCube
.olap4jSchema.olap4jCatalog;
}
// convenience method - not part of olap4j API
public XmlaOlap4jConnection getConnection() {
return olap4jLevel.olap4jHierarchy.olap4jDimension.olap4jCube
.olap4jSchema.olap4jCatalog.olap4jDatabaseMetaData
.olap4jConnection;
}
// convenience method - not part of olap4j API
public Map<Property, Object> getPropertyValueMap() {
return propertyValueMap;
}
public String getPropertyFormattedValue(Property property)
throws OlapException
{
// FIXME: need to use a format string; but what format string; and how
// to format the property on the client side?
return String.valueOf(getPropertyValue(property));
}
public void setProperty(Property property, Object value) {
propertyValueMap.put(property, value);
}
public NamedList<Property> getProperties() {
return olap4jLevel.getProperties();
}
public int getOrdinal() {
return ordinal;
}
public boolean isHidden() {
throw new UnsupportedOperationException();
}
public int getDepth() {
// Since in regular hierarchies members have the same depth as their
// level, we store depth as a property only where it is different.
final Object depth =
propertyValueMap.get(Property.StandardMemberProperty.DEPTH);
if (depth == null) {
return olap4jLevel.getDepth();
} else {
return toInteger(depth);
}
}
/**
* Converts an object to an integer value. Must not be null.
*
* @param o Object
* @return Integer value
*/
static int toInteger(Object o) {
if (o instanceof Number) {
Number number = (Number) o;
return number.intValue();
}
return Integer.valueOf(o.toString());
}
public Member getDataMember() {
throw new UnsupportedOperationException();
}
}
// End XmlaOlap4jMember.java
|
package org.svetovid.installer;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import org.svetovid.io.SvetovidProcess;
import org.svetovid.run.SvetovidProcessBuilder;
public final class JavaInstallation implements Comparable<JavaInstallation> {
public static final String LIB_FILE_NAME = "svetovid-lib.jar";
private Path location;
private Path binLocation;
private Path libLocation;
private String jdkVersion;
private String jreVersion;
private String libVersion;
private JavaInstallation() {
this.location = null;
String[] extdirs = System.getProperty("java.ext.dirs").split(File.pathSeparator);
if (extdirs.length > 1) {
libLocation = Paths.get(extdirs[1]);
}
}
private JavaInstallation(Path location) {
this.location = location;
initialize();
}
@Override
public int hashCode() {
if (location == null) {
return 0;
}
return location.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof JavaInstallation)) {
return false;
}
Path thatLocation = ((JavaInstallation) obj).location;
if (this.location == thatLocation) {
return true;
}
if (this.location == null) {
return false;
}
return this.location.equals(thatLocation);
}
@Override
public int compareTo(JavaInstallation that) {
if ((this.location == null) && (that.location == null)) {
return 0;
}
if (this.location == null) {
return -1;
}
if (that.location == null) {
return 1;
}
return this.location.compareTo(that.location);
}
private void initialize() {
if (location == null) {
return;
}
binLocation = libLocation = null;
jdkVersion = jreVersion = libVersion = null;
if (!Files.isDirectory(location)) {
return;
}
binLocation = location.resolve("bin");
if (!Files.isDirectory(binLocation)) {
return;
}
Path binary = binLocation.resolve("javac");
SvetovidProcess process = exec(binLocation, binary.toString(), "-version");
if (process != null) {
jdkVersion = process.err.readLine();
jdkVersion = jdkVersion.substring(jdkVersion.indexOf(' ') + 1);
}
binary = binLocation.resolve("java");
process = exec(binLocation, binary.toString(), "-version");
if (process != null) {
jreVersion = process.err.readLine();
jreVersion = jreVersion.substring(jreVersion.indexOf('"') + 1, jreVersion.length() - 1);
}
libLocation = location.resolve("jre/lib/ext");
if (!Files.isDirectory(libLocation)) {
libLocation = location.resolve("lib/ext");
}
if (!Files.isDirectory(libLocation)) {
return;
}
Path libFile = libLocation.resolve(LIB_FILE_NAME);
if (!Files.isRegularFile(libFile)) {
return;
}
try {
ZipFile zip = new ZipFile(libFile.toString());
try {
ZipEntry entry = zip.getEntry("version.properties");
if (entry != null) {
InputStream stream = zip.getInputStream(entry);
Properties properties = new Properties();
properties.load(stream);
libVersion = properties.getProperty("version");
}
} finally {
zip.close();
}
} catch (ZipException e) {
// Do nothing
} catch (IOException e) {
// Do Nothing
}
}
protected static SvetovidProcess exec(String... command) {
return exec(null, command);
}
protected static SvetovidProcess exec(Path directory, String... command) {
SvetovidProcessBuilder builder = new SvetovidProcessBuilder(directory, command);
try {
return builder.start();
} catch (IOException e) {
return null;
}
}
public Path getLocation() {
return location;
}
public Path getBinLocation() {
return binLocation;
}
public Path getLibLocation() {
return libLocation;
}
public String getJdkVersion() {
return jdkVersion;
}
public String getJreVersion() {
return jreVersion;
}
public String getLibVersion() {
return libVersion;
}
}
|
package nak.nakloidGUI.gui.mainWindowViews;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.stream.Collectors;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.events.MouseWheelListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.ScrollBar;
import nak.nakloidGUI.NakloidGUI;
import nak.nakloidGUI.coredata.CoreData;
import nak.nakloidGUI.coredata.CoreData.CoreDataSubscriber;
import nak.nakloidGUI.gui.MainWindow.MainWindowDisplayMode;
import nak.nakloidGUI.gui.MainWindow.MusicalScales;
import nak.nakloidGUI.gui.NoteOption;
import nak.nakloidGUI.models.Note;
public class MainView extends Canvas implements CoreDataSubscriber {
private CoreData coreData;
private ScrollBar horizontalBar=getHorizontalBar(), verticalBar=getVerticalBar();
private Point viewSize=new Point(0, 0), offset=new Point(0,0);
private MainWindowDisplayMode displayMode = MainWindowDisplayMode.NOTES;
private int margin;
private double msByPixel = NakloidGUI.preferenceStore.getDouble("gui.mainWindow.baseMsByPixel");
private int noteHeight = NakloidGUI.preferenceStore.getInt("gui.mainWindow.baseNoteHeight");
final private Cursor cursorCross=new Cursor(null,SWT.CURSOR_CROSS), cursorArrow=new Cursor(null,SWT.CURSOR_ARROW);
private TreeMap<Integer, Integer> cursorLocus = new TreeMap<Integer, Integer>();
private List<MainViewListener> mainViewListeners = new ArrayList<MainViewListener>();
public interface MainViewListener {
public void mainViewHorizontalBarUpdated(SelectionEvent e);
public void mainViewVerticalBarUpdated(SelectionEvent e);
public void pitchesDrawn();
public void waveformSeeked();
}
public void addMainViewListener(MainViewListener mainViewListener) {
this.mainViewListeners.add(mainViewListener);
}
public void removeMainViewListener(MainViewListener mainViewListener) {
this.mainViewListeners.remove(mainViewListener);
}
public MainView(Composite parent, CoreData coreData) {
super(parent, SWT.NO_REDRAW_RESIZE|SWT.H_SCROLL|SWT.V_SCROLL|SWT.NO_BACKGROUND);
this.coreData = coreData;
coreData.addSubscribers(this);
margin = (int)((double)coreData.nakloidIni.output.ms_margin/msByPixel);
viewSize.x = (int)(((double)coreData.getScoreLength())/msByPixel) + margin;
viewSize.y = (getMidiNoteUpperLimit()-getMidiNoteLowerLimit()+1) * noteHeight;
GridData gdCnvMainView = new GridData(GridData.FILL_BOTH);
setLayoutData(gdCnvMainView);
CanvasPaintListener canvasPaintListener = new CanvasPaintListener();
addPaintListener(canvasPaintListener);
CanvasMouseListener canvasMouseListener = new CanvasMouseListener();
addMouseListener(canvasMouseListener);
addMouseWheelListener(canvasMouseListener);
addMouseMoveListener(canvasMouseListener);
addMouseTrackListener(canvasMouseListener);
horizontalBar.setEnabled(false);
horizontalBar.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
int hSelection = horizontalBar.getSelection();
int vSelection = verticalBar.getSelection();
scroll(-hSelection-offset.x, -vSelection-offset.y, 0, 0, viewSize.x, viewSize.y, false);
offset.x = -hSelection;
offset.y = -vSelection;
for (MainViewListener mainViewListener : mainViewListeners) {
mainViewListener.mainViewHorizontalBarUpdated(e);
}
}
});
verticalBar.setEnabled(false);
verticalBar.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
int hSelection = horizontalBar.getSelection();
int vSelection = verticalBar.getSelection();
scroll(-hSelection-offset.x, -vSelection-offset.y, 0, 0, viewSize.x, viewSize.y, false);
offset.x = -hSelection;
offset.y = -vSelection;
for (MainViewListener mainViewListener : mainViewListeners) {
mainViewListener.mainViewVerticalBarUpdated(e);
}
}
});
}
@Override
public void redraw() {
if (!this.isDisposed()) {
reloadScrollBarsBaseData();
int hPage = viewSize.x - getClientArea().width;
int vPage = viewSize.y - getClientArea().height;
int hSelection = horizontalBar.getSelection();
int vSelection = verticalBar.getSelection();
if (hSelection >= hPage) {
if (hPage <= 0) {
hSelection = 0;
}
offset.x = -hSelection;
}
if (vSelection >= vPage) {
if (vPage <= 0) {
vSelection = 0;
}
offset.y = -vSelection;
}
super.redraw();
}
}
public void redraw(MainWindowDisplayMode mainWindowDisplayMode) {
if (!this.isDisposed()) {
this.displayMode = mainWindowDisplayMode;
if (mainWindowDisplayMode == MainWindowDisplayMode.PITCHES) {
getShell().setCursor(cursorCross);
} else {
getShell().setCursor(cursorArrow);
}
super.redraw();
}
}
public void redraw(double msByPixel, int noteHeight) {
if (!this.isDisposed()) {
margin = (int)((double)coreData.nakloidIni.output.ms_margin/msByPixel);
viewSize.x = (int)(((double)coreData.getScoreLength())/msByPixel)+margin;
viewSize.y = (getMidiNoteUpperLimit()-getMidiNoteLowerLimit()+1)*noteHeight;
int clientHeight = getClientArea().height;
int clientWidth = getClientArea().width;
offset.x = (int)(this.msByPixel/(double)msByPixel*(offset.x-(clientWidth/2))) + (clientWidth/2);
offset.y = (int)((double)noteHeight/this.noteHeight*(offset.y-(clientHeight/2))) + (clientHeight/2);
if (-offset.x+clientWidth > viewSize.x) {
offset.x = clientWidth - viewSize.x;
} else if (offset.x > 0) {
offset.x = 0;
}
if (-offset.y+clientHeight > viewSize.y) {
offset.y = clientHeight - viewSize.y;
} else if (offset.y > 0) {
offset.y = 0;
}
reloadScrollBarsBaseData();
verticalBar.setSelection(-offset.y);
horizontalBar.setSelection(-offset.x);
scroll(offset.x, offset.y, offset.x, offset.y, viewSize.x, viewSize.y, false);
this.msByPixel = msByPixel;
this.noteHeight = noteHeight;
super.redraw();
}
}
public Point getTimelineSize() {
return viewSize;
}
public Point getOffset() {
return offset;
}
@Override
public void updateVocal() {}
@Override
public void updatePitches() {}
@Override
public void updateScore() {
margin = (int)((double)coreData.nakloidIni.output.ms_margin/msByPixel);
viewSize.x = (int)(((double)coreData.getScoreLength())/msByPixel)+margin;
viewSize.y = (getMidiNoteUpperLimit()-getMidiNoteLowerLimit()+1)*noteHeight;
reloadScrollBarsBaseData();
}
@Override
public void updateSongWaveform() {}
private class CanvasPaintListener implements PaintListener {
Rectangle clientArea = getClientArea();
@Override
public void paintControl(PaintEvent e) {
if (clientArea != getClientArea()) {
clientArea = getClientArea();
reloadScrollBarsBaseData();
}
Image image = new Image(e.display, getClientArea().width, getClientArea().height);
GC gcImage = new GC(image);
gcImage.setAntialias(SWT.ON);
// draw piano-roll background
for (int i=0; i<getMidiNoteUpperLimit()-getMidiNoteLowerLimit()+1; i++) {
int numMidiNote = getMidiNoteUpperLimit()-i;
gcImage.setForeground(e.display.getSystemColor(SWT.COLOR_GRAY));
if (MusicalScales.getMusicalScalesFromNumMidiNote(numMidiNote).isMajor()) {
gcImage.setBackground(e.display.getSystemColor(SWT.COLOR_GRAY));
gcImage.fillRectangle(new Rectangle(offset.x, i*noteHeight+offset.y, viewSize.x, noteHeight));
}
gcImage.setForeground(e.display.getSystemColor(SWT.COLOR_GRAY));
gcImage.drawLine(offset.x, (i+1)*noteHeight+offset.y, viewSize.x+offset.x, (i+1)*noteHeight+offset.y);
}
// draw notes
for (Note tmpNote : coreData.getNotes()) {
if (tmpNote.getBasePitch()<getMidiNoteUpperLimit() && tmpNote.getBasePitch()>getMidiNoteLowerLimit()) {
Point tmpPoint = new Point((int)(margin+(tmpNote.getStart()/msByPixel))+offset.x,
(getMidiNoteUpperLimit()-tmpNote.getBasePitch())*noteHeight+offset.y);
Rectangle tmpRectangle = new Rectangle(tmpPoint.x, tmpPoint.y, (int)(tmpNote.getLength()/msByPixel), noteHeight);
if (displayMode == MainWindowDisplayMode.PITCHES) {
gcImage.setAlpha(30);
}
gcImage.setBackground(e.display.getSystemColor(SWT.COLOR_DARK_MAGENTA));
gcImage.fillRectangle(tmpRectangle);
gcImage.setAlpha(255);
gcImage.setForeground(e.display.getSystemColor(SWT.COLOR_WHITE));
gcImage.drawRectangle(tmpRectangle);
gcImage.drawText(tmpNote.getPronunciationAliasString(), tmpPoint.x+3, tmpPoint.y+3, true);
}
}
// draw pitches
if (displayMode == MainWindowDisplayMode.PITCHES) {
// saved pitches
gcImage.setForeground(e.display.getSystemColor(SWT.COLOR_DARK_CYAN));
double[] midiNoteNumbers = new double[coreData.getPitches().size()];
midiNoteNumbers = coreData.getPitches().getMidiNoteNumbers();
int[] tmpPitchPositions = new int[(int)(midiNoteNumbers.length/msByPixel)*2+2];
tmpPitchPositions[0] = 0;
tmpPitchPositions[1] = viewSize.y;
for (int i=0; i<tmpPitchPositions.length/2-1; i++) {
tmpPitchPositions[(i+1)*2] = (int)(i+offset.x);
double tmpPitch = midiNoteNumbers[(int)(i*msByPixel)];
tmpPitchPositions[(i+1)*2+1] = (tmpPitch>getMidiNoteLowerLimit()&&tmpPitch<getMidiNoteUpperLimit())?midiNoteNumber2pos(tmpPitch):viewSize.y;
}
gcImage.drawPolyline(tmpPitchPositions);
// temporary pitches
gcImage.setForeground(e.display.getSystemColor(SWT.COLOR_CYAN));
int[] tmpCursorLocus = new int[cursorLocus.size()*2];
int i = 0;
for (Entry<Integer, Integer> entry : cursorLocus.entrySet()) {
tmpCursorLocus[i] = entry.getKey();
tmpCursorLocus[i+1] = entry.getValue();
i += 2;
}
gcImage.drawPolyline(tmpCursorLocus);
}
// draw seekbar
gcImage.setForeground(e.display.getSystemColor(SWT.COLOR_MAGENTA));
if (coreData.getSongWaveform()!=null && coreData.getSongWaveform().isLoaded()) {
int tmpSeekPoint = (int)(coreData.getSongWaveform().getMicrosecond()/1000/msByPixel + offset.x);
gcImage.drawLine(tmpSeekPoint, 0, tmpSeekPoint, viewSize.y);
}
e.gc.drawImage(image, 0, 0);
gcImage.dispose();
image.dispose();
}
}
private class CanvasMouseListener implements MouseListener, MouseWheelListener, MouseMoveListener, MouseTrackListener {
boolean writingMode = false;
int maxCursorX=0, minCursorX=0;
@Override
public void mouseDoubleClick(MouseEvent e) {
Point clickPoint = new Point(e.x, e.y);
Note clickedNote = null;
for (Note tmpNote : coreData.getNotes()) {
if (tmpNote.getBasePitch()<getMidiNoteUpperLimit() && tmpNote.getBasePitch()>getMidiNoteLowerLimit()) {
Point tmpPoint = new Point((int)(tmpNote.getStart()/msByPixel)+margin+offset.x,
(getMidiNoteUpperLimit()-tmpNote.getBasePitch())*noteHeight+offset.y);
Rectangle tmpRectangle = new Rectangle(tmpPoint.x, tmpPoint.y, (int)(tmpNote.getLength()/msByPixel), noteHeight);
if (tmpRectangle.contains(clickPoint)) {
clickedNote = tmpNote;
break;
}
}
}
if (clickedNote != null) {
NoteOption dialog = new NoteOption(getShell(), coreData, clickedNote);
dialog.open();
}
}
@Override
public void mouseScrolled(MouseEvent e) {
verticalBar.setSelection(verticalBar.getSelection()-e.count);
}
@Override
public void mouseMove(MouseEvent e) {
if (writingMode && getClientArea().contains(e.x, e.y)) {
if (e.x > maxCursorX) {
maxCursorX = e.x;
} else if (e.x < minCursorX) {
minCursorX = e.x;
} else {
return;
}
cursorLocus.put(e.x, e.y);
mainViewListeners.stream().forEach(MainViewListener::pitchesDrawn);
}
}
@Override
public void mouseDown(MouseEvent e) {
if (displayMode == MainWindowDisplayMode.PITCHES) {
writingMode = true;
maxCursorX = minCursorX = e.x;
cursorLocus.put(e.x, e.y);
mainViewListeners.stream().forEach(MainViewListener::pitchesDrawn);
}
}
@Override
public void mouseUp(MouseEvent e) {
writingMode = false;
if (cursorLocus.size() > 0) {
List<Integer> cursorKeys = cursorLocus.keySet().stream()
.map(i->(int)(i*msByPixel))
.collect(Collectors.toList());
Integer[] cursorValues = cursorLocus.values().toArray(new Integer[cursorLocus.size()]);
ArrayList<Double> tmpMidiNoteNumbers = new ArrayList<Double>();
for (int i=0; i<cursorLocus.size()-1; i++) {
int tmp = cursorKeys.get(i+1) - cursorKeys.get(i);
for (int j=0; j<tmp; j++) {
tmpMidiNoteNumbers.add(pos2midiNoteNumber((cursorValues[i]*(tmp-j)+(cursorValues[i+1]*j))/tmp));
}
}
tmpMidiNoteNumbers.add(pos2midiNoteNumber(cursorValues[cursorValues.length-1]));
coreData.replaceMidiNoteNumbers(tmpMidiNoteNumbers, (int)((minCursorX-offset.x)*msByPixel));
try {
coreData.savePitches();
} catch (IOException e1) {
MessageDialog.openError(getShell(), "NakloidGUI", "\n"+e1.getMessage());
}
cursorLocus.clear();
mainViewListeners.stream().forEach(MainViewListener::pitchesDrawn);
}
}
@Override
public void mouseEnter(MouseEvent e) {
if (displayMode == MainWindowDisplayMode.PITCHES) {
getShell().setCursor(cursorCross);
}
}
@Override
public void mouseExit(MouseEvent e) {
getShell().setCursor(cursorArrow);
}
@Override
public void mouseHover(MouseEvent e) {}
}
private void reloadScrollBarsBaseData() {
Rectangle clientArea = getClientArea();
if (clientArea.width>0 && viewSize.x>clientArea.width) {
horizontalBar.setEnabled(true);
horizontalBar.setMaximum(viewSize.x);
horizontalBar.setPageIncrement((int)(clientArea.width*0.8));
horizontalBar.setThumb(clientArea.width);
} else {
horizontalBar.setEnabled(false);
}
if (clientArea.height>0 && viewSize.y > clientArea.height) {
verticalBar.setEnabled(true);
verticalBar.setMaximum(viewSize.y);
verticalBar.setPageIncrement((int)(clientArea.height*0.8));
verticalBar.setThumb(clientArea.height);
} else {
verticalBar.setEnabled(false);
}
}
private int getMidiNoteUpperLimit() {
return NakloidGUI.preferenceStore.getInt("gui.mainWindow.numMidiNoteUpperLimit");
}
private int getMidiNoteLowerLimit() {
return NakloidGUI.preferenceStore.getInt("gui.mainWindow.numMidiNoteLowerLimit");
}
private int midiNoteNumber2pos(double midiNoteNumber) {
return (int)((getMidiNoteUpperLimit()-midiNoteNumber)*noteHeight) + offset.y + (noteHeight/2);
}
private double pos2midiNoteNumber(int pos) {
return getMidiNoteUpperLimit() - (((double)pos-(noteHeight/2+offset.y))/noteHeight);
}
}
|
package nars.core.build;
import nars.core.ConceptProcessor;
import nars.core.Memory;
import nars.core.NARBuilder;
import nars.core.Param;
import nars.core.control.SequentialMemoryCycle;
import nars.entity.Concept;
import nars.entity.ConceptBuilder;
import nars.entity.Task;
import nars.entity.TaskLink;
import nars.entity.TermLink;
import nars.language.Term;
import nars.storage.AbstractBag;
import nars.storage.Bag;
/**
* Default set of NAR parameters which have been classically used for development.
*/
public class DefaultNARBuilder extends NARBuilder implements ConceptBuilder {
public int taskLinkBagLevels;
/** Size of TaskLinkBag */
public int taskLinkBagSize;
public int termLinkBagLevels;
/** Size of TermLinkBag */
public int termLinkBagSize;
/** determines maximum number of concepts */
private int conceptBagSize;
/** Size of TaskBuffer */
private int taskBufferSize = 10;
public DefaultNARBuilder() {
super();
setConceptBagLevels(100);
setConceptBagSize(1000);
setTaskLinkBagLevels(100);
setTaskLinkBagSize(20);
setTermLinkBagLevels(100);
setTermLinkBagSize(100);
setTaskBufferSize(10);
}
@Override
public Param newParam() {
Param p = new Param();
p.noiseLevel.set(100);
//Cycle control
p.cycleMemory.set(1);
p.cycleInputTasks.set(1);
p.decisionThreshold.set(0.30);
p.conceptCyclesToForget.set(10);
p.taskCyclesToForget.set(20);
p.beliefCyclesToForget.set(50);
p.newTaskCyclesToForget.set(10);
p.conceptBeliefsMax.set(7);
p.conceptQuestionsMax.set(5);
p.duration.set(5);
p.shortTermMemorySize.set(15);
p.contrapositionPriority.set(30);
p.termLinkMaxReasoned.set(3);
p.termLinkMaxMatched.set(10);
p.termLinkRecordLength.set(10);
//NAL9 experimental
p.experimentalNarsPlus.set(false);
p.internalExperience.set(false);
p.abbreviationMinComplexity.set(20);
p.abbreviationMinQuality.set(0.95f);
return p;
}
@Override
public ConceptProcessor newConceptProcessor(Param p, ConceptBuilder c) {
return new SequentialMemoryCycle(newConceptBag(p), c);
}
@Override
public ConceptBuilder getConceptBuilder() {
return this;
}
@Override
public Concept newConcept(Term t, Memory m) {
AbstractBag<TaskLink> taskLinks = new Bag<>(getTaskLinkBagLevels(), getTaskLinkBagSize(), m.param.taskCyclesToForget);
AbstractBag<TermLink> termLinks = new Bag<>(getTermLinkBagLevels(), getTermLinkBagSize(), m.param.beliefCyclesToForget);
return new Concept(t, taskLinks, termLinks, m);
}
protected AbstractBag<Concept> newConceptBag(Param p) {
return new Bag(getConceptBagLevels(), getConceptBagSize(), p.conceptCyclesToForget);
}
@Override
public AbstractBag<Task> newNovelTaskBag(Param p) {
return new Bag<>(getConceptBagLevels(), getTaskBufferSize(), p.newTaskCyclesToForget);
}
public int getConceptBagSize() { return conceptBagSize; }
public DefaultNARBuilder setConceptBagSize(int conceptBagSize) { this.conceptBagSize = conceptBagSize; return this; }
/** Level granularity in Bag, usually 100 (two digits) */
private int conceptBagLevels;
public int getConceptBagLevels() { return conceptBagLevels; }
public DefaultNARBuilder setConceptBagLevels(int bagLevels) { this.conceptBagLevels = bagLevels; return this; }
/**
* @return the taskLinkBagLevels
*/
public int getTaskLinkBagLevels() {
return taskLinkBagLevels;
}
public DefaultNARBuilder setTaskLinkBagLevels(int taskLinkBagLevels) {
this.taskLinkBagLevels = taskLinkBagLevels;
return this;
}
public void setTaskBufferSize(int taskBufferSize) {
this.taskBufferSize = taskBufferSize;
}
public int getTaskBufferSize() {
return taskBufferSize;
}
public int getTaskLinkBagSize() {
return taskLinkBagSize;
}
public DefaultNARBuilder setTaskLinkBagSize(int taskLinkBagSize) {
this.taskLinkBagSize = taskLinkBagSize;
return this;
}
public int getTermLinkBagLevels() {
return termLinkBagLevels;
}
public DefaultNARBuilder setTermLinkBagLevels(int termLinkBagLevels) {
this.termLinkBagLevels = termLinkBagLevels;
return this;
}
public int getTermLinkBagSize() {
return termLinkBagSize;
}
public DefaultNARBuilder setTermLinkBagSize(int termLinkBagSize) {
this.termLinkBagSize = termLinkBagSize;
return this;
}
public static class CommandLineNARBuilder extends DefaultNARBuilder {
private final Param param;
@Override public Param newParam() {
return param;
}
public CommandLineNARBuilder(String[] args) {
super();
param = super.newParam();
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if ("--silence".equals(arg)) {
arg = args[++i];
int sl = Integer.parseInt(arg);
param.noiseLevel.set(100-sl);
}
if ("--noise".equals(arg)) {
arg = args[++i];
int sl = Integer.parseInt(arg);
param.noiseLevel.set(sl);
}
}
}
/**
* Decode the silence level
*
* @param param Given argument
* @return Whether the argument is not the silence level
*/
public static boolean isReallyFile(String param) {
return !"--silence".equals(param);
}
}
// /** Concept decay rate in ConceptBag, in [1, 99]. */
// private static final int CONCEPT_CYCLES_TO_FORGET = 10;
// /** TaskLink decay rate in TaskLinkBag, in [1, 99]. */
// private static final int TASK_LINK_CYCLES_TO_FORGET = 20;
// /** TermLink decay rate in TermLinkBag, in [1, 99]. */
// private static final int TERM_LINK_CYCLES_TO_FORGET = 50;
// /** Task decay rate in TaskBuffer, in [1, 99]. */
// private static final int NEW_TASK_FORGETTING_CYCLE = 10;
}
|
package com.pmovil.toast;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.component.Status;
import net.rim.device.api.ui.UiApplication;
public class NativeToastImpl {
//this can not be implemented...
public boolean isShown() {
return false;
}
public void showText(final String param, final int param1) {
/*
public static void show(String message, Bitmap bitmap, int time, long style, boolean allowDismiss, boolean block, int priority)
Shows a status screen of a particular style for specified time.
Invoke this method to show a status screen of a particular style to the user.
Parameters:
message - Message to display.
bitmap - Icon to show in the left part of this screen.
time - Milliseconds for which this screen should remain visible.
style - The style of the status screen
allowDismiss - If true, allows the status screen to be dismissed early.
block - Causes this method to block until the user dismisses this screen, or until the number of seconds specified in the time parameter passes. This parameter has no effect if the Status.GLOBAL_STATUS style is set.
priority - Display priority for this screen, if it is a Status.GLOBAL_STATUS screen.
Throws:
RuntimeException - If no timer is available for use by this screen.
*/
UiApplication.getApplication().invokeLater(new Runnable() {
public void run() {
Status.show(param, Bitmap.getPredefinedBitmap(Bitmap.INFORMATION), param1, 0, true, false, 0);
}
});
}
public boolean isSupported() {
return true;
}
}
|
package VASSAL.build.module;
import VASSAL.tools.ProblemDialog;
import static java.lang.Math.round;
import java.awt.AWTEventMulticaster;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Component;
import java.awt.Composite;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.ActionListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
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.geom.AffineTransform;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.OverlayLayout;
import javax.swing.RootPaneContainer;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import net.miginfocom.swing.MigLayout;
import org.jdesktop.animation.timing.Animator;
import org.jdesktop.animation.timing.TimingTargetAdapter;
import org.w3c.dom.Element;
import VASSAL.build.AbstractConfigurable;
import VASSAL.build.AutoConfigurable;
import VASSAL.build.Buildable;
import VASSAL.build.Configurable;
import VASSAL.build.GameModule;
import VASSAL.build.IllegalBuildException;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.build.module.map.BoardPicker;
import VASSAL.build.module.map.CounterDetailViewer;
import VASSAL.build.module.map.DefaultPieceCollection;
import VASSAL.build.module.map.DrawPile;
import VASSAL.build.module.map.Drawable;
import VASSAL.build.module.map.ForwardToChatter;
import VASSAL.build.module.map.ForwardToKeyBuffer;
import VASSAL.build.module.map.GlobalMap;
import VASSAL.build.module.map.HidePiecesButton;
import VASSAL.build.module.map.HighlightLastMoved;
import VASSAL.build.module.map.ImageSaver;
import VASSAL.build.module.map.KeyBufferer;
import VASSAL.build.module.map.LOS_Thread;
import VASSAL.build.module.map.LayeredPieceCollection;
import VASSAL.build.module.map.MapCenterer;
import VASSAL.build.module.map.MapShader;
import VASSAL.build.module.map.MassKeyCommand;
import VASSAL.build.module.map.MenuDisplayer;
import VASSAL.build.module.map.PieceCollection;
import VASSAL.build.module.map.PieceMover;
import VASSAL.build.module.map.PieceRecenterer;
import VASSAL.build.module.map.Scroller;
import VASSAL.build.module.map.SelectionHighlighters;
import VASSAL.build.module.map.SetupStack;
import VASSAL.build.module.map.StackExpander;
import VASSAL.build.module.map.StackMetrics;
import VASSAL.build.module.map.TextSaver;
import VASSAL.build.module.map.Zoomer;
import VASSAL.build.module.map.boardPicker.Board;
import VASSAL.build.module.map.boardPicker.board.MapGrid;
import VASSAL.build.module.map.boardPicker.board.Region;
import VASSAL.build.module.map.boardPicker.board.RegionGrid;
import VASSAL.build.module.map.boardPicker.board.ZonedGrid;
import VASSAL.build.module.map.boardPicker.board.mapgrid.Zone;
import VASSAL.build.module.properties.ChangePropertyCommandEncoder;
import VASSAL.build.module.properties.GlobalProperties;
import VASSAL.build.module.properties.MutablePropertiesContainer;
import VASSAL.build.module.properties.MutableProperty;
import VASSAL.build.module.properties.PropertySource;
import VASSAL.build.widget.MapWidget;
import VASSAL.command.AddPiece;
import VASSAL.command.Command;
import VASSAL.command.MoveTracker;
import VASSAL.configure.BooleanConfigurer;
import VASSAL.configure.ColorConfigurer;
import VASSAL.configure.CompoundValidityChecker;
import VASSAL.configure.Configurer;
import VASSAL.configure.ConfigurerFactory;
import VASSAL.configure.IconConfigurer;
import VASSAL.configure.IntConfigurer;
import VASSAL.configure.MandatoryComponent;
import VASSAL.configure.NamedHotKeyConfigurer;
import VASSAL.configure.PlayerIdFormattedStringConfigurer;
import VASSAL.configure.VisibilityCondition;
import VASSAL.counters.ColoredBorder;
import VASSAL.counters.Deck;
import VASSAL.counters.DeckVisitor;
import VASSAL.counters.DeckVisitorDispatcher;
import VASSAL.counters.DragBuffer;
import VASSAL.counters.GamePiece;
import VASSAL.counters.Highlighter;
import VASSAL.counters.KeyBuffer;
import VASSAL.counters.PieceFinder;
import VASSAL.counters.PieceVisitorDispatcher;
import VASSAL.counters.Properties;
import VASSAL.counters.ReportState;
import VASSAL.counters.Stack;
import VASSAL.i18n.Resources;
import VASSAL.i18n.TranslatableConfigurerFactory;
import VASSAL.preferences.PositionOption;
import VASSAL.preferences.Prefs;
import VASSAL.tools.AdjustableSpeedScrollPane;
import VASSAL.tools.ComponentSplitter;
import VASSAL.tools.KeyStrokeSource;
import VASSAL.tools.LaunchButton;
import VASSAL.tools.NamedKeyStroke;
import VASSAL.tools.ToolBarComponent;
import VASSAL.tools.UniqueIdManager;
import VASSAL.tools.WrapLayout;
import VASSAL.tools.menu.MenuManager;
import VASSAL.tools.swing.SplitPane;
import VASSAL.tools.swing.SwingUtils;
/**
* The Map is the main component for displaying and containing {@link GamePiece}s during play. Pieces are displayed on
* a Map and moved by clicking and dragging. Keyboard events are forwarded to selected pieces. Multiple map windows are
* supported in a single game, with dragging between windows allowed.
* <p>
* A Map may contain many different {@link Buildable} subcomponents. Components which are added directly to a Map are
* contained in the <code>VASSAL.build.module.map</code> package
*/
public class Map extends AbstractConfigurable implements GameComponent, MouseListener, MouseMotionListener, DropTargetListener, Configurable,
UniqueIdManager.Identifyable, ToolBarComponent, MutablePropertiesContainer, PropertySource, PlayerRoster.SideChangeListener {
protected static boolean changeReportingEnabled = true;
protected String mapID = ""; //$NON-NLS-1$
protected String mapName = ""; //$NON-NLS-1$
protected static final String MAIN_WINDOW_HEIGHT = "mainWindowHeight"; //$NON-NLS-1$
protected static final UniqueIdManager idMgr = new UniqueIdManager("Map"); //$NON-NLS-1$
protected JPanel theMap;
protected ArrayList<Drawable> drawComponents = new ArrayList<>();
protected JLayeredPane layeredPane = new JLayeredPane();
protected JScrollPane scroll;
/**
* @deprecated type will change to {@link SplitPane}
*/
@Deprecated(since = "2020-08-05", forRemoval = true)
protected ComponentSplitter.SplitPane mainWindowDock;
protected BoardPicker picker;
protected JToolBar toolBar = new JToolBar();
protected Zoomer zoom;
protected StackMetrics metrics;
protected Dimension edgeBuffer = new Dimension(0, 0);
protected Color bgColor = Color.white;
protected LaunchButton launchButton;
protected boolean useLaunchButton = false;
protected boolean useLaunchButtonEdit = false;
protected String markMovedOption = GlobalOptions.ALWAYS;
protected String markUnmovedIcon = "/images/unmoved.gif"; //$NON-NLS-1$
protected String markUnmovedText = ""; //$NON-NLS-1$
protected String markUnmovedTooltip = Resources.getString("Map.mark_unmoved"); //$NON-NLS-1$
protected MouseListener multicaster = null;
protected ArrayList<MouseListener> mouseListenerStack = new ArrayList<>();
protected List<Board> boards = new CopyOnWriteArrayList<>();
protected int[][] boardWidths; // Cache of board widths by row/column
protected int[][] boardHeights; // Cache of board heights by row/column
protected PieceCollection pieces = new DefaultPieceCollection();
protected Highlighter highlighter = new ColoredBorder();
protected ArrayList<Highlighter> highlighters = new ArrayList<>();
protected boolean clearFirst = false; // Whether to clear the display before
// drawing the map
protected boolean hideCounters = false; // Option to hide counters to see
// map
protected float pieceOpacity = 1.0f;
protected boolean allowMultiple = false;
protected VisibilityCondition visibilityCondition;
protected DragGestureListener dragGestureListener;
protected String moveWithinFormat;
protected String moveToFormat;
protected String createFormat;
protected String changeFormat = "$" + MESSAGE + "$"; //$NON-NLS-1$ //$NON-NLS-2$
protected NamedKeyStroke moveKey;
protected String tooltip = ""; //$NON-NLS-1$
protected MutablePropertiesContainer propsContainer = new MutablePropertiesContainer.Impl();
protected PropertyChangeListener repaintOnPropertyChange = evt -> repaint();
protected PieceMover pieceMover;
protected KeyListener[] saveKeyListeners = null;
public Map() {
getView();
theMap.addMouseListener(this);
if (shouldDockIntoMainWindow()) {
toolBar.setLayout(new MigLayout("ins 0,gapx 0,hidemode 3"));
} else {
toolBar.setLayout(new WrapLayout(WrapLayout.LEFT, 0, 0));
}
toolBar.setAlignmentX(0.0F);
toolBar.setFloatable(false);
}
public Component getComponent() {
return theMap;
}
// Global Change Reporting control
public static void setChangeReportingEnabled(boolean b) {
changeReportingEnabled = b;
}
public static boolean isChangeReportingEnabled() {
return changeReportingEnabled;
}
public static final String NAME = "mapName"; //$NON-NLS-1$
public static final String MARK_MOVED = "markMoved"; //$NON-NLS-1$
public static final String MARK_UNMOVED_ICON = "markUnmovedIcon"; //$NON-NLS-1$
public static final String MARK_UNMOVED_TEXT = "markUnmovedText"; //$NON-NLS-1$
public static final String MARK_UNMOVED_TOOLTIP = "markUnmovedTooltip"; //$NON-NLS-1$
public static final String EDGE_WIDTH = "edgeWidth"; //$NON-NLS-1$
public static final String EDGE_HEIGHT = "edgeHeight"; //$NON-NLS-1$
public static final String BACKGROUND_COLOR = "backgroundcolor";
public static final String HIGHLIGHT_COLOR = "color"; //$NON-NLS-1$
public static final String HIGHLIGHT_THICKNESS = "thickness"; //$NON-NLS-1$
public static final String ALLOW_MULTIPLE = "allowMultiple"; //$NON-NLS-1$
public static final String USE_LAUNCH_BUTTON = "launch"; //$NON-NLS-1$
public static final String BUTTON_NAME = "buttonName"; //$NON-NLS-1$
public static final String TOOLTIP = "tooltip"; //$NON-NLS-1$
public static final String ICON = "icon"; //$NON-NLS-1$
public static final String HOTKEY = "hotkey"; //$NON-NLS-1$
public static final String SUPPRESS_AUTO = "suppressAuto"; //$NON-NLS-1$
public static final String MOVE_WITHIN_FORMAT = "moveWithinFormat"; //$NON-NLS-1$
public static final String MOVE_TO_FORMAT = "moveToFormat"; //$NON-NLS-1$
public static final String CREATE_FORMAT = "createFormat"; //$NON-NLS-1$
public static final String CHANGE_FORMAT = "changeFormat"; //$NON-NLS-1$
public static final String MOVE_KEY = "moveKey"; //$NON-NLS-1$
public static final String MOVING_STACKS_PICKUP_UNITS = "movingStacksPickupUnits"; //$NON-NLS-1$
@Override
public void setAttribute(String key, Object value) {
if (NAME.equals(key)) {
setMapName((String) value);
} else if (MARK_MOVED.equals(key)) {
markMovedOption = (String) value;
} else if (MARK_UNMOVED_ICON.equals(key)) {
markUnmovedIcon = (String) value;
if (pieceMover != null) {
pieceMover.setAttribute(key, value);
}
} else if (MARK_UNMOVED_TEXT.equals(key)) {
markUnmovedText = (String) value;
if (pieceMover != null) {
pieceMover.setAttribute(key, value);
}
} else if (MARK_UNMOVED_TOOLTIP.equals(key)) {
markUnmovedTooltip = (String) value;
} else if ("edge".equals(key)) { // Backward-compatible //$NON-NLS-1$
String s = (String) value;
int i = s.indexOf(','); //$NON-NLS-1$
if (i > 0) {
edgeBuffer = new Dimension(Integer.parseInt(s.substring(0, i)), Integer.parseInt(s.substring(i + 1)));
}
} else if (EDGE_WIDTH.equals(key)) {
if (value instanceof String) {
value = Integer.valueOf((String) value);
}
try {
edgeBuffer = new Dimension((Integer) value, edgeBuffer.height);
} catch (NumberFormatException ex) {
throw new IllegalBuildException(ex);
}
} else if (EDGE_HEIGHT.equals(key)) {
if (value instanceof String) {
value = Integer.valueOf((String) value);
}
try {
edgeBuffer = new Dimension(edgeBuffer.width, (Integer) value);
} catch (NumberFormatException ex) {
throw new IllegalBuildException(ex);
}
} else if (BACKGROUND_COLOR.equals(key)) {
if (value instanceof String) {
value = ColorConfigurer.stringToColor((String) value);
}
bgColor = (Color) value;
} else if (ALLOW_MULTIPLE.equals(key)) {
if (value instanceof String) {
value = Boolean.valueOf((String) value);
}
allowMultiple = (Boolean) value;
if (picker != null) {
picker.setAllowMultiple(allowMultiple);
}
} else if (HIGHLIGHT_COLOR.equals(key)) {
if (value instanceof String) {
value = ColorConfigurer.stringToColor((String) value);
}
if (value != null) {
((ColoredBorder) highlighter).setColor((Color) value);
}
} else if (HIGHLIGHT_THICKNESS.equals(key)) {
if (value instanceof String) {
value = Integer.valueOf((String) value);
}
if (highlighter instanceof ColoredBorder) {
((ColoredBorder) highlighter).setThickness((Integer) value);
}
} else if (USE_LAUNCH_BUTTON.equals(key)) {
if (value instanceof String) {
value = Boolean.valueOf((String) value);
}
useLaunchButtonEdit = (Boolean) value;
launchButton.setVisible(useLaunchButton);
} else if (SUPPRESS_AUTO.equals(key)) {
if (value instanceof String) {
value = Boolean.valueOf((String) value);
}
if (Boolean.TRUE.equals(value)) {
moveWithinFormat = ""; //$NON-NLS-1$
}
} else if (MOVE_WITHIN_FORMAT.equals(key)) {
moveWithinFormat = (String) value;
} else if (MOVE_TO_FORMAT.equals(key)) {
moveToFormat = (String) value;
} else if (CREATE_FORMAT.equals(key)) {
createFormat = (String) value;
} else if (CHANGE_FORMAT.equals(key)) {
changeFormat = (String) value;
} else if (MOVE_KEY.equals(key)) {
if (value instanceof String) {
value = NamedHotKeyConfigurer.decode((String) value);
}
moveKey = (NamedKeyStroke) value;
} else if (TOOLTIP.equals(key)) {
tooltip = (String) value;
launchButton.setAttribute(key, value);
} else {
launchButton.setAttribute(key, value);
}
}
@Override
public String getAttributeValueString(String key) {
if (NAME.equals(key)) {
return getMapName();
} else if (MARK_MOVED.equals(key)) {
return markMovedOption;
} else if (MARK_UNMOVED_ICON.equals(key)) {
return markUnmovedIcon;
} else if (MARK_UNMOVED_TEXT.equals(key)) {
return markUnmovedText;
} else if (MARK_UNMOVED_TOOLTIP.equals(key)) {
return markUnmovedTooltip;
} else if (EDGE_WIDTH.equals(key)) {
return String.valueOf(edgeBuffer.width); //$NON-NLS-1$
} else if (EDGE_HEIGHT.equals(key)) {
return String.valueOf(edgeBuffer.height); //$NON-NLS-1$
} else if (BACKGROUND_COLOR.equals(key)) {
return ColorConfigurer.colorToString(bgColor);
} else if (ALLOW_MULTIPLE.equals(key)) {
return String.valueOf(picker.isAllowMultiple()); //$NON-NLS-1$
} else if (HIGHLIGHT_COLOR.equals(key)) {
if (highlighter instanceof ColoredBorder) {
return ColorConfigurer.colorToString(
((ColoredBorder) highlighter).getColor());
} else {
return null;
}
} else if (HIGHLIGHT_THICKNESS.equals(key)) {
if (highlighter instanceof ColoredBorder) {
return String.valueOf(
((ColoredBorder) highlighter).getThickness()); //$NON-NLS-1$
} else {
return null;
}
} else if (USE_LAUNCH_BUTTON.equals(key)) {
return String.valueOf(useLaunchButtonEdit);
} else if (MOVE_WITHIN_FORMAT.equals(key)) {
return getMoveWithinFormat();
} else if (MOVE_TO_FORMAT.equals(key)) {
return getMoveToFormat();
} else if (CREATE_FORMAT.equals(key)) {
return getCreateFormat();
} else if (CHANGE_FORMAT.equals(key)) {
return getChangeFormat();
} else if (MOVE_KEY.equals(key)) {
return NamedHotKeyConfigurer.encode(moveKey);
} else if (TOOLTIP.equals(key)) {
return (tooltip == null || tooltip.length() == 0)
? launchButton.getAttributeValueString(name) : tooltip;
} else {
return launchButton.getAttributeValueString(key);
}
}
@Override
public void build(Element e) {
ActionListener al = e1 -> {
if (mainWindowDock == null && launchButton.isEnabled() && theMap.getTopLevelAncestor() != null) {
theMap.getTopLevelAncestor().setVisible(!theMap.getTopLevelAncestor().isVisible());
}
};
launchButton = new LaunchButton(Resources.getString("Editor.Map.map"), TOOLTIP, BUTTON_NAME, HOTKEY, ICON, al);
launchButton.setEnabled(false);
launchButton.setVisible(false);
if (e != null) {
super.build(e);
getBoardPicker();
getStackMetrics();
} else {
getBoardPicker();
getStackMetrics();
addChild(new ForwardToKeyBuffer());
addChild(new Scroller());
addChild(new ForwardToChatter());
addChild(new MenuDisplayer());
addChild(new MapCenterer());
addChild(new StackExpander());
addChild(new PieceMover());
addChild(new KeyBufferer());
addChild(new ImageSaver());
addChild(new CounterDetailViewer());
setMapName("Main Map");
}
if (getComponentsOf(GlobalProperties.class).isEmpty()) {
addChild(new GlobalProperties());
}
if (getComponentsOf(SelectionHighlighters.class).isEmpty()) {
addChild(new SelectionHighlighters());
}
if (getComponentsOf(HighlightLastMoved.class).isEmpty()) {
addChild(new HighlightLastMoved());
}
setup(false);
}
private void addChild(Buildable b) {
add(b);
b.addTo(this);
}
/**
* Every map must include a {@link BoardPicker} as one of its build components
*/
public void setBoardPicker(BoardPicker picker) {
if (this.picker != null) {
GameModule.getGameModule().removeCommandEncoder(picker);
GameModule.getGameModule().getGameState().addGameComponent(picker);
}
this.picker = picker;
if (picker != null) {
picker.setAllowMultiple(allowMultiple);
GameModule.getGameModule().addCommandEncoder(picker);
GameModule.getGameModule().getGameState().addGameComponent(picker);
}
}
/**
* Every map must include a {@link BoardPicker} as one of its build components
*
* @return the BoardPicker for this map
*/
public BoardPicker getBoardPicker() {
if (picker == null) {
picker = new BoardPicker();
picker.build(null);
add(picker);
picker.addTo(this);
}
return picker;
}
/**
* A map may include a {@link Zoomer} as one of its build components
*/
public void setZoomer(Zoomer z) {
zoom = z;
}
/**
* A map may include a {@link Zoomer} as one of its build components
*
* @return the Zoomer for this map
*/
public Zoomer getZoomer() {
return zoom;
}
/**
* Every map must include a {@link StackMetrics} as one of its build components, which governs the stacking behavior
* of GamePieces on the map
*/
public void setStackMetrics(StackMetrics sm) {
metrics = sm;
}
/**
* Every map must include a {@link StackMetrics} as one of its build
* components, which governs the stacking behavior of GamePieces on the map
*
* @return the StackMetrics for this map
*/
public StackMetrics getStackMetrics() {
if (metrics == null) {
metrics = new StackMetrics();
metrics.build(null);
add(metrics);
metrics.addTo(this);
}
return metrics;
}
/**
* @return the current zoom factor for the map
*/
public double getZoom() {
return zoom == null ? 1.0 : zoom.getZoomFactor();
}
/**
* @return the toolbar for this map's window
*/
@Override
public JToolBar getToolBar() {
return toolBar;
}
/**
* Add a {@link Drawable} component to this map
*/
public void addDrawComponent(Drawable theComponent) {
drawComponents.add(theComponent);
}
/**
* Remove a {@link Drawable} component from this map
*/
public void removeDrawComponent(Drawable theComponent) {
drawComponents.remove(theComponent);
}
/**
* Expects to be added to a {@link GameModule}. Determines a unique id for
* this Map. Registers itself as {@link KeyStrokeSource}. Registers itself
* as a {@link GameComponent}. Registers itself as a drop target and drag
* source.
*
* @see #getId
* @see DragBuffer
*/
@Override
public void addTo(Buildable b) {
useLaunchButton = useLaunchButtonEdit;
idMgr.add(this);
final GameModule g = GameModule.getGameModule();
g.addCommandEncoder(new ChangePropertyCommandEncoder(this));
validator = new CompoundValidityChecker(
new MandatoryComponent(this, BoardPicker.class),
new MandatoryComponent(this, StackMetrics.class)).append(idMgr);
final DragGestureListener dgl = dge -> {
if (dragGestureListener != null &&
mouseListenerStack.isEmpty() &&
SwingUtils.isDragTrigger(dge)) {
dragGestureListener.dragGestureRecognized(dge);
}
};
DragSource.getDefaultDragSource().createDefaultDragGestureRecognizer(
theMap, DnDConstants.ACTION_MOVE, dgl);
theMap.setDropTarget(PieceMover.DragHandler.makeDropTarget(
theMap, DnDConstants.ACTION_MOVE, this));
g.getGameState().addGameComponent(this);
g.getToolBar().add(launchButton);
if (shouldDockIntoMainWindow()) {
final IntConfigurer config =
new IntConfigurer(MAIN_WINDOW_HEIGHT, null, -1);
Prefs.getGlobalPrefs().addOption(null, config);
mainWindowDock = g.getPlayerWindow().splitControlPanel(layeredPane, SplitPane.HIDE_BOTTOM, true);
mainWindowDock.setResizeWeight(0.0);
g.addKeyStrokeSource(
new KeyStrokeSource(theMap, JComponent.WHEN_FOCUSED));
} else {
g.addKeyStrokeSource(
new KeyStrokeSource(theMap, JComponent.WHEN_IN_FOCUSED_WINDOW));
}
// Fix for bug 1630993: toolbar buttons not appearing
toolBar.addHierarchyListener(new HierarchyListener() {
@Override
public void hierarchyChanged(HierarchyEvent e) {
Window w;
if ((w = SwingUtilities.getWindowAncestor(toolBar)) != null) {
w.validate();
}
if (toolBar.getSize().width > 0) {
toolBar.removeHierarchyListener(this);
}
}
});
GameModule.getGameModule().addSideChangeListenerToPlayerRoster(this);
g.getPrefs().addOption(
Resources.getString("Prefs.general_tab"), //$NON-NLS-1$
new IntConfigurer(
PREFERRED_EDGE_DELAY,
Resources.getString("Map.scroll_delay_preference"), //$NON-NLS-1$
PREFERRED_EDGE_SCROLL_DELAY
)
);
g.getPrefs().addOption(
Resources.getString("Prefs.general_tab"), //$NON-NLS-1$
new BooleanConfigurer(
MOVING_STACKS_PICKUP_UNITS,
Resources.getString("Map.moving_stacks_preference"), //$NON-NLS-1$
Boolean.FALSE
)
);
}
public void setPieceMover(PieceMover mover) {
pieceMover = mover;
}
@Override
public void removeFrom(Buildable b) {
GameModule.getGameModule().getGameState().removeGameComponent(this);
Window w = SwingUtilities.getWindowAncestor(theMap);
if (w != null) {
w.dispose();
}
GameModule.getGameModule().getToolBar().remove(launchButton);
idMgr.remove(this);
if (picker != null) {
GameModule.getGameModule().removeCommandEncoder(picker);
GameModule.getGameModule().getGameState().addGameComponent(picker);
}
PlayerRoster.removeSideChangeListener(this);
}
@Override
public void sideChanged(String oldSide, String newSide) {
repaint();
}
/**
* Set the boards for this map. Each map may contain more than one
* {@link Board}.
*/
public synchronized void setBoards(Collection<Board> c) {
boards.clear();
for (Board b : c) {
b.setMap(this);
boards.add(b);
}
setBoardBoundaries();
}
/**
* Set the boards for this map. Each map may contain more than one
* {@link Board}.
*
* @deprecated Use {@link #setBoards(Collection)} instead.
*/
@Deprecated(since = "2020-08-05", forRemoval = true)
public synchronized void setBoards(Enumeration<Board> boardList) {
ProblemDialog.showDeprecated("2020-08-05");
setBoards(Collections.list(boardList));
}
@Override
public Command getRestoreCommand() {
return null;
}
/**
* @return the {@link Board} on this map containing the argument point
*/
public Board findBoard(Point p) {
for (Board b : boards) {
if (b.bounds().contains(p))
return b;
}
return null;
}
/**
* @return the {@link Zone} on this map containing the argument point
*/
public Zone findZone(Point p) {
Board b = findBoard(p);
if (b != null) {
MapGrid grid = b.getGrid();
if (grid instanceof ZonedGrid) {
Rectangle r = b.bounds();
p.translate(-r.x, -r.y); // Translate to Board co-ords
return ((ZonedGrid) grid).findZone(p);
}
}
return null;
}
/**
* Search on all boards for a Zone with the given name
*
* @param name Zone Name
* @return Located zone
*/
public Zone findZone(String name) {
for (Board b : boards) {
for (ZonedGrid zg : b.getAllDescendantComponentsOf(ZonedGrid.class)) {
Zone z = zg.findZone(name);
if (z != null) {
return z;
}
}
}
return null;
}
/**
* Search on all boards for a Region with the given name
*
* @param name Region name
* @return Located region
*/
public Region findRegion(String name) {
for (Board b : boards) {
for (RegionGrid rg : b.getAllDescendantComponentsOf(RegionGrid.class)) {
Region r = rg.findRegion(name);
if (r != null) {
return r;
}
}
}
return null;
}
/**
* Return the board with the given name
*
* @param name Board Name
* @return null if no such board found
*/
public Board getBoardByName(String name) {
if (name != null) {
for (Board b : boards) {
if (name.equals(b.getName())) {
return b;
}
}
}
return null;
}
public Dimension getPreferredSize() {
final Dimension size = mapSize();
size.width *= getZoom();
size.height *= getZoom();
return size;
}
/**
* @return the size of the map in pixels at 100% zoom,
* including the edge buffer
*/
// FIXME: why synchronized?
public synchronized Dimension mapSize() {
final Rectangle r = new Rectangle(0, 0);
for (Board b : boards) r.add(b.bounds());
r.width += edgeBuffer.width;
r.height += edgeBuffer.height;
return r.getSize();
}
public boolean isLocationRestricted(Point p) {
Board b = findBoard(p);
if (b != null) {
Rectangle r = b.bounds();
Point snap = new Point(p);
snap.translate(-r.x, -r.y);
return b.isLocationRestricted(snap);
} else {
return false;
}
}
/**
* @return the nearest allowable point according to the {@link VASSAL.build.module.map.boardPicker.board.MapGrid} on
* the {@link Board} at this point
* @see Board#snapTo
* @see VASSAL.build.module.map.boardPicker.board.MapGrid#snapTo
*/
public Point snapTo(Point p) {
Point snap = new Point(p);
final Board b = findBoard(p);
if (b == null) return snap;
final Rectangle r = b.bounds();
snap.translate(-r.x, -r.y);
snap = b.snapTo(snap);
snap.translate(r.x, r.y);
// RFE 882378
// If we have snapped to a point 1 pixel off the edge of the map, move
// back
// onto the map.
if (findBoard(snap) == null) {
snap.translate(-r.x, -r.y);
if (snap.x == r.width) {
snap.x = r.width - 1;
} else if (snap.x == -1) {
snap.x = 0;
}
if (snap.y == r.height) {
snap.y = r.height - 1;
} else if (snap.y == -1) {
snap.y = 0;
}
snap.translate(r.x, r.y);
}
return snap;
}
/**
* The buffer of empty space around the boards in the Map window,
* in component coordinates at 100% zoom
*/
public Dimension getEdgeBuffer() {
return new Dimension(edgeBuffer);
}
/**
* Translate a point from component coordinates (i.e., x,y position on
* the JPanel) to map coordinates (i.e., accounting for zoom factor).
*
* @see #componentCoordinates
* @deprecated Use {@link #componentToMap(Point)}
*/
@Deprecated(since = "2020-08-05", forRemoval = true)
public Point mapCoordinates(Point p) {
ProblemDialog.showDeprecated("2020-08-05");
return componentToMap(p);
}
/**
* @deprecated Use {@link #componentToMap(Rectangle)}
*/
@Deprecated(since = "2020-08-05", forRemoval = true)
public Rectangle mapRectangle(Rectangle r) {
ProblemDialog.showDeprecated("2020-08-05");
return componentToMap(r);
}
/**
* Translate a point from map coordinates to component coordinates
*
* @see #mapCoordinates
* @deprecated {@link #mapToComponent(Point)}
*/
@Deprecated(since = "2020-08-05", forRemoval = true)
public Point componentCoordinates(Point p) {
ProblemDialog.showDeprecated("2020-08-05");
return mapToComponent(p);
}
/**
* @deprecated Use {@link #mapToComponent(Rectangle)}
*/
@Deprecated(since = "2020-08-05", forRemoval = true)
public Rectangle componentRectangle(Rectangle r) {
ProblemDialog.showDeprecated("2020-08-05");
return mapToComponent(r);
}
protected int scale(int c, double zoom) {
return (int) (c * zoom);
}
protected Point scale(Point p, double zoom) {
return new Point((int) (p.x * zoom), (int) (p.y * zoom));
}
protected Rectangle scale(Rectangle r, double zoom) {
return new Rectangle(
(int) (r.x * zoom),
(int) (r.y * zoom),
(int) (r.width * zoom),
(int) (r.height * zoom)
);
}
public int mapToDrawing(int c, double os_scale) {
return scale(c, getZoom() * os_scale);
}
public Point mapToDrawing(Point p, double os_scale) {
return scale(p, getZoom() * os_scale);
}
public Rectangle mapToDrawing(Rectangle r, double os_scale) {
return scale(r, getZoom() * os_scale);
}
public int mapToComponent(int c) {
return scale(c, getZoom());
}
public Point mapToComponent(Point p) {
return scale(p, getZoom());
}
public Rectangle mapToComponent(Rectangle r) {
return scale(r, getZoom());
}
public int componentToDrawing(int c, double os_scale) {
return scale(c, os_scale);
}
public Point componentToDrawing(Point p, double os_scale) {
return scale(p, os_scale);
}
public Rectangle componentToDrawing(Rectangle r, double os_scale) {
return scale(r, os_scale);
}
public int componentToMap(int c) {
return scale(c, 1.0 / getZoom());
}
public Point componentToMap(Point p) {
return scale(p, 1.0 / getZoom());
}
public Rectangle componentToMap(Rectangle r) {
return scale(r, 1.0 / getZoom());
}
@SuppressWarnings("unused")
public int drawingToMap(int c, double os_scale) {
return scale(c, 1.0 / (getZoom() * os_scale));
}
public Point drawingToMap(Point p, double os_scale) {
return scale(p, 1.0 / (getZoom() * os_scale));
}
public Rectangle drawingToMap(Rectangle r, double os_scale) {
return scale(r, 1.0 / (getZoom() * os_scale));
}
@SuppressWarnings("unused")
public int drawingToComponent(int c, double os_scale) {
return scale(c, 1.0 / os_scale);
}
@SuppressWarnings("unused")
public Point drawingToComponent(Point p, double os_scale) {
return scale(p, 1.0 / os_scale);
}
@SuppressWarnings("unused")
public Rectangle drawingToComponent(Rectangle r, double os_scale) {
return scale(r, 1.0 / os_scale);
}
/**
* @return a String name for the given location on the map
* @see Board#locationName
*/
public String locationName(Point p) {
String loc = getDeckNameAt(p);
if (loc == null) {
Board b = findBoard(p);
if (b != null) {
loc = b.locationName(new Point(p.x - b.bounds().x, p.y - b.bounds().y));
}
}
if (loc == null) {
loc = Resources.getString("Map.offboard"); //$NON-NLS-1$
}
return loc;
}
public String localizedLocationName(Point p) {
String loc = getLocalizedDeckNameAt(p);
if (loc == null) {
Board b = findBoard(p);
if (b != null) {
loc = b.localizedLocationName(new Point(p.x - b.bounds().x, p.y - b.bounds().y));
}
}
if (loc == null) {
loc = Resources.getString("Map.offboard"); //$NON-NLS-1$
}
return loc;
}
/**
* Is this map visible to all players
*/
@SuppressWarnings("unused")
public boolean isVisibleToAll() {
if (this instanceof PrivateMap) {
if (!getAttributeValueString(PrivateMap.VISIBLE).equals("true")) { //$NON-NLS-1$
return false;
}
}
return true;
}
/**
* Return the name of the deck whose bounding box contains p
*/
@SuppressWarnings("unused")
public String getDeckNameContaining(Point p) {
String deck = null;
if (p != null) {
for (DrawPile d : getComponentsOf(DrawPile.class)) {
Rectangle box = d.boundingBox();
if (box != null && box.contains(p)) {
deck = d.getConfigureName();
break;
}
}
}
return deck;
}
/**
* Return the name of the deck whose position is p
*
* @param p Point to look for Deck
* @return Name of Deck
*/
public String getDeckNameAt(Point p) {
String deck = null;
if (p != null) {
for (DrawPile d : getComponentsOf(DrawPile.class)) {
if (d.getPosition().equals(p)) {
deck = d.getConfigureName();
break;
}
}
}
return deck;
}
public String getLocalizedDeckNameAt(Point p) {
String deck = null;
if (p != null) {
for (DrawPile d : getComponentsOf(DrawPile.class)) {
if (d.getPosition().equals(p)) {
deck = d.getLocalizedConfigureName();
break;
}
}
}
return deck;
}
/**
* Because MouseEvents are received in component coordinates, it is
* inconvenient for MouseListeners on the map to have to translate to map
* coordinates. MouseListeners added with this method will receive mouse
* events with points already translated into map coordinates.
* addLocalMouseListenerFirst inserts the new listener at the start of the
* chain.
*/
public void addLocalMouseListener(MouseListener l) {
multicaster = AWTEventMulticaster.add(multicaster, l);
}
public void addLocalMouseListenerFirst(MouseListener l) {
multicaster = AWTEventMulticaster.add(l, multicaster);
}
public void removeLocalMouseListener(MouseListener l) {
multicaster = AWTEventMulticaster.remove(multicaster, l);
}
/**
* MouseListeners on a map may be pushed and popped onto a stack.
* Only the top listener on the stack receives mouse events.
*/
public void pushMouseListener(MouseListener l) {
mouseListenerStack.add(l);
}
/**
* MouseListeners on a map may be pushed and popped onto a stack. Only the top listener on the stack receives mouse
* events
*/
public void popMouseListener() {
mouseListenerStack.remove(mouseListenerStack.size() - 1);
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
public MouseEvent translateEvent(MouseEvent e) {
// don't write over Java's mouse event
final MouseEvent mapEvent = new MouseEvent(
e.getComponent(), e.getID(), e.getWhen(), e.getModifiersEx(),
e.getX(), e.getY(), e.getXOnScreen(), e.getYOnScreen(),
e.getClickCount(), e.isPopupTrigger(), e.getButton()
);
final Point p = componentToMap(mapEvent.getPoint());
mapEvent.translatePoint(p.x - mapEvent.getX(), p.y - mapEvent.getY());
return mapEvent;
}
/**
* Mouse events are first translated into map coordinates. Then the event is forwarded to the top MouseListener in the
* stack, if any, otherwise forwarded to all LocalMouseListeners
*
* @see #pushMouseListener
* @see #popMouseListener
* @see #addLocalMouseListener
*/
@Override
public void mouseClicked(MouseEvent e) {
if (!mouseListenerStack.isEmpty()) {
mouseListenerStack.get(mouseListenerStack.size() - 1).mouseClicked(translateEvent(e));
} else if (multicaster != null) {
multicaster.mouseClicked(translateEvent(e));
}
}
/**
* Mouse events are first translated into map coordinates. Then the event is forwarded to the top MouseListener in the
* stack, if any, otherwise forwarded to all LocalMouseListeners
*
* @see #pushMouseListener
* @see #popMouseListener
* @see #addLocalMouseListener
*/
public static Map activeMap = null;
public static void setActiveMap(Map m) {
activeMap = m;
}
public static void clearActiveMap() {
if (activeMap != null) {
activeMap.repaint();
setActiveMap(null);
}
}
@Override
public void mousePressed(MouseEvent e) {
// Deselect any counters on the last Map with focus
if (!this.equals(activeMap)) {
boolean dirty = false;
final KeyBuffer kbuf = KeyBuffer.getBuffer();
final ArrayList<GamePiece> l = new ArrayList<>(kbuf.asList());
for (GamePiece p : l) {
if (p.getMap() == activeMap) {
kbuf.remove(p);
dirty = true;
}
}
if (dirty && activeMap != null) {
activeMap.repaint();
}
}
setActiveMap(this);
if (!mouseListenerStack.isEmpty()) {
mouseListenerStack.get(mouseListenerStack.size() - 1).mousePressed(translateEvent(e));
} else if (multicaster != null) {
multicaster.mousePressed(translateEvent(e));
}
}
/**
* Mouse events are first translated into map coordinates.
* Then the event is forwarded to the top MouseListener in the
* stack, if any, otherwise forwarded to all LocalMouseListeners.
*
* @see #pushMouseListener
* @see #popMouseListener
* @see #addLocalMouseListener
*/
@Override
public void mouseReleased(MouseEvent e) {
// don't write over Java's mouse event
Point p = e.getPoint();
p.translate(theMap.getX(), theMap.getY());
if (theMap.getBounds().contains(p)) {
if (!mouseListenerStack.isEmpty()) {
mouseListenerStack.get(mouseListenerStack.size() - 1).mouseReleased(translateEvent(e));
} else if (multicaster != null) {
multicaster.mouseReleased(translateEvent(e));
}
// Request Focus so that keyboard input will be recognized
theMap.requestFocus();
}
// Clicking with mouse always repaints the map
clearFirst = true;
theMap.repaint();
activeMap = this;
}
/**
* Save all current Key Listeners and remove them from the
* map. Used by Traits that need to prevent Key Commands
* at certain times.
*/
public void enableKeyListeners() {
if (saveKeyListeners == null) return;
for (KeyListener kl : saveKeyListeners) {
theMap.addKeyListener(kl);
}
saveKeyListeners = null;
}
/**
* Restore the previously disabled KeyListeners
*/
public void disableKeyListeners() {
if (saveKeyListeners != null) return;
saveKeyListeners = theMap.getKeyListeners();
for (KeyListener kl : saveKeyListeners) {
theMap.removeKeyListener(kl);
}
}
/**
* This listener will be notified when a drag event is initiated, assuming
* that no MouseListeners are on the stack.
*
* @param dragGestureListener Listener
* @see #pushMouseListener
*/
public void setDragGestureListener(DragGestureListener dragGestureListener) {
this.dragGestureListener = dragGestureListener;
}
public DragGestureListener getDragGestureListener() {
return dragGestureListener;
}
@Override
public void dragEnter(DropTargetDragEvent dtde) {
}
@Override
public void dragOver(DropTargetDragEvent dtde) {
scrollAtEdge(dtde.getLocation(), SCROLL_ZONE);
}
@Override
public void dropActionChanged(DropTargetDragEvent dtde) {
}
/*
* Cancel final scroll and repaint map
*/
@Override
public void dragExit(DropTargetEvent dte) {
if (scroller.isRunning()) scroller.stop();
repaint();
}
@Override
public void drop(DropTargetDropEvent dtde) {
if (dtde.getDropTargetContext().getComponent() == theMap) {
final MouseEvent evt = new MouseEvent(
theMap,
MouseEvent.MOUSE_RELEASED,
System.currentTimeMillis(),
0,
dtde.getLocation().x,
dtde.getLocation().y,
1,
false,
MouseEvent.NOBUTTON
);
theMap.dispatchEvent(evt);
dtde.dropComplete(true);
}
if (scroller.isRunning()) scroller.stop();
}
/**
* Mouse motion events are not forwarded to LocalMouseListeners or to listeners on the stack
*/
@Override
public void mouseMoved(MouseEvent e) {
}
/**
* Mouse motion events are not forwarded to LocalMouseListeners or to
* listeners on the stack.
* <p>
* The map scrolls when dragging the mouse near the edge.
*/
@Override
public void mouseDragged(MouseEvent e) {
if (!SwingUtils.isContextMouseButtonDown(e)) {
scrollAtEdge(e.getPoint(), SCROLL_ZONE);
} else {
if (scroller.isRunning()) scroller.stop();
}
}
/*
* Delay before starting scroll at edge
*/
public static final int PREFERRED_EDGE_SCROLL_DELAY = 200;
public static final String PREFERRED_EDGE_DELAY = "PreferredEdgeDelay"; //$NON-NLS-1$
/**
* The width of the hot zone for triggering autoscrolling.
*/
public static final int SCROLL_ZONE = 30;
/**
* The horizontal component of the autoscrolling vector, -1, 0, or 1.
*/
protected int sx;
/**
* The vertical component of the autoscrolling vector, -1, 0, or 1.
*/
protected int sy;
protected int dx, dy;
/**
* Begin autoscrolling the map if the given point is within the given
* distance from a viewport edge.
*
* @param evtPt Point to check
* @param dist Distance to check
*/
public void scrollAtEdge(Point evtPt, int dist) {
final Rectangle vrect = scroll.getViewport().getViewRect();
final int px = evtPt.x - vrect.x;
final int py = evtPt.y - vrect.y;
// determine scroll vector
sx = 0;
if (px < dist && px >= 0) {
sx = -1;
dx = dist - px;
} else if (px < vrect.width && px >= vrect.width - dist) {
sx = 1;
dx = dist - (vrect.width - px);
}
sy = 0;
if (py < dist && py >= 0) {
sy = -1;
dy = dist - py;
} else if (py < vrect.height && py >= vrect.height - dist) {
sy = 1;
dy = dist - (vrect.height - py);
}
dx /= 2;
dy /= 2;
// start autoscrolling if we have a nonzero scroll vector
if (sx != 0 || sy != 0) {
if (!scroller.isRunning()) {
scroller.setStartDelay((Integer)
GameModule.getGameModule().getPrefs().getValue(PREFERRED_EDGE_DELAY));
scroller.start();
}
} else {
if (scroller.isRunning()) scroller.stop();
}
}
/**
* The animator which controls autoscrolling.
*/
protected Animator scroller = new Animator(Animator.INFINITE,
new TimingTargetAdapter() {
private long t0;
@Override
public void timingEvent(float fraction) {
// Constant velocity along each axis, 0.5px/ms
final long t1 = System.currentTimeMillis();
final int dt = (int) ((t1 - t0) / 2);
t0 = t1;
scroll(sx * dt, sy * dt);
// Check whether we have hit an edge
final Rectangle vrect = scroll.getViewport().getViewRect();
if ((sx == -1 && vrect.x == 0) ||
(sx == 1 && vrect.x + vrect.width >= theMap.getWidth())) sx = 0;
if ((sy == -1 && vrect.y == 0) ||
(sy == 1 && vrect.y + vrect.height >= theMap.getHeight())) sy = 0;
// Stop if the scroll vector is zero
if (sx == 0 && sy == 0) scroller.stop();
}
@Override
public void begin() {
t0 = System.currentTimeMillis();
}
}
);
public void repaint(boolean cf) {
clearFirst = cf;
theMap.repaint();
}
public void paintRegion(Graphics g, Rectangle visibleRect) {
paintRegion(g, visibleRect, theMap);
}
public void paintRegion(Graphics g, Rectangle visibleRect, Component c) {
clearMapBorder(g); // To avoid ghost pieces around the edge
drawBoardsInRegion(g, visibleRect, c);
drawDrawable(g, false);
drawPiecesInRegion(g, visibleRect, c);
drawDrawable(g, true);
}
public void drawBoardsInRegion(Graphics g,
Rectangle visibleRect,
Component c) {
final Graphics2D g2d = (Graphics2D) g;
final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
final double dzoom = getZoom() * os_scale;
for (Board b : boards) {
b.drawRegion(g, getLocation(b, dzoom), visibleRect, dzoom, c);
}
}
public void drawBoardsInRegion(Graphics g, Rectangle visibleRect) {
drawBoardsInRegion(g, visibleRect, theMap);
}
public void repaint() {
theMap.repaint();
}
public void drawPiecesInRegion(Graphics g,
Rectangle visibleRect,
Component c) {
if (hideCounters) {
return;
}
final Graphics2D g2d = (Graphics2D) g;
final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
final double dzoom = getZoom() * os_scale;
Composite oldComposite = g2d.getComposite();
g2d.setComposite(
AlphaComposite.getInstance(AlphaComposite.SRC_OVER, pieceOpacity));
final GamePiece[] stack = pieces.getPieces();
for (GamePiece gamePiece : stack) {
final Point pt = mapToDrawing(gamePiece.getPosition(), os_scale);
if (gamePiece.getClass() == Stack.class) {
getStackMetrics().draw(
(Stack) gamePiece, pt, g, this, dzoom, visibleRect
);
} else {
gamePiece.draw(g, pt.x, pt.y, c, dzoom);
if (Boolean.TRUE.equals(gamePiece.getProperty(Properties.SELECTED))) {
highlighter.draw(gamePiece, g, pt.x, pt.y, c, dzoom);
}
}
/*
// draw bounding box for debugging
final Rectangle bb = stack[i].boundingBox();
g.drawRect(pt.x + bb.x, pt.y + bb.y, bb.width, bb.height);
*/
}
g2d.setComposite(oldComposite);
}
public void drawPiecesInRegion(Graphics g, Rectangle visibleRect) {
drawPiecesInRegion(g, visibleRect, theMap);
}
public void drawPieces(Graphics g, int xOffset, int yOffset) {
if (hideCounters) {
return;
}
Graphics2D g2d = (Graphics2D) g;
final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
Composite oldComposite = g2d.getComposite();
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, pieceOpacity));
GamePiece[] stack = pieces.getPieces();
for (GamePiece gamePiece : stack) {
Point pt = mapToDrawing(gamePiece.getPosition(), os_scale);
gamePiece.draw(g, pt.x + xOffset, pt.y + yOffset, theMap, getZoom());
if (Boolean.TRUE.equals(gamePiece.getProperty(Properties.SELECTED))) {
highlighter.draw(gamePiece, g, pt.x - xOffset, pt.y - yOffset, theMap, getZoom());
}
}
g2d.setComposite(oldComposite);
}
public void drawDrawable(Graphics g, boolean aboveCounters) {
for (Drawable drawable : drawComponents) {
if (!(aboveCounters ^ drawable.drawAboveCounters())) {
drawable.draw(g, this);
}
}
}
public Highlighter getHighlighter() {
return highlighter;
}
public void setHighlighter(Highlighter h) {
highlighter = h;
}
public void addHighlighter(Highlighter h) {
highlighters.add(h);
}
public void removeHighlighter(Highlighter h) {
highlighters.remove(h);
}
public Iterator<Highlighter> getHighlighters() {
return highlighters.iterator();
}
/**
* @return a Collection of all {@link Board}s on the Map
*/
public Collection<Board> getBoards() {
return Collections.unmodifiableCollection(boards);
}
/**
* @return an Enumeration of all {@link Board}s on the map
* @deprecated Use {@link #getBoards()} instead.
*/
@Deprecated(since = "2020-08-05", forRemoval = true)
public Enumeration<Board> getAllBoards() {
ProblemDialog.showDeprecated("2020-08-05");
return Collections.enumeration(boards);
}
public int getBoardCount() {
return boards.size();
}
/**
* Returns the boundingBox of a GamePiece accounting for the offset of a piece within its parent stack. Return null if
* this piece is not on the map
*
* @see GamePiece#boundingBox
*/
public Rectangle boundingBoxOf(GamePiece p) {
Rectangle r = null;
if (p.getMap() == this) {
r = p.boundingBox();
final Point pos = p.getPosition();
r.translate(pos.x, pos.y);
if (Boolean.TRUE.equals(p.getProperty(Properties.SELECTED))) {
r.add(highlighter.boundingBox(p));
for (Iterator<Highlighter> i = getHighlighters(); i.hasNext(); ) {
r.add(i.next().boundingBox(p));
}
}
if (p.getParent() != null) {
final Point pt = getStackMetrics().relativePosition(p.getParent(), p);
r.translate(pt.x, pt.y);
}
}
return r;
}
/**
* Returns the selection bounding box of a GamePiece accounting for the offset of a piece within a stack
*
* @see GamePiece#getShape
*/
public Rectangle selectionBoundsOf(GamePiece p) {
if (p.getMap() != this) {
throw new IllegalArgumentException(
Resources.getString("Map.piece_not_on_map")); //$NON-NLS-1$
}
final Rectangle r = p.getShape().getBounds();
r.translate(p.getPosition().x, p.getPosition().y);
if (p.getParent() != null) {
Point pt = getStackMetrics().relativePosition(p.getParent(), p);
r.translate(pt.x, pt.y);
}
return r;
}
/**
* Returns the position of a GamePiece accounting for the offset within a parent stack, if any
*/
public Point positionOf(GamePiece p) {
if (p.getMap() != this) {
throw new IllegalArgumentException(
Resources.getString("Map.piece_not_on_map")); //$NON-NLS-1$
}
final Point point = p.getPosition();
if (p.getParent() != null) {
final Point pt = getStackMetrics().relativePosition(p.getParent(), p);
point.translate(pt.x, pt.y);
}
return point;
}
/**
* @return an array of all GamePieces on the map. This is a read-only copy.
* Altering the array does not alter the pieces on the map.
*/
public GamePiece[] getPieces() {
return pieces.getPieces();
}
public GamePiece[] getAllPieces() {
return pieces.getAllPieces();
}
public void setPieceCollection(PieceCollection pieces) {
this.pieces = pieces;
}
public PieceCollection getPieceCollection() {
return pieces;
}
protected void clearMapBorder(Graphics g) {
final Graphics2D g2d = (Graphics2D) g.create();
final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
if (clearFirst || boards.isEmpty()) {
g.setColor(bgColor);
g.fillRect(
0,
0,
componentToDrawing(theMap.getWidth(), os_scale),
componentToDrawing(theMap.getHeight(), os_scale)
);
clearFirst = false;
} else {
final int mw = componentToDrawing(theMap.getWidth(), os_scale);
final int mh = componentToDrawing(theMap.getHeight(), os_scale);
final int ew = mapToDrawing(edgeBuffer.width, os_scale);
final int eh = mapToDrawing(edgeBuffer.height, os_scale);
g.setColor(bgColor);
g.fillRect(0, 0, ew, mh);
g.fillRect(0, 0, mw, eh);
g.fillRect(mw - ew, 0, ew, mh);
g.fillRect(0, mh - eh, mw, eh);
}
}
/**
* Adjusts the bounds() rectangle to account for the Board's relative
* position to other boards. In other words, if Board A is N pixels wide
* and Board B is to the right of Board A, then the origin of Board B
* will be adjusted N pixels to the right.
*/
protected void setBoardBoundaries() {
int maxX = 0;
int maxY = 0;
for (Board b : boards) {
Point relPos = b.relativePosition();
maxX = Math.max(maxX, relPos.x);
maxY = Math.max(maxY, relPos.y);
}
boardWidths = new int[maxX + 1][maxY + 1];
boardHeights = new int[maxX + 1][maxY + 1];
for (Board b : boards) {
Point relPos = b.relativePosition();
boardWidths[relPos.x][relPos.y] = b.bounds().width;
boardHeights[relPos.x][relPos.y] = b.bounds().height;
}
Point offset = new Point(edgeBuffer.width, edgeBuffer.height);
for (Board b : boards) {
Point relPos = b.relativePosition();
Point location = getLocation(relPos.x, relPos.y, 1.0);
b.setLocation(location.x, location.y);
b.translate(offset.x, offset.y);
}
theMap.revalidate();
}
protected Point getLocation(Board b, double zoom) {
Point p;
if (zoom == 1.0) {
p = b.bounds().getLocation();
} else {
Point relPos = b.relativePosition();
p = getLocation(relPos.x, relPos.y, zoom);
p.translate((int) (zoom * edgeBuffer.width), (int) (zoom * edgeBuffer.height));
}
return p;
}
protected Point getLocation(int column, int row, double zoom) {
Point p = new Point();
for (int x = 0; x < column; ++x) {
p.translate((int) Math.floor(zoom * boardWidths[x][row]), 0);
}
for (int y = 0; y < row; ++y) {
p.translate(0, (int) Math.floor(zoom * boardHeights[column][y]));
}
return p;
}
/**
* Draw the boards of the map at the given point and zoom factor onto
* the given Graphics object
*/
public void drawBoards(Graphics g, int xoffset, int yoffset, double zoom, Component obs) {
for (Board b : boards) {
Point p = getLocation(b, zoom);
p.translate(xoffset, yoffset);
b.draw(g, p.x, p.y, zoom, obs);
}
}
/**
* Repaint the given area, specified in map coordinates
*/
public void repaint(Rectangle r) {
r.setLocation(mapToComponent(new Point(r.x, r.y)));
r.setSize((int) (r.width * getZoom()), (int) (r.height * getZoom()));
theMap.repaint(r.x, r.y, r.width, r.height);
}
/**
* @param show if true, enable drawing of GamePiece. If false, don't draw GamePiece when painting the map
*/
public void setPiecesVisible(boolean show) {
hideCounters = !show;
}
public boolean isPiecesVisible() {
return !hideCounters && pieceOpacity != 0;
}
public float getPieceOpacity() {
return pieceOpacity;
}
public void setPieceOpacity(float pieceOpacity) {
this.pieceOpacity = pieceOpacity;
}
@Override
public Object getProperty(Object key) {
Object value;
MutableProperty p = propsContainer.getMutableProperty(String.valueOf(key));
if (p != null) {
value = p.getPropertyValue();
} else {
value = GameModule.getGameModule().getProperty(key);
}
return value;
}
@Override
public Object getLocalizedProperty(Object key) {
Object value = null;
MutableProperty p = propsContainer.getMutableProperty(String.valueOf(key));
if (p != null) {
value = p.getPropertyValue();
}
if (value == null) {
value = GameModule.getGameModule().getLocalizedProperty(key);
}
return value;
}
/**
* Return the auto-move key. It may be named, so just return
* the allocated KeyStroke.
*
* @return auto move keystroke
*/
public KeyStroke getMoveKey() {
return moveKey == null ? null : moveKey.getKeyStroke();
}
/**
* @return the top-level window containing this map
*/
protected Window createParentFrame() {
if (GlobalOptions.getInstance().isUseSingleWindow()) {
JDialog d = new JDialog(GameModule.getGameModule().getPlayerWindow());
d.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
d.setTitle(getDefaultWindowTitle());
return d;
} else {
JFrame d = new JFrame();
d.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
d.setTitle(getDefaultWindowTitle());
d.setJMenuBar(MenuManager.getInstance().getMenuBarFor(d));
return d;
}
}
public boolean shouldDockIntoMainWindow() {
// set to show via a button, or no combined window at all, don't dock
if (useLaunchButton || !GlobalOptions.getInstance().isUseSingleWindow()) {
return false;
}
// otherwise dock if this map is the first not to show via a button
for (Map m : GameModule.getGameModule().getComponentsOf(Map.class)) {
if (m == this) {
return true;
} else if (m.shouldDockIntoMainWindow()) {
return false;
}
}
// Module isn't fully built yet, and/or no maps at all in module yet (perhaps THIS map will soon be the first one)
return true;
}
/**
* When a game is started, create a top-level window, if none exists.
* When a game is ended, remove all boards from the map.
*
* @see GameComponent
*/
@Override
public void setup(boolean show) {
if (show) {
final GameModule g = GameModule.getGameModule();
if (shouldDockIntoMainWindow()) {
if (mainWindowDock != null) { // This is protected from null elsewhere, and crashed null here, so I'm thinking protect here too.
mainWindowDock.showComponent();
final int height = (Integer)
Prefs.getGlobalPrefs().getValue(MAIN_WINDOW_HEIGHT);
if (height > 0) {
final Container top = mainWindowDock.getTopLevelAncestor();
top.setSize(top.getWidth(), height);
}
}
if (toolBar.getParent() == null) {
g.getToolBar().addSeparator();
g.getToolBar().add(toolBar);
}
toolBar.setVisible(true);
} else {
if (SwingUtilities.getWindowAncestor(theMap) == null) {
final Window topWindow = createParentFrame();
topWindow.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
if (useLaunchButton) {
topWindow.setVisible(false);
} else {
g.getGameState().setup(false);
}
}
});
((RootPaneContainer) topWindow).getContentPane().add("North", getToolBar()); //$NON-NLS-1$
((RootPaneContainer) topWindow).getContentPane().add("Center", layeredPane); //$NON-NLS-1$
topWindow.setSize(600, 400);
final PositionOption option =
new PositionOption(PositionOption.key + getIdentifier(), topWindow);
g.getPrefs().addOption(option);
}
theMap.getTopLevelAncestor().setVisible(!useLaunchButton);
theMap.revalidate();
}
} else {
pieces.clear();
boards.clear();
if (mainWindowDock != null) {
if (mainWindowDock.getHideableComponent().isShowing()) {
Prefs.getGlobalPrefs().getOption(MAIN_WINDOW_HEIGHT)
.setValue(mainWindowDock.getTopLevelAncestor().getHeight());
}
mainWindowDock.hideComponent();
toolBar.setVisible(false);
} else if (theMap.getTopLevelAncestor() != null) {
theMap.getTopLevelAncestor().setVisible(false);
}
}
launchButton.setEnabled(show);
launchButton.setVisible(useLaunchButton);
}
public void appendToTitle(String s) {
if (mainWindowDock == null) {
Component c = theMap.getTopLevelAncestor();
if (s == null) {
if (c instanceof JFrame) {
((JFrame) c).setTitle(getDefaultWindowTitle());
}
if (c instanceof JDialog) {
((JDialog) c).setTitle(getDefaultWindowTitle());
}
} else {
if (c instanceof JFrame) {
((JFrame) c).setTitle(((JFrame) c).getTitle() + s);
}
if (c instanceof JDialog) {
((JDialog) c).setTitle(((JDialog) c).getTitle() + s);
}
}
}
}
protected String getDefaultWindowTitle() {
return getLocalizedMapName().length() > 0 ? getLocalizedMapName() : Resources.getString("Map.window_title", GameModule.getGameModule().getLocalizedGameName()); //$NON-NLS-1$
}
/**
* Use the provided {@link PieceFinder} instance to locate a visible piece at the given location
*/
public GamePiece findPiece(Point pt, PieceFinder finder) {
GamePiece[] stack = pieces.getPieces();
for (int i = stack.length - 1; i >= 0; --i) {
GamePiece p = finder.select(this, stack[i], pt);
if (p != null) {
return p;
}
}
return null;
}
/**
* Use the provided {@link PieceFinder} instance to locate any piece at the given location, regardless of whether it
* is visible or not
*/
public GamePiece findAnyPiece(Point pt, PieceFinder finder) {
GamePiece[] stack = pieces.getAllPieces();
for (int i = stack.length - 1; i >= 0; --i) {
GamePiece p = finder.select(this, stack[i], pt);
if (p != null) {
return p;
}
}
return null;
}
/**
* Place a piece at the destination point. If necessary, remove the piece from its parent Stack or Map
*
* @return a {@link Command} that reproduces this action
*/
public Command placeAt(GamePiece piece, Point pt) {
Command c;
if (GameModule.getGameModule().getGameState().getPieceForId(piece.getId()) == null) {
piece.setPosition(pt);
addPiece(piece);
GameModule.getGameModule().getGameState().addPiece(piece);
c = new AddPiece(piece);
} else {
MoveTracker tracker = new MoveTracker(piece);
piece.setPosition(pt);
addPiece(piece);
c = tracker.getMoveCommand();
}
return c;
}
/**
* Apply the provided {@link PieceVisitorDispatcher} to all pieces on this map. Returns the first non-null
* {@link Command} returned by <code>commandFactory</code>
*
* @param commandFactory Command Factory
*/
public Command apply(PieceVisitorDispatcher commandFactory) {
GamePiece[] stack = pieces.getPieces();
Command c = null;
for (int i = 0; i < stack.length && c == null; ++i) {
c = (Command) commandFactory.accept(stack[i]);
}
return c;
}
/**
* Move a piece to the destination point. If a piece is at the point (i.e. has a location exactly equal to it), merge
* with the piece by forwarding to {@link StackMetrics#merge}. Otherwise, place by forwarding to placeAt()
*
* @see StackMetrics#merge
*/
public Command placeOrMerge(final GamePiece p, final Point pt) {
Command c = apply(new DeckVisitorDispatcher(new Merger(this, pt, p)));
if (c == null || c.isNull()) {
c = placeAt(p, pt);
// If no piece at destination and this is a stacking piece, create
// a new Stack containing the piece
if (!(p instanceof Stack) &&
!Boolean.TRUE.equals(p.getProperty(Properties.NO_STACK))) {
final Stack parent = getStackMetrics().createStack(p);
if (parent != null) {
c = c.append(placeAt(parent, pt));
}
}
}
return c;
}
/**
* Adds a GamePiece to this map. Removes the piece from its parent Stack and from its current map, if different from
* this map
*/
public void addPiece(GamePiece p) {
if (indexOf(p) < 0) {
if (p.getParent() != null) {
p.getParent().remove(p);
p.setParent(null);
}
if (p.getMap() != null && p.getMap() != this) {
p.getMap().removePiece(p);
}
pieces.add(p);
p.setMap(this);
theMap.repaint();
}
}
/**
* Reorder the argument GamePiece to the new index. When painting the map, pieces are drawn in order of index
*
* @deprecated use {@link PieceCollection#moveToFront}
*/
@SuppressWarnings("unused")
@Deprecated(since = "2020-08-05", forRemoval = true)
public void reposition(GamePiece s, int pos) {
ProblemDialog.showDeprecated("2020-08-05");
}
/**
* Returns the index of a piece. When painting the map, pieces are drawn in order of index Return -1 if the piece is
* not on this map
*/
public int indexOf(GamePiece s) {
return pieces.indexOf(s);
}
/**
* Removes a piece from the map
*/
public void removePiece(GamePiece p) {
pieces.remove(p);
theMap.repaint();
}
/**
* Center the map at given map coordinates within its JScrollPane container
*/
public void centerAt(Point p) {
centerAt(p, 0, 0);
}
/**
* Center the map at the given map coordinates, if the point is not
* already within (dx,dy) of the center.
*/
public void centerAt(Point p, int dx, int dy) {
if (scroll != null) {
p = mapToComponent(p);
final Rectangle r = theMap.getVisibleRect();
r.x = p.x - r.width / 2;
r.y = p.y - r.height / 2;
final Dimension d = getPreferredSize();
if (r.x + r.width > d.width) r.x = d.width - r.width;
if (r.y + r.height > d.height) r.y = d.height - r.height;
r.width = dx > r.width ? 0 : r.width - dx;
r.height = dy > r.height ? 0 : r.height - dy;
theMap.scrollRectToVisible(r);
}
}
/**
* Ensure that the given region (in map coordinates) is visible
*/
public void ensureVisible(Rectangle r) {
final double no_recenter_pct = 0.9;
if (scroll != null) {
final Point p = mapToComponent(r.getLocation());
final Rectangle r_current = theMap.getVisibleRect();
// If r is already visible decide if unit is close enough to
// border to justify a recenter
// if r is within a band of n%width/height of border, trigger recenter
Rectangle r_norecenter = new Rectangle(0, 0);
;
Double tmpDouble = r_current.width * no_recenter_pct;
r_norecenter.width = (int) round(tmpDouble);
r_norecenter.width = (int) round(r_current.width * no_recenter_pct);
r_norecenter.height = (int) round(r_current.height * no_recenter_pct);
r_norecenter.x = r_current.x + (int) round(r_current.width - r_norecenter.width) / 2;
r_norecenter.y = r_current.y + (int) round(r_current.height - r_norecenter.height) / 2;
boolean bTriggerRecenter = false;
if (p.x < r_norecenter.x) bTriggerRecenter = true;
if (p.x > (r_norecenter.x + r_norecenter.width)) bTriggerRecenter = true;
if (p.y < r_norecenter.y) bTriggerRecenter = true;
if (p.y > (r_norecenter.y + r_norecenter.height)) bTriggerRecenter = true;
if (bTriggerRecenter == true) {
r.x = p.x - r_current.width / 2;
r.y = p.y - r_current.height / 2;
r.width = r_current.width;
r.height = r_current.height;
final Dimension d = getPreferredSize();
if (r.x + r.width > d.width) r.x = d.width - r.width;
if (r.y + r.height > d.height) r.y = d.height - r.height;
theMap.scrollRectToVisible(r);
}
}
}
/**
* Scrolls the map in the containing JScrollPane.
*
* @param dx number of pixels to scroll horizontally
* @param dy number of pixels to scroll vertically
*/
public void scroll(int dx, int dy) {
Rectangle r = scroll.getViewport().getViewRect();
r.translate(dx, dy);
r = r.intersection(new Rectangle(getPreferredSize()));
theMap.scrollRectToVisible(r);
}
public static String getConfigureTypeName() {
return Resources.getString("Editor.Map.component_type"); //$NON-NLS-1$
}
public String getMapName() {
return getConfigureName();
}
public String getLocalizedMapName() {
return getLocalizedConfigureName();
}
public void setMapName(String s) {
mapName = s;
setConfigureName(mapName);
if (tooltip == null || tooltip.length() == 0) {
launchButton.setToolTipText(s != null ? Resources.getString("Map.show_hide", s) : Resources.getString("Map.show_hide", Resources.getString("Map.map"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
@Override
public HelpFile getHelpFile() {
return HelpFile.getReferenceManualPage("Map.htm"); //$NON-NLS-1$
}
@Override
public String[] getAttributeDescriptions() {
return new String[]{
Resources.getString("Editor.Map.map_name"), //$NON-NLS-1$
Resources.getString("Editor.Map.mark_pieces_moved"), //$NON-NLS-1$
Resources.getString("Editor.Map.mark_unmoved_button_text"), //$NON-NLS-1$
Resources.getString("Editor.Map.mark_unmoved_tooltip_text"), //$NON-NLS-1$
Resources.getString("Editor.Map.mark_unmoved_button_icon"), //$NON-NLS-1$
Resources.getString("Editor.Map.horizontal"), //$NON-NLS-1$
Resources.getString("Editor.Map.vertical"), //$NON-NLS-1$
Resources.getString("Editor.Map.bkgdcolor"), //$NON-NLS-1$
Resources.getString("Editor.Map.multiboard"), //$NON-NLS-1$
Resources.getString("Editor.Map.bc_selected_counter"), //$NON-NLS-1$
Resources.getString("Editor.Map.bt_selected_counter"), //$NON-NLS-1$
Resources.getString("Editor.Map.show_hide"), //$NON-NLS-1$
Resources.getString(Resources.BUTTON_TEXT),
Resources.getString(Resources.TOOLTIP_TEXT),
Resources.getString(Resources.BUTTON_ICON),
Resources.getString(Resources.HOTKEY_LABEL),
Resources.getString("Editor.Map.report_move_within"), //$NON-NLS-1$
Resources.getString("Editor.Map.report_move_to"), //$NON-NLS-1$
Resources.getString("Editor.Map.report_created"), //$NON-NLS-1$
Resources.getString("Editor.Map.report_modified"), //$NON-NLS-1$
Resources.getString("Editor.Map.key_applied_all") //$NON-NLS-1$
};
}
@Override
public String[] getAttributeNames() {
return new String[]{
NAME,
MARK_MOVED,
MARK_UNMOVED_TEXT,
MARK_UNMOVED_TOOLTIP,
MARK_UNMOVED_ICON,
EDGE_WIDTH,
EDGE_HEIGHT,
BACKGROUND_COLOR,
ALLOW_MULTIPLE,
HIGHLIGHT_COLOR,
HIGHLIGHT_THICKNESS,
USE_LAUNCH_BUTTON,
BUTTON_NAME,
TOOLTIP,
ICON,
HOTKEY,
MOVE_WITHIN_FORMAT,
MOVE_TO_FORMAT,
CREATE_FORMAT,
CHANGE_FORMAT,
MOVE_KEY
};
}
@Override
public Class<?>[] getAttributeTypes() {
return new Class<?>[]{
String.class,
GlobalOptions.Prompt.class,
String.class,
String.class,
UnmovedIconConfig.class,
Integer.class,
Integer.class,
Color.class,
Boolean.class,
Color.class,
Integer.class,
Boolean.class,
String.class,
String.class,
IconConfig.class,
NamedKeyStroke.class,
MoveWithinFormatConfig.class,
MoveToFormatConfig.class,
CreateFormatConfig.class,
ChangeFormatConfig.class,
NamedKeyStroke.class
};
}
public static final String LOCATION = "location"; //$NON-NLS-1$
public static final String OLD_LOCATION = "previousLocation"; //$NON-NLS-1$
public static final String OLD_MAP = "previousMap"; //$NON-NLS-1$
public static final String MAP_NAME = "mapName"; //$NON-NLS-1$
public static final String PIECE_NAME = "pieceName"; //$NON-NLS-1$
public static final String MESSAGE = "message"; //$NON-NLS-1$
public static class IconConfig implements ConfigurerFactory {
@Override
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new IconConfigurer(key, name, "/images/map.gif"); //$NON-NLS-1$
}
}
public static class UnmovedIconConfig implements ConfigurerFactory {
@Override
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new IconConfigurer(key, name, "/images/unmoved.gif"); //$NON-NLS-1$
}
}
public static class MoveWithinFormatConfig implements TranslatableConfigurerFactory {
@Override
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new PlayerIdFormattedStringConfigurer(key, name, new String[]{PIECE_NAME, LOCATION, MAP_NAME, OLD_LOCATION});
}
}
public static class MoveToFormatConfig implements TranslatableConfigurerFactory {
@Override
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new PlayerIdFormattedStringConfigurer(key, name, new String[]{PIECE_NAME, LOCATION, OLD_MAP, MAP_NAME, OLD_LOCATION});
}
}
public static class CreateFormatConfig implements TranslatableConfigurerFactory {
@Override
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new PlayerIdFormattedStringConfigurer(key, name, new String[]{PIECE_NAME, MAP_NAME, LOCATION});
}
}
public static class ChangeFormatConfig implements TranslatableConfigurerFactory {
@Override
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new PlayerIdFormattedStringConfigurer(key, name, new String[]{
MESSAGE,
ReportState.COMMAND_NAME,
ReportState.OLD_UNIT_NAME,
ReportState.NEW_UNIT_NAME,
ReportState.MAP_NAME,
ReportState.LOCATION_NAME});
}
}
public String getCreateFormat() {
if (createFormat != null) {
return createFormat;
} else {
String val = "$" + PIECE_NAME + "$ created in $" + LOCATION + "$"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
if (!boards.isEmpty()) {
Board b = boards.get(0);
if (b.getGrid() == null || b.getGrid().getGridNumbering() == null) {
val = ""; //$NON-NLS-1$
}
}
return val;
}
}
public String getChangeFormat() {
return isChangeReportingEnabled() ? changeFormat : "";
}
public String getMoveToFormat() {
if (moveToFormat != null) {
return moveToFormat;
} else {
String val = "$" + PIECE_NAME + "$" + " moves $" + OLD_LOCATION + "$ -> $" + LOCATION + "$ *"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
if (!boards.isEmpty()) {
Board b = boards.get(0);
if (b.getGrid() == null || b.getGrid().getGridNumbering() != null) {
val = ""; //$NON-NLS-1$
}
}
return val;
}
}
public String getMoveWithinFormat() {
if (moveWithinFormat != null) {
return moveWithinFormat;
} else {
String val = "$" + PIECE_NAME + "$" + " moves $" + OLD_LOCATION + "$ -> $" + LOCATION + "$ *"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
if (!boards.isEmpty()) {
Board b = boards.get(0);
if (b.getGrid() == null) {
val = ""; //$NON-NLS-1$
}
}
return val;
}
}
@Override
public Class<?>[] getAllowableConfigureComponents() {
return new Class<?>[]{GlobalMap.class, LOS_Thread.class, ToolbarMenu.class, MultiActionButton.class, HidePiecesButton.class, Zoomer.class,
CounterDetailViewer.class, HighlightLastMoved.class, LayeredPieceCollection.class, ImageSaver.class, TextSaver.class, DrawPile.class, SetupStack.class,
MassKeyCommand.class, MapShader.class, PieceRecenterer.class};
}
@Override
public VisibilityCondition getAttributeVisibility(String name) {
if (visibilityCondition == null) {
visibilityCondition = () -> useLaunchButton;
}
if (List.of(HOTKEY, BUTTON_NAME, TOOLTIP, ICON).contains(name)) {
return visibilityCondition;
} else if (List.of(MARK_UNMOVED_TEXT, MARK_UNMOVED_ICON, MARK_UNMOVED_TOOLTIP).contains(name)) {
return () -> !GlobalOptions.NEVER.equals(markMovedOption);
} else {
return super.getAttributeVisibility(name);
}
}
/**
* Each Map must have a unique String id
*/
@Override
public void setId(String id) {
mapID = id;
}
public static Map getMapById(String id) {
return (Map) idMgr.findInstance(id);
}
/**
* Utility method to return a {@link List} of all map components in the
* module.
*
* @return the list of <code>Map</code>s
*/
public static List<Map> getMapList() {
final GameModule g = GameModule.getGameModule();
final List<Map> l = g.getComponentsOf(Map.class);
for (ChartWindow cw : g.getComponentsOf(ChartWindow.class)) {
for (MapWidget mw : cw.getAllDescendantComponentsOf(MapWidget.class)) {
l.add(mw.getMap());
}
}
return l;
}
/**
* Utility method to return a list of all map components in the module
*
* @return Iterator over all maps
* @deprecated Use {@link #getMapList()} instead.
*/
@Deprecated(since = "2020-08-05", forRemoval = true)
public static Iterator<Map> getAllMaps() {
ProblemDialog.showDeprecated("2020-08-05");
return getMapList().iterator();
}
/**
* Find a contained Global Variable by name
*/
@Override
public MutableProperty getMutableProperty(String name) {
return propsContainer.getMutableProperty(name);
}
@Override
public void addMutableProperty(String key, MutableProperty p) {
propsContainer.addMutableProperty(key, p);
p.addMutablePropertyChangeListener(repaintOnPropertyChange);
}
@Override
public MutableProperty removeMutableProperty(String key) {
MutableProperty p = propsContainer.removeMutableProperty(key);
if (p != null) {
p.removeMutablePropertyChangeListener(repaintOnPropertyChange);
}
return p;
}
@Override
public String getMutablePropertiesContainerId() {
return getMapName();
}
/**
* Each Map must have a unique String id
*
* @return the id for this map
*/
@Override
public String getId() {
return mapID;
}
/**
* Make a best gues for a unique identifier for the target. Use
* {@link VASSAL.tools.UniqueIdManager.Identifyable#getConfigureName} if non-null, otherwise use
* {@link VASSAL.tools.UniqueIdManager.Identifyable#getId}
*
* @return Unique Identifier
*/
public String getIdentifier() {
return UniqueIdManager.getIdentifier(this);
}
/**
* @return the Swing component representing the map
*/
public JComponent getView() {
if (theMap == null) {
theMap = new View(this);
scroll = new AdjustableSpeedScrollPane(
theMap,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.unregisterKeyboardAction(
KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0));
scroll.unregisterKeyboardAction(
KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0));
scroll.setAlignmentX(0.0f);
scroll.setAlignmentY(0.0f);
layeredPane.setLayout(new InsetLayout(layeredPane, scroll));
layeredPane.add(scroll, JLayeredPane.DEFAULT_LAYER);
}
return theMap;
}
/**
* @return the JLayeredPane holding map insets
*/
public JLayeredPane getLayeredPane() {
return layeredPane;
}
/**
* The Layout responsible for arranging insets which overlay the Map
* InsetLayout currently is responsible for keeping the {@link GlobalMap}
* in the upper-left corner of the {@link Map.View}.
*/
public static class InsetLayout extends OverlayLayout {
private static final long serialVersionUID = 1L;
private final JScrollPane base;
public InsetLayout(Container target, JScrollPane base) {
super(target);
this.base = base;
}
@Override
public void layoutContainer(Container target) {
super.layoutContainer(target);
base.getLayout().layoutContainer(base);
final Dimension viewSize = base.getViewport().getSize();
final Insets insets = base.getInsets();
viewSize.width += insets.left;
viewSize.height += insets.top;
// prevent non-base components from overlapping the base's scrollbars
final int n = target.getComponentCount();
for (int i = 0; i < n; ++i) {
Component c = target.getComponent(i);
if (c != base && c.isVisible()) {
final Rectangle b = c.getBounds();
b.width = Math.min(b.width, viewSize.width);
b.height = Math.min(b.height, viewSize.height);
c.setBounds(b);
}
}
}
}
/**
* Implements default logic for merging pieces at a given location within
* a map Returns a {@link Command} that merges the input {@link GamePiece}
* with an existing piece at the input position, provided the pieces are
* stackable, visible, in the same layer, etc.
*/
public static class Merger implements DeckVisitor {
private final Point pt;
private final Map map;
private final GamePiece p;
public Merger(Map map, Point pt, GamePiece p) {
this.map = map;
this.pt = pt;
this.p = p;
}
@Override
public Object visitDeck(Deck d) {
if (d.getPosition().equals(pt)) {
return map.getStackMetrics().merge(d, p);
} else {
return null;
}
}
@Override
public Object visitStack(Stack s) {
if (s.getPosition().equals(pt) && map.getStackMetrics().isStackingEnabled() && !Boolean.TRUE.equals(p.getProperty(Properties.NO_STACK))
&& s.topPiece() != null && map.getPieceCollection().canMerge(s, p)) {
return map.getStackMetrics().merge(s, p);
} else {
return null;
}
}
@Override
public Object visitDefault(GamePiece piece) {
if (piece.getPosition().equals(pt) && map.getStackMetrics().isStackingEnabled() && !Boolean.TRUE.equals(p.getProperty(Properties.NO_STACK))
&& !Boolean.TRUE.equals(piece.getProperty(Properties.INVISIBLE_TO_ME)) && !Boolean.TRUE.equals(piece.getProperty(Properties.NO_STACK))
&& map.getPieceCollection().canMerge(piece, p)) {
return map.getStackMetrics().merge(piece, p);
} else {
return null;
}
}
}
/**
* The component that represents the map itself
*/
public static class View extends JPanel {
private static final long serialVersionUID = 1L;
protected Map map;
public View(Map m) {
setFocusTraversalKeysEnabled(false);
map = m;
}
@Override
public void paint(Graphics g) {
// Don't draw the map until the game is updated.
if (GameModule.getGameModule().getGameState().isUpdating()) {
return;
}
final Graphics2D g2d = (Graphics2D) g;
g2d.addRenderingHints(SwingUtils.FONT_HINTS);
final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
// HDPI: We may get a transform where scale != 1. This means we
// are running on an HDPI system. We want to draw at the effective
// scale factor to prevent poor quality upscaling, so reset the
// transform to scale of 1 and multiply the map zoom by the OS scaling.
final AffineTransform orig_t = g2d.getTransform();
g2d.setTransform(SwingUtils.descaleTransform(orig_t));
final Rectangle r = map.componentToDrawing(getVisibleRect(), os_scale);
g2d.setColor(map.bgColor);
g2d.fillRect(r.x, r.y, r.width, r.height);
map.paintRegion(g2d, r);
g2d.setTransform(orig_t);
}
@Override
public void update(Graphics g) {
// To avoid flicker, don't clear the display first
paint(g);
}
@Override
public Dimension getPreferredSize() {
return map.getPreferredSize();
}
public Map getMap() {
return map;
}
}
}
|
package polyglot.frontend;
import polyglot.ast.*;
import polyglot.types.*;
import polyglot.util.*;
import polyglot.visit.*;
import polyglot.main.Options;
import polyglot.main.Report;
import java.io.*;
import java.util.*;
/**
* This is an abstract <code>ExtensionInfo</code>.
*/
public abstract class AbstractExtensionInfo implements ExtensionInfo {
protected Compiler compiler;
private Options options;
protected TypeSystem ts = null;
protected NodeFactory nf = null;
protected SourceLoader source_loader = null;
protected TargetFactory target_factory = null;
protected Stats stats;
/**
* A list of all active (that is, uncompleted) <code>SourceJob</code>s.
*/
protected LinkedList worklist;
/**
* A map from <code>Source</code>s to <code>SourceJob</code>s or to
* the <code>COMPLETED_JOB</code> object if the SourceJob previously existed
* but has now finished. The map contains entries for all
* <code>Source</code>s that have had <code>Job</code>s added for them.
*/
protected Map jobs;
protected static final Object COMPLETED_JOB = "COMPLETED JOB";
/** The currently running job, or null if no job is running. */
protected Job currentJob;
public Options getOptions() {
if (this.options == null) {
this.options = createOptions();
}
return options;
}
protected Options createOptions() {
return new Options(this);
}
/** Return a Stats object to accumulate and report statistics. */
public Stats getStats() {
if (this.stats == null) {
this.stats = new Stats(this);
}
return stats;
}
public Compiler compiler() {
return compiler;
}
public void initCompiler(Compiler compiler) {
this.compiler = compiler;
jobs = new HashMap();
worklist = new LinkedList();
// Register the extension with the compiler.
compiler.addExtension(this);
currentJob = null;
// Create the type system and node factory.
typeSystem();
nodeFactory();
initTypeSystem();
}
protected abstract void initTypeSystem();
/**
* Run all jobs in the work list (and any children they have) to
* completion. This method returns <code>true</code> if all jobs were
* successfully completed. If all jobs were successfully completed, then
* the worklist will be empty.
*
* The scheduling of <code>Job</code>s uses two methods to maintain
* scheduling invariants: <code>selectJobFromWorklist</code> selects
* a <code>SourceJob</code> from <code>worklist</code> (a list of
* jobs that still need to be processed); <code>enforceInvariants</code> is
* called before a pass is performed on a <code>SourceJob</code> and is
* responsible for ensuring all dependencies are satisfied before the
* pass proceeds, i.e. enforcing any scheduling invariants.
*/
public boolean runToCompletion() {
boolean okay = true;
while (okay && ! worklist.isEmpty()) {
SourceJob job = selectJobFromWorklist();
if (Report.should_report(Report.frontend, 1)) {
Report.report(1, "Running job " + job);
}
okay &= runAllPasses(job);
if (job.completed()) {
// the job has finished. Let's remove it from the map so it
// can be garbage collected, and free up the AST.
jobs.put(job.source(), COMPLETED_JOB);
if (Report.should_report(Report.frontend, 1)) {
Report.report(1, "Completed job " + job);
}
}
else {
// the job is not yet completed (although, it really
// should be...)
if (Report.should_report(Report.frontend, 1)) {
Report.report(1, "Failed to complete job " + job);
}
worklist.add(job);
}
}
if (Report.should_report(Report.frontend, 1))
Report.report(1, "Finished all passes
(okay ? "okay" : "failed"));
return okay;
}
/**
* Select and remove a <code>SourceJob</code> from the non-empty
* <code>worklist</code>. Return the selected <code>SourceJob</code>
* which will be scheduled to run all of its remaining passes.
*/
protected SourceJob selectJobFromWorklist() {
return (SourceJob)worklist.remove(0);
}
/**
* Read a source file and compile it up to the the current job's last
* barrier.
*/
public boolean readSource(FileSource source) {
// Add a new SourceJob for the given source. If a Job for the source
// already exists, then we will be given the existing job.
SourceJob job = addJob(source);
if (job == null) {
// addJob returns null if the job has already been completed, in
// which case we can just ignore the request to read in the source.
return true;
}
// Run the new job up to the currentJob's SourceJob's last barrier, to
// make sure that dependencies are satisfied.
Pass.ID barrier;
if (currentJob != null) {
if (currentJob.sourceJob().lastBarrier() == null) {
throw new InternalCompilerError("A Source Job which has " +
"not reached a barrier cannot read another " +
"source file.");
}
barrier = currentJob.sourceJob().lastBarrier().id();
}
else {
barrier = Pass.FIRST_BARRIER;
}
return runToPass(job, barrier);
}
/**
* Run all pending passes on <code>job</code>.
*/
public boolean runAllPasses(Job job) {
List pending = job.pendingPasses();
// Run until there are no more passes.
if (!pending.isEmpty()) {
Pass lastPass = (Pass)pending.get(pending.size() - 1);
return runToPass(job, lastPass);
}
return true;
}
/**
* Run a job until the <code>goal</code> pass completes.
*/
public boolean runToPass(Job job, Pass.ID goal) {
if (Report.should_report(Report.frontend, 1))
Report.report(1, "Running " + job + " to pass named " + goal);
if (job.completed(goal)) {
return true;
}
Pass pass = job.passByID(goal);
return runToPass(job, pass);
}
/**
* Run a job up to the <code>goal</code> pass.
*/
public boolean runToPass(Job job, Pass goal) {
if (Report.should_report(Report.frontend, 1))
Report.report(1, "Running " + job + " to pass " + goal);
while (! job.pendingPasses().isEmpty()) {
Pass pass = (Pass) job.pendingPasses().get(0);
runPass(job, pass);
if (pass == goal) {
break;
}
}
if (job.completed()) {
if (Report.should_report(Report.frontend, 1))
Report.report(1, "Job " + job + " completed");
}
return job.status();
}
/**
* Run the pass <code>pass</code> on the job. Before running the pass on
* the job, if the job is a <code>SourceJob</code>, then this method will
* ensure that the scheduling invariants are enforced by calling
* <code>enforceInvariants</code>.
*/
protected void runPass(Job job, Pass pass) {
// make sure that all scheduling invariants are satisfied before running
// the next pass. We may thus execute some other passes on other
// jobs running the given pass.
enforceInvariants(job, pass);
if (getOptions().disable_passes.contains(pass.name())) {
if (Report.should_report(Report.frontend, 1))
Report.report(1, "Skipping pass " + pass);
job.finishPass(pass, true);
return;
}
if (Report.should_report(Report.frontend, 1))
Report.report(1, "Trying to run pass " + pass + " on " + job.source());
if (job.isRunning()) {
// We're currently running. We can't reach the goal.
throw new InternalCompilerError(job +
" cannot reach pass " +
pass);
}
pass.resetTimers();
boolean result = false;
if (job.status()) {
Job oldCurrentJob = this.currentJob;
this.currentJob = job;
Report.should_report.push(pass.name());
// Stop the timer on the old pass. */
Pass oldPass = oldCurrentJob != null
? oldCurrentJob.runningPass()
: null;
if (oldPass != null) {
oldPass.toggleTimers(true);
}
job.setRunningPass(pass);
pass.toggleTimers(false);
result = pass.run();
pass.toggleTimers(false);
job.setRunningPass(null);
Report.should_report.pop();
this.currentJob = oldCurrentJob;
// Restart the timer on the old pass. */
if (oldPass != null) {
oldPass.toggleTimers(true);
}
// pretty-print this pass if we need to.
if (getOptions().print_ast.contains(pass.name())) {
System.err.println("
"
System.err.println("Pretty-printing AST for " + job +
" after " + pass.name());
PrettyPrinter pp = new PrettyPrinter();
pp.printAst(job.ast(), new CodeWriter(System.err, 78));
}
// dump this pass if we need to.
if (getOptions().dump_ast.contains(pass.name())) {
System.err.println("
"
System.err.println("Dumping AST for " + job +
" after " + pass.name());
NodeVisitor dumper =
new DumpAst(new CodeWriter(System.err, 78));
dumper = dumper.begin();
job.ast().visit(dumper);
dumper.finish();
}
// This seems to work around a VM bug on linux with JDK
// 1.4.0. The mark-sweep collector will sometimes crash.
// Running the GC explicitly here makes the bug go away.
// If this fails, maybe run with bigger heap.
// System.gc();
}
Stats stats = getStats();
stats.accumPassTimes(pass.id(), pass.inclusiveTime(),
pass.exclusiveTime());
if (Report.should_report(Report.time, 2)) {
Report.report(2, "Finished " + pass +
" status=" + str(result) + " inclusive_time=" +
pass.inclusiveTime() + " exclusive_time=" +
pass.exclusiveTime());
}
else if (Report.should_report(Report.frontend, 1)) {
Report.report(1, "Finished " + pass +
" status=" + str(result));
}
job.finishPass(pass, result);
}
/**
* Before running <code>Pass pass</code> on <code>SourceJob job</code>
* make sure that all appropriate scheduling invariants are satisfied,
* to ensure that all passes of other jobs that <code>job</code> depends
* on will have already been done.
*
*/
protected void enforceInvariants(Job job, Pass pass) {
SourceJob srcJob = job.sourceJob();
if (srcJob == null) {
return;
}
BarrierPass lastBarrier = srcJob.lastBarrier();
if (lastBarrier != null) {
// make sure that _all_ dependent jobs have completed at least up to
// the last barrier (not just children).
// Ideally the invariant should be that only the source jobs that
// job _depends on_ should be brought up to the last barrier.
// This is work to be done in the future...
List allDependentSrcs = new ArrayList(srcJob.dependencies());
Iterator i = allDependentSrcs.iterator();
while (i.hasNext()) {
Source s = (Source)i.next();
Object o = jobs.get(s);
if (o == COMPLETED_JOB) continue;
if (o == null) {
throw new InternalCompilerError("Unknown source " + s);
}
SourceJob sj = (SourceJob)o;
if (sj.pending(lastBarrier.id())) {
// Make the job run up to the last barrier.
// We ignore the return result, since even if the job
// fails, we will keep on going and see
// how far we get...
if (Report.should_report(Report.frontend, 3)) {
Report.report(3, "Running " + sj +
" to " + lastBarrier.id() + " for " + srcJob);
}
runToPass(sj, lastBarrier.id());
}
}
}
if (pass instanceof GlobalBarrierPass) {
// need to make sure that _all_ jobs have completed just up to
// this global barrier.
List allSrcJobs = new ArrayList(jobs.values());
Iterator i = allSrcJobs.iterator();
while (i.hasNext()) {
Object o = i.next();
if (o == COMPLETED_JOB) continue;
SourceJob sj = (SourceJob)o;
if (sj.completed(pass.id()) ||
sj.nextPass() == sj.passByID(pass.id())) {
// the source job has either done this global pass
// (which is possible if the job was loaded late in the
// game), or is right up to the global barrier.
continue;
}
// Make the job run up to just before the global barrier.
// We ignore the return result, since even if the job
// fails, we will keep on going and see
// how far we get...
Pass beforeGlobal = sj.getPreviousTo(pass.id());
if (Report.should_report(Report.frontend, 3)) {
Report.report(3, "Running " + sj +
" to " + beforeGlobal.id() + " for " + srcJob);
}
runToPass(sj, beforeGlobal);
}
}
}
private static String str(boolean okay) {
if (okay) {
return "done";
}
else {
return "failed";
}
}
/**
* Get the file name extension of source files. This is
* either the language extension's default file name extension
* or the string passed in with the "-sx" command-line option.
*/
public String[] fileExtensions() {
String[] sx = getOptions() == null ? null : getOptions().source_ext;
if (sx == null) {
sx = defaultFileExtensions();
}
if (sx.length == 0) {
return defaultFileExtensions();
}
return sx;
}
/** Get the default list of file extensions. */
public String[] defaultFileExtensions() {
String ext = defaultFileExtension();
return new String[] { ext };
}
/** Get the source file loader object for this extension. */
public SourceLoader sourceLoader() {
if (source_loader == null) {
source_loader = new SourceLoader(this, getOptions().source_path);
}
return source_loader;
}
/** Get the target factory object for this extension. */
public TargetFactory targetFactory() {
if (target_factory == null) {
target_factory = new TargetFactory(getOptions().output_directory,
getOptions().output_ext,
getOptions().output_stdout);
}
return target_factory;
}
/** Create the type system for this extension. */
protected abstract TypeSystem createTypeSystem();
/** Get the type system for this extension. */
public TypeSystem typeSystem() {
if (ts == null) {
ts = createTypeSystem();
}
return ts;
}
/** Create the node factory for this extension. */
protected abstract NodeFactory createNodeFactory();
/** Get the AST node factory for this extension. */
public NodeFactory nodeFactory() {
if (nf == null) {
nf = createNodeFactory();
}
return nf;
}
/**
* Get the job extension for this language extension. The job
* extension is used to extend the <code>Job</code> class
* without subtyping.
*/
public JobExt jobExt() {
return null;
}
/**
* Adds a dependency from the current job to the given Source.
*/
public void addDependencyToCurrentJob(Source s) {
if (s == null)
return;
if (currentJob != null) {
Object o = jobs.get(s);
if (o != COMPLETED_JOB) {
if (Report.should_report(Report.frontend, 2)) {
Report.report(2, "Adding dependency from " +
currentJob.source() + " to " +
s);
}
currentJob.sourceJob().addDependency(s);
}
}
else {
throw new InternalCompilerError("No current job!");
}
}
/**
* Add a new <code>SourceJob</code> for the <code>Source source</code>.
* A new job will be created if
* needed. If the <code>Source source</code> has already been processed,
* and its job discarded to release resources, then <code>null</code>
* will be returned.
*/
public SourceJob addJob(Source source) {
return addJob(source, null);
}
/**
* Add a new <code>SourceJob</code> for the <code>Source source</code>,
* with AST <code>ast</code>.
* A new job will be created if
* needed. If the <code>Source source</code> has already been processed,
* and its job discarded to release resources, then <code>null</code>
* will be returned.
*/
public SourceJob addJob(Source source, Node ast) {
Object o = jobs.get(source);
SourceJob job = null;
if (o == COMPLETED_JOB) {
// the job has already been completed.
// We don't need to add a job
return null;
}
else if (o == null) {
// No appropriate job yet exists, we will create one.
job = this.createSourceJob(source, ast);
// record the job in the map and the worklist.
jobs.put(source, job);
worklist.addLast(job);
if (Report.should_report(Report.frontend, 3)) {
Report.report(3, "Adding job for " + source + " at the " +
"request of job " + currentJob);
}
}
else {
job = (SourceJob)o;
}
// if the current source job caused this job to load, record the
// dependency.
if (currentJob instanceof SourceJob) {
((SourceJob)currentJob).addDependency(source);
}
return job;
}
/**
* Create a new <code>SourceJob</code> for the given source and AST.
* In general, this method should only be called by <code>addJob</code>.
*/
protected SourceJob createSourceJob(Source source, Node ast) {
return new SourceJob(this, jobExt(), source, ast);
}
/**
* Create a new non-<code>SourceJob</code> <code>Job</code>, for the
* given AST. In general this method should only be called by
* <code>spawnJob</code>.
*
* @param ast the AST the new Job is for.
* @param context the context that the AST occurs in
* @param outer the <code>Job</code> that spawned this job.
* @param begin the first pass to perform for this job.
* @param end the last pass to perform for this job.
*/
protected Job createJob(Node ast, Context context, Job outer, Pass.ID begin, Pass.ID end) {
return new InnerJob(this, jobExt(), ast, context, outer, begin, end);
}
/**
* Spawn a new job. All passes between the pass <code>begin</code>
* and <code>end</code> inclusive will be performed immediately on
* the AST <code>ast</code>.
*
* @param c the context that the AST occurs in
* @param ast the AST the new Job is for.
* @param outerJob the <code>Job</code> that spawned this job.
* @param begin the first pass to perform for this job.
* @param end the last pass to perform for this job.
* @return the new job. The caller can check the result with
* <code>j.status()</code> and get the ast with <code>j.ast()</code>.
*/
public Job spawnJob(Context c, Node ast, Job outerJob,
Pass.ID begin, Pass.ID end) {
Job j = createJob(ast, c, outerJob, begin, end);
if (Report.should_report(Report.frontend, 1))
Report.report(1, this +" spawning " + j);
// Run all the passes
runAllPasses(j);
// Return the job. The caller can check the result with j.status().
return j;
}
/** Get the parser for this language extension. */
public abstract Parser parser(Reader reader, FileSource source,
ErrorQueue eq);
/**
* Replace the pass named <code>id</code> in <code>passes</code> with
* the list of <code>newPasses</code>.
*/
public void replacePass(List passes, Pass.ID id, List newPasses) {
for (ListIterator i = passes.listIterator(); i.hasNext(); ) {
Pass p = (Pass) i.next();
if (p.id() == id) {
if (p instanceof BarrierPass) {
throw new InternalCompilerError("Cannot replace a barrier pass.");
}
i.remove();
for (Iterator j = newPasses.iterator(); j.hasNext(); ) {
i.add(j.next());
}
return;
}
}
throw new InternalCompilerError("Pass " + id + " not found.");
}
/**
* Remove the pass named <code>id</code> from <code>passes</code>.
*/
public void removePass(List passes, Pass.ID id) {
for (ListIterator i = passes.listIterator(); i.hasNext(); ) {
Pass p = (Pass) i.next();
if (p.id() == id) {
if (p instanceof BarrierPass) {
throw new InternalCompilerError("Cannot remove a barrier pass.");
}
i.remove();
return;
}
}
throw new InternalCompilerError("Pass " + id + " not found.");
}
/**
* Insert the list of <code>newPasses</code> into <code>passes</code>
* immediately before the pass named <code>id</code>.
*/
public void beforePass(List passes, Pass.ID id, List newPasses) {
for (ListIterator i = passes.listIterator(); i.hasNext(); ) {
Pass p = (Pass) i.next();
if (p.id() == id) {
// Backup one position.
i.previous();
for (Iterator j = newPasses.iterator(); j.hasNext(); ) {
i.add(j.next());
}
return;
}
}
throw new InternalCompilerError("Pass " + id + " not found.");
}
/**
* Insert the list of <code>newPasses</code> into <code>passes</code>
* immediately after the pass named <code>id</code>.
*/
public void afterPass(List passes, Pass.ID id, List newPasses) {
for (ListIterator i = passes.listIterator(); i.hasNext(); ) {
Pass p = (Pass) i.next();
if (p.id() == id) {
for (Iterator j = newPasses.iterator(); j.hasNext(); ) {
i.add(j.next());
}
return;
}
}
throw new InternalCompilerError("Pass " + id + " not found.");
}
/**
* Replace the pass named <code>id</code> in <code>passes</code> with
* the pass <code>pass</code>.
*/
public void replacePass(List passes, Pass.ID id, Pass pass) {
replacePass(passes, id, Collections.singletonList(pass));
}
/**
* Insert the pass <code>pass</code> into <code>passes</code>
* immediately before the pass named <code>id</code>.
*/
public void beforePass(List passes, Pass.ID id, Pass pass) {
beforePass(passes, id, Collections.singletonList(pass));
}
/**
* Insert the pass <code>pass</code> into <code>passes</code>
* immediately after the pass named <code>id</code>.
*/
public void afterPass(List passes, Pass.ID id, Pass pass) {
afterPass(passes, id, Collections.singletonList(pass));
}
/**
* Get the complete list of passes for the job.
*/
public abstract List passes(Job job);
/**
* Get the sub-list of passes for the job between passes
* <code>begin</code> and <code>end</code>, inclusive.
*/
public List passes(Job job, Pass.ID begin, Pass.ID end) {
List l = passes(job);
Pass p = null;
Iterator i = l.iterator();
while (i.hasNext()) {
p = (Pass) i.next();
if (begin == p.id()) break;
if (! (p instanceof BarrierPass)) i.remove();
}
while (p.id() != end && i.hasNext()) {
p = (Pass) i.next();
}
while (i.hasNext()) {
p = (Pass) i.next();
i.remove();
}
return l;
}
public String toString() {
return getClass().getName() + " worklist=" + worklist;
}
}
|
package gamepack;
import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.geom.Rectangle;
public class Tile implements DrawableObject
{
private int value;
private Rectangle rectangle;
private Direction tileDirection; //Give in which direction the tile goes
private Tile arrivedTile; //If the tile has an arrived Tile
private Point arrivedPoint; //If the tile has an arrived Point
public Point getArrivedPoint() {
return arrivedPoint;
}
public Tile(int x, int y, int size)
{
this(x, y, 2,size); //changer le 2 en random value entre 2 ou 4 ou bombe
}
public Tile(int x, int y, int value, int size)
{
this.rectangle = new Rectangle(x, y, size, size);
this.value = value;
tileDirection = Direction.None;
}
public int getValue()
{
return this.value;
}
public float getX()
{
return this.rectangle.getX();
}
public float getY()
{
return this.rectangle.getY();
}
public void setX(int x)
{
this.rectangle.setX(x);
}
public void setY(int y)
{
this.rectangle.setY(y);
}
public void doubleValue()
{
value = 2*value;
}
private float getCenterX()
{
return this.rectangle.getCenterX();
}
private float getCenterY()
{
return this.rectangle.getCenterY();
}
public Tile getArrivedTile()
{
return this.arrivedTile;
}
public void setArrivedTile(Tile t)
{
this.arrivedTile = t;
}
public int getArrivedPointX()
{
return arrivedPoint.getX();
}
public int getArrivedPointY()
{
return arrivedPoint.getY();
}
public void setArrivedPoint(Point arrivedPoint)
{
this.arrivedPoint = arrivedPoint;
}
public Direction getDirection()
{
return this.tileDirection;
}
public void setDirection(Direction tileDirection)
{
this.tileDirection = tileDirection;
}
public void move(float x, float y)
{
this.rectangle.setX(this.rectangle.getX() + x);
this.rectangle.setY(this.rectangle.getY() + y);
}
//Test if two tiles have the same
public boolean equals(Tile secondTile)
{
if (getX() == secondTile.getX() && getY() == secondTile.getY() && value == secondTile.getValue())
return true;
return false;
}
//If the tile and his arrivedTile has the same coordinates, return true
//then, double the value of the arrivedTile (use a method doubleValue())
public Boolean refreshFusion()
{
if (this.equals(this.arrivedTile)) {
this.arrivedTile.doubleValue();
return true;
}else{
return false;
}
}
//return true if the tile has arrived to his arrivedPoint
public boolean isArrived()
{
if(arrivedPoint != null)
return getX() == arrivedPoint.getX() && getY() == arrivedPoint.getY();
return true;
}
//avoid a bad positionning of the tile (it could be positionning after the arrived point due to
//bad framerate)
public void improvePosition()
{
if(tileDirection == Direction.Left)
{
if(getX() < getArrivedPointX())
setX(getArrivedPointX());
}
else if(tileDirection == Direction.Right)
{
if(getX() > getArrivedPointX())
setX(getArrivedPointX());
}
else if(tileDirection == Direction.Up)
{
if(getY() < getArrivedPointY())
setY(getArrivedPointY());
}
else if(tileDirection == Direction.Down)
{
if(getY() > getArrivedPointY())
setY(getArrivedPointY());
}
}
public void beDrawn(Graphics g)
{
//Couleurs de tests, changer
g.setColor(Color.red);
g.fill(rectangle);
g.draw(rectangle);
g.setColor(Color.white);
g.drawString("" + value, getCenterX(), getCenterY());
}
}
|
package game;
import graphic.Balloon;
import graphic.Fuel;
import graphic.Leaf;
import handlers.SceneHandler;
import handlers.ScrollingHandler;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
import scrollables.BackHills;
import scrollables.GreenHills;
import scrollables.SecondHills;
import util.ParticleManager;
public class MainState extends BasicGameState {
private Image skyimage;
/*the scrollable foreground and backgrounds*/
private ScrollingHandler frontground, background, backlayer;
private SceneHandler sceneHandler = SceneHandler.getInstance();
private Balloon balloon;
private ParticleManager particleManager = new ParticleManager();
private Fuel fuelIndicator;
@Override
public int getID() {
return Game.STATE.MAIN;
}
@Override
public void init(GameContainer gameContainer, StateBasedGame stateBasedGame) throws SlickException {
frontground = new ScrollingHandler("frontground", new GreenHills(0.0f,0,true,1)); //create front collidable scrollable
frontground.add(new GreenHills(0.0f, 0, true, 2)); //add more map to the front scrollable
frontground.add(new GreenHills(0.0f, 0, true, 3)); //add more map to the front scrollable
frontground.add(new GreenHills(0.0f, 0, true, 4)); //add more map to the front scrollable
background = new ScrollingHandler("background", new BackHills(0.0f,0,false,1)); //create front collidable scrollable
background.add(new BackHills(0.0f, 0, false, 2)); //add more map to the front scrollable
background.add(new BackHills(0.0f,0,false,3)); //add more map to the front scrollable
background.add(new BackHills(0.0f,0,false,4)); //add more map to the front scrollable
balloon = (Balloon) sceneHandler.spawn(280, 200, Balloon.class, "balloon");
fuelIndicator = (Fuel) sceneHandler.spawn(280, 200, Fuel.class);
sceneHandler.spawn(280, 200, Leaf.class, "leaf");
backlayer = new ScrollingHandler("background", new SecondHills(0.0f,0,false,1)); //create back non collidable scrollable
backlayer.add(new SecondHills(0.0f, 0, false, 2)); //add more map to the back scrollable
backlayer.add(new SecondHills(0.0f, 0, false, 3)); //add more map to the back scrollable
backlayer.add(new SecondHills(0.0f, 0, false, 4)); //add more map to the back scrollable
skyimage = new Image("data/image/sky.png");
particleManager.addParticle("data/particles/emitter.xml", "data/particles/particle.png");
particleManager.addParticle("data/particles/emitter_fast.xml", "data/particles/particle.png");
}
@Override
public void render(GameContainer gameContainer, StateBasedGame stateBasedGame, Graphics graphics) throws SlickException {
skyimage.draw(0, 0, MainGame.SCREEN_WIDTH, MainGame.SCREEN_HEIGHT);
background.render(gameContainer, graphics);
backlayer.render(gameContainer, graphics);
particleManager.render(graphics);
frontground.render(gameContainer, graphics); //render the frontground scrollables
sceneHandler.render(gameContainer, graphics); //render the balloon balloon.printStats(graphics, 400, 0); //error checking, print stats of ballon
frontground.printStats(graphics, 200, 0, balloon); //error checking of frontground scrollable
if(balloon.isCollided(sceneHandler.getSceneObjectById("leaf"))){
graphics.drawString("Collided", 500, 300);
}
//render fuel
graphics.drawString("Fuel: "+balloon.getFuel(), 700, 0);
graphics.drawString("Lives: "+balloon.getLives(), 850, 0);
//render score
graphics.drawString("Distance: "+(int)frontground.getDistance()+"m",1000,0); }
@Override
public void update(GameContainer gameContainer, StateBasedGame stateBasedGame, int delta) throws SlickException {
float deltaTime = delta /1000;
backgroundMove(background, deltaTime-1, 0, stateBasedGame);
backgroundMove(backlayer, deltaTime-2, 0, stateBasedGame);
backgroundMove(frontground, deltaTime-4, 0, stateBasedGame); //update the front scrollable
sceneHandler.update(gameContainer, delta);
particleManager.upate(delta);
}
/*moves the background, separate method for clarity*/
public void backgroundMove(ScrollingHandler bg, float x, float y, StateBasedGame sbg) {
bg.update(x, y, balloon, sbg);
}
@Override
public void enter(GameContainer container, StateBasedGame game) throws SlickException {
init(container, game);
}
@Override
public void leave(GameContainer container, StateBasedGame game) throws SlickException {
super.leave(container, game); //To change body of overridden methods use File | Settings | File Templates.
}
}
|
package gameutils;
import java.applet.Applet;
import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
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.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferStrategy;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
/**
* Game is the main class that must be extended by the user. It handles the game loop and certain other functions.<br>
* Game extends Applet but also supports being a desktop app.<br>
* Remember: if this game will be used as an Applet, a default constructor <strong>MUST</strong> be present.<br>
* <br>
* It uses a Screen system where only 1 Screen is active at one time.<br>
* <br>
* A typical game looks like this: <br>
* <br>
* <code>
* public class MyGame extends Game {<br>
* public static void main(String args[]) {<br>
* MyGame game = new MyGame();<br>
* game.setupFrame("My Game",800,600,true);<br>
* game.start();<br>
* }<br>
* <br>
* public void initGame() {<br>
* //Initialize the game<br>
* }<br>
* <br>
* public void update(long deltaTime) {<br>
* super.update(deltaTime);<br>
* //Optional: update the game<br>
* }<br>
* <br>
* public void paused() {<br>
* //Pause the game<br>
* }<br>
*<br>
* public void resumed() {<br>
* //Resume the game<br>
* }<br>
*<br>
* public void resized(int width, int height) {<br>
* //Resize the game<br>
* }<br>
*<br>
* public void stopGame() {<br>
* //Stop the game<br>
* }<br>
*<br>
* public void paint(Graphics2D g) {<br>
* super.paint(g);<br>
* //Optional: draw the game<br>
* }<br>
* }
* </code>
* @author Roi Atalla
*/
public abstract class Game extends Applet {
private static final long serialVersionUID = -1870725768768871166L;
static {
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch(Exception exc) {}
}
/**
* Initializes and displays the window.
* @param title The title of the window
* @param width The width of the window
* @param height The height of the window
* @param resizable If true, the window will be resizable, else it will not be resizable.
* @return The JFrame that was initialized by this method.
*/
protected final JFrame setupFrame(String title, boolean resizable) {
final JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setIgnoreRepaint(true);
frame.setResizable(resizable);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
stop();
}
});
frame.add(this);
frame.setVisible(true);
isApplet = false;
setSize(width,height);
init();
((JPanel)frame.getContentPane()).revalidate();
return frame;
}
/**
* Used to notify the game loop thread to update and render as fast as possible.
*/
public static final int MAX_FPS = 0;
/**
* Used to notify the game loop thread to update the maximum number of times before render.
*/
public static final int MAX_UPDATES = -1;
/**
* 1 second in nanoseconds, AKA 1,000,000 nanoseconds.
*/
public static final long ONE_SECOND = (long)1e9;
private final Art art;
private final Sound sound;
private final Map<String,ScreenInfo> screens;
private ScreenInfo currentScreen;
private final Canvas canvas;
private final Input input;
private ArrayList<Event> events;
private ArrayList<Event> tempEvents;
private boolean isApplet = true;
private int width, height;
private Object quality;
private int maxUpdates;
private int FPS;
private double version;
private boolean showFPS;
private boolean useYield;
private volatile boolean isProcessingEvents;
private volatile boolean isActive;
private volatile boolean isPaused;
/**
* Default constructor. The defaults are:<br>
* - MAX_UPDATES is set
* - 60FPS<br>
* - Version 1.0<br>
* - showFPS = true<br>
* - quality = high<br>
* - standardKeysEnabled = true
*/
public Game() {
this(0,0);
}
/**
* Sets defaults and the FPS and version.
* @param FPS The FPS to achieve.
* @param version The version of this game.
*/
public Game(int width, int height) {
art = new Art();
sound = new Sound();
screens = Collections.synchronizedMap(new HashMap<String,ScreenInfo>());
currentScreen = new ScreenInfo(new Screen() {
public void init(Game game) {}
public Game getGame() { return null; }
public void show() {}
public void hide() {}
public void paused() {}
public void resumed() {}
public void resized(int width, int height) {}
public void update(long deltaTime) {}
public void draw(Graphics2D g) {}
});
screens.put("Default", currentScreen);
canvas = new Canvas();
input = new Input();
events = new ArrayList<Event>();
tempEvents = new ArrayList<Event>();
this.width = width;
this.height = height;
FPS = 60;
version = 1.0;
showFPS = true;
quality = RenderingHints.VALUE_ANTIALIAS_ON;
maxUpdates = MAX_UPDATES;
}
/**
* Returns the current working directory of this game.
* @return The current working directory of this game.
*/
public URL getCodeBase() {
if(isApplet())
return super.getCodeBase();
try{
return getClass().getResource("/");
}
catch(Exception exc) {
exc.printStackTrace();
return null;
}
}
public Graphics getGraphics() {
return canvas.getGraphics();
}
/**
* Returns the appropriate container of this game: this instance if it is an Applet, the JFrame if it is a desktop application.
* @return If this game is an Applet, it returns this instance, else it returns the JFrame used to display this game.
*/
public Container getRootParent() {
if(isApplet())
return this;
return getParent().getParent().getParent().getParent();
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
/**
* @return Returns true if this game is an Applet, false otherwise.
*/
public boolean isApplet() {
return isApplet;
}
/**
* @return Returns true if this game is currently active.
*/
public boolean isActive() {
return isActive;
}
/**
* Manually pauses the game loop. paused() will be called
*/
public void pause() {
if(isActive()) {
isPaused = true;
paused();
}
}
/**
* Returns true if the game loop is paused.
* @return True if the game loop is paused, false otherwise.
*/
public boolean isPaused() {
return isPaused;
}
/**
* Manually resumes the game loop. resumed() will be called right before the game loop resumes.
*/
public void resume() {
if(isActive() && isPaused()) {
isPaused = false;
resumed();
}
}
/**
* If this game is an applet, it calls the superclass's resize method, else it calls setSize(int,int).
* @param width The new width of this game's canvas.
* @param height The new height of this game's canvas;
*/
public void resize(int width, int height) {
setSize(width,height);
}
/**
* If this game is an Applet, it calls the superclass's resize method, else it adjusts the JFrame according to the platform specific Insets.
* @param width The new width of this game's canvas
* @param height The new height of this game's canvas
*/
public void setSize(int width, int height) {
invalidate();
if(isApplet())
super.resize(width,height);
else {
Insets i = getRootParent().getInsets();
getRootParent().setSize(width+i.right+i.left,height+i.bottom+i.top);
((JFrame)getRootParent()).setLocationRelativeTo(null);
}
this.width = width;
this.height = height;
invalidate();
validate();
}
public void setFullScreen(boolean setFullScreen) {
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
if(setFullScreen) {
if(isFullScreen())
throw new IllegalStateException("A full screen window is already open.");
JFrame frame = new JFrame();
frame.setResizable(false);
frame.setUndecorated(true);
frame.setIgnoreRepaint(true);
remove(canvas);
invalidate();
validate();
frame.add(canvas);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
setFullScreen(false);
}
});
if(!isApplet())
getRootParent().setVisible(false);
gd.setFullScreenWindow(frame);
}
else {
if(!isFullScreen())
return;
gd.getFullScreenWindow().dispose();
gd.setFullScreenWindow(null);
add(canvas);
invalidate();
validate();
if(!isApplet())
getRootParent().setVisible(true);
}
canvas.requestFocus();
}
/**
* Returns true if this game is running full screen.
* @return True if this game is running full screen, false otherwise.
*/
public boolean isFullScreen() {
return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getFullScreenWindow() != null;
}
final void gameLoop() {
if(isActive())
return;
Thread.currentThread().setName("Game Loop Thread");
try {
resize(width,height);
synchronized(Game.this) {
initGame();
}
getScreen().show();
}
catch(Exception exc) {
exc.printStackTrace();
}
Listener listener = new Listener();
canvas.addKeyListener(listener);
canvas.addMouseListener(listener);
canvas.addMouseMotionListener(listener);
canvas.addMouseWheelListener(listener);
canvas.createBufferStrategy(2);
BufferStrategy strategy = canvas.getBufferStrategy();
Font fpsFont = new Font(Font.SANS_SERIF,Font.TRUETYPE_FONT,10);
int frames = 0;
int currentFPS = 0;
long time = System.nanoTime();
long lastTime = System.nanoTime();
isActive = true;
canvas.requestFocus();
while(isActive()) {
long diffTime = System.nanoTime()-lastTime;
lastTime += diffTime;
try{
processEvents();
}
catch(Exception exc) {
exc.printStackTrace();
}
int updateCount = 0;
while(diffTime > 0 && (maxUpdates <= 0 || updateCount < maxUpdates) && !isPaused()) {
long deltaTime = FPS > 0 ? deltaTime = Math.min(diffTime,ONE_SECOND/FPS) : diffTime;
try{
synchronized(Game.this) {
update(deltaTime);
}
}
catch(Exception exc) {
exc.printStackTrace();
}
diffTime -= deltaTime;
updateCount++;
}
try{
do{
do{
Graphics2D g = (Graphics2D)strategy.getDrawGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,quality);
try{
synchronized(Game.this) {
paint(g);
}
}
catch(Exception exc) {
exc.printStackTrace();
}
if(showFPS) {
g.setFont(fpsFont);
g.drawString("Version " + version + " " + currentFPS + " FPS",2,getHeight()-2);
}
g.dispose();
}while(strategy.contentsRestored());
strategy.show();
}while(strategy.contentsLost());
}
catch(Exception exc) {
exc.printStackTrace();
}
frames++;
if(System.nanoTime()-time >= ONE_SECOND) {
time = System.nanoTime();
currentFPS = frames;
frames = 0;
}
try{
if(FPS > 0) {
long sleepTime = Math.round((ONE_SECOND/FPS)-(System.nanoTime()-lastTime));
if(sleepTime <= 0)
continue;
long prevTime = System.nanoTime();
while(System.nanoTime()-prevTime <= sleepTime) {
if(useYield)
Thread.yield();
else
Thread.sleep(1);
}
}
}
catch(Exception exc) {
exc.printStackTrace();
}
}
if(stopGame() && !isApplet())
System.exit(0);
}
private void processEvents() {
isProcessingEvents = true;
synchronized(events) {
for(Event e : events) {
switch(e.id) {
case 0:
for(InputListener l : currentScreen.listeners) {
try {
l.keyTyped((KeyEvent)e.event,getScreen());
}
catch(Exception exc) {
exc.printStackTrace();
}
}
break;
case 1:
input.keyPressed((KeyEvent)e.event);
for(InputListener l : currentScreen.listeners) {
try {
l.keyPressed((KeyEvent)e.event,getScreen());
}
catch(Exception exc) {
exc.printStackTrace();
}
}
break;
case 2:
input.keyReleased((KeyEvent)e.event);
for(InputListener l : currentScreen.listeners) {
try {
l.keyReleased((KeyEvent)e.event,getScreen());
}
catch(Exception exc) {
exc.printStackTrace();
}
}
break;
case 3:
for(InputListener l : currentScreen.listeners) {
try {
l.mouseClicked((MouseEvent)e.event,getScreen());
}
catch(Exception exc) {
exc.printStackTrace();
}
}
break;
case 4:
for(InputListener l : currentScreen.listeners) {
try {
l.mouseEntered((MouseEvent)e.event,getScreen());
}
catch(Exception exc) {
exc.printStackTrace();
}
}
break;
case 5:
for(InputListener l : currentScreen.listeners) {
try {
l.mouseExited((MouseEvent)e.event,getScreen());
}
catch(Exception exc) {
exc.printStackTrace();
}
}
break;
case 6:
input.mousePressed((MouseEvent)e.event);
for(InputListener l : currentScreen.listeners) {
try {
l.mousePressed((MouseEvent)e.event,getScreen());
}
catch(Exception exc) {
exc.printStackTrace();
}
}
break;
case 7:
input.mouseReleased((MouseEvent)e.event);
for(InputListener l : currentScreen.listeners) {
try {
l.mouseReleased((MouseEvent)e.event,getScreen());
}
catch(Exception exc) {
exc.printStackTrace();
}
}
break;
case 8:
input.mouseDragged((MouseEvent)e.event);
for(InputListener l : currentScreen.listeners) {
try {
l.mouseDragged((MouseEvent)e.event,getScreen());
}
catch(Exception exc) {
exc.printStackTrace();
}
}
break;
case 9:
input.mouseMoved((MouseEvent)e.event);
for(InputListener l : currentScreen.listeners) {
try {
l.mouseMoved((MouseEvent)e.event,getScreen());
}
catch(Exception exc) {
exc.printStackTrace();
}
}
break;
case 10:
for(InputListener l : currentScreen.listeners) {
try {
l.mouseWheelMoved((MouseWheelEvent)e.event,getScreen());
}
catch(Exception exc) {
exc.printStackTrace();
}
}
break;
case 11:
try {
resized(getWidth(),getHeight());
}
catch(Exception exc) {
exc.printStackTrace();
}
break;
case 12:
if(isPaused() && isActive())
try {
resume();
}
catch(Exception exc) {
exc.printStackTrace();
}
break;
case 13:
if(!isPaused() && isActive())
try {
pause();
}
catch(Exception exc) {
exc.printStackTrace();
}
break;
}
}
events.clear();
events.addAll(tempEvents);
tempEvents.clear();
}
isProcessingEvents = false;
}
public final void init() {
setIgnoreRepaint(true);
setLayout(new BorderLayout());
add(canvas);
canvas.setSize(super.getWidth(),super.getHeight());
canvas.setIgnoreRepaint(true);
canvas.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent ce) {
if(isProcessingEvents) {
tempEvents.add(new Event(11,ce));
}
else {
synchronized(events) {
events.add(new Event(11,ce));
}
}
}
});
canvas.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent fe) {
if(isProcessingEvents) {
tempEvents.add(new Event(12,fe));
}
else {
synchronized(events) {
events.add(new Event(12,fe));
}
}
}
public void focusLost(FocusEvent fe) {
if(isProcessingEvents) {
tempEvents.add(new Event(13,fe));
}
else {
synchronized(events) {
events.add(new Event(13,fe));
}
}
input.reset();
}
});
new Thread() {
public void run() {
while(true) {
try {
Thread.sleep(Long.MAX_VALUE);
}
catch(Exception exc) {}
}
}
}.start();
}
/**
* Automatically called if this game is an Applet, otherwise it has to be manually called. This method starts the game loop thread.
*/
public final void start() {
if(!isActive())
new Thread() {
public void run() {
gameLoop();
}
}.start();
}
/**
* Called when the window is closed. Calling this method stops the game loop. stopGame() is then called on the game loop thread.
*/
public final void stop() {
sound.setOn(false);
isActive = false;
}
/**
* Called as soon as the game is created.
*/
protected abstract void initGame();
/**
* Called the set FPS times a second. Updates the current screen.
* @param deltaTime The time passed since the last call to it.
*/
protected void update(long deltaTime) {
getScreen().update(deltaTime);
}
/**
* Called when this game loses focus.
*/
protected void paused() {
getScreen().paused();
}
/**
* Called when this game regains focus.
*/
protected void resumed() {
getScreen().resumed();
}
/**
* called when the game is resized.
* @param width The new width.
* @param height The new height.
*/
protected void resized(int width, int height) {
getScreen().resized(width, height);
}
/**
* Called when this game is stopped.
* @return true if the window should be closed, false otherwise.
*/
protected boolean stopGame() {
return true;
}
/**
* Called the set FPS times a second. Clears the window using the Graphics2D's background color then draws the current screen.
* @param g The Graphics context to be used to draw to the canvas.
*/
protected void paint(Graphics2D g) {
g.clearRect(0, 0, getWidth(), getHeight());
getScreen().draw((Graphics2D)g.create());
}
/**
* Adds a screen to this game.
* @param screen The Screen to add.
* @param name The name of the screen.
*/
public synchronized void addScreen(Screen screen, String name) {
if(screen == null)
throw new IllegalArgumentException("Screen cannot be null.");
if(name == null)
throw new IllegalArgumentException("Name cannot be null.");
screens.put(name,new ScreenInfo(screen));
screen.init(this);
}
/**
* Returns the current screen.
* @return The current screen.
*/
public Screen getScreen() {
return currentScreen.screen;
}
/**
* Returns the name of the current screen. This is the same as calling <code>getName(getScreen())</code>.
* @return The name of the current screen.
*/
public String getScreenName() {
return getName(getScreen());
}
/**
* Returns the screen specified
* @param name The name of the screen.
* @return The screen associated with the specified name.
*/
public Screen getScreen(String name) {
return screens.get(name).screen;
}
/**
* Returns the name of the screen.
* @param screen The Screen who's name is returned.
* @return The name of the specified screen.
*/
public synchronized String getName(Screen screen) {
for(String s : screens.keySet())
if(screens.get(s).screen == screen)
return s;
return null;
}
/**
* Adds the screen and sets it as the current screen.
* @param screen The Screen to be added and set.
* @param name The name assigned to the Screen.
*/
public synchronized void setScreen(Screen screen, String name) {
addScreen(screen,name);
setScreen(name);
}
public void setScreen(Screen screen) {
setScreen(getScreenInfo(screen));
}
public void setScreen(String name) {
ScreenInfo info = screens.get(name);
if(info == null)
throw new IllegalArgumentException(name + " does not exist.");
setScreen(info);
}
private void setScreen(ScreenInfo screenInfo) {
if(screenInfo == null || !screens.containsValue(screenInfo))
throw new IllegalArgumentException("Screen has not been added.");
currentScreen.screen.hide();
currentScreen = screenInfo;
if(isActive)
currentScreen.screen.show();
}
private ScreenInfo getScreenInfo(Screen screen) {
if(screen == null)
return null;
for(ScreenInfo s : screens.values())
if(s.screen == screen)
return s;
return null;
}
/**
* Adds an input listener on the specified screen.
* @param screen The Screen to add the listener to.
* @param listener The InputListener to be notified of input events on this screen.
*/
public void addInputListener(Screen screen, InputListener listener) {
if(screen == null)
throw new IllegalArgumentException("Screen cannot be null.");
addInputListener(getScreenInfo(screen),listener);
}
/**
* Adds an input listener on the specified screen.
* @param name The name of the screen to add the listener to.
* @param listener The InputListener to be notified of input events on this screen.
*/
public void addInputListener(String name, InputListener listener) {
ScreenInfo info = screens.get(name);
if(info == null)
throw new IllegalArgumentException(name + " does not exist.");
addInputListener(screens.get(name),listener);
}
private synchronized void addInputListener(ScreenInfo screenInfo, InputListener listener) {
if(screenInfo == null || !screens.containsValue(screenInfo))
throw new IllegalArgumentException("Screen has not been added.");
if(listener == null)
throw new IllegalArgumentException("InputListener cannot be null.");
screenInfo.listeners.add(listener);
}
/**
* Removes the input listener from the specified screen.
* @param screen The Screen to remove the listener from.
* @param listener The InputListener reference to remove.
*/
public void removeInputListener(Screen screen, InputListener listener) {
if(screen == null)
throw new IllegalArgumentException("Screen cannot be null.");
removeInputListener(getScreenInfo(screen),listener);
}
/**
* Removes the input listener from the specified screen.
* @param name The name of the screen to remove the listener from.
* @param listener The InputListneer reference to remove.
*/
public void removeInputListener(String name, InputListener listener) {
ScreenInfo info = screens.get(name);
if(info == null)
throw new IllegalArgumentException(name + " does not exist.");
removeInputListener(screens.get(name),listener);
}
private synchronized void removeInputListener(ScreenInfo screenInfo, InputListener listener) {
if(screenInfo == null || !screens.containsValue(screenInfo))
throw new IllegalArgumentException("Screen has not been added.");
if(listener == null)
throw new IllegalArgumentException("InputListener cannot be null.");
screenInfo.listeners.remove(listener);
}
/**
* Sets the version of the game.
* @param version The current version of the game.
*/
public void setVersion(double version) {
this.version = version;
}
/**
* Returns the version of the game.
* @return The current version of the game.
*/
public double getVersion() {
return version;
}
/**
* Sets the showFPS property.
* @param showFPS If true, the FPS is updated and displayed every second, else the FPS is not displayed.
*/
public void showFPS(boolean showFPS) {
this.showFPS = showFPS;
}
/**
* Returns the current state of the showFPS property.
* @return If true, the FPS is updated and displayed every second, else the FPS is not displayed.
*/
public boolean isShowingFPS() {
return showFPS;
}
/**
* Sets the optimal FPS of this game.
* @param FPS Specifies the number of updates and frames shown per second.
*/
public void setFPS(int FPS) {
this.FPS = FPS;
}
/**
* Returns the optimal FPS of this game.
* @return The number of udpates and frames shown per second.
*/
public int getFPS() {
return FPS;
}
/**
* Sets whether the game loop should use Thread.yield() or Thread.sleep(1).<br>
* Thread.yield() produces a smoother game loop but at the expense of a high CPU usage.<br>
* Thread.sleep(1) is less smooth but barely uses any CPU time.<br>
* The default is Thread.sleep(1).
* @param useYield If true, uses Thread.yield(), otherwise uses Thread.sleep(1).
*/
public void useYield(boolean useYield) {
this.useYield = useYield;
}
/**
* Returns whether the game loop uses Thread.yield() or Thread.sleep(1). The default is Thread.sleep(1).
* @return True if the game loop uses Thread.yield(), false if it uses Thread.sleep(1).
*/
public boolean usesYield() {
return useYield;
}
/**
* Sets the quality of this game's graphics.
* @param highQuality If true, the graphics are of high quality, else the graphics are of low quality.
*/
public void setHighQuality(boolean highQuality) {
if(highQuality)
quality = RenderingHints.VALUE_ANTIALIAS_ON;
else
quality = RenderingHints.VALUE_ANTIALIAS_OFF;
}
/**
* Returns the current state of the quality property.
* @return If true, the graphics are of high quality, else the graphics are of low quality.
*/
public boolean isHighQuality() {
return quality == RenderingHints.VALUE_ANTIALIAS_ON;
}
/**
* Sets the maximum number of updates before render.
* @param maxUpdates The maximum number of updates before render.
*/
public void setMaximumUpdatesBeforeRender(int maxUpdates) {
this.maxUpdates = maxUpdates;
}
/**
* Returns the maximum number of updates before render.
* @return The maximum number of updates before render.
*/
public int getMaximumUpdatesBeforeRender() {
return maxUpdates;
}
/**
* Returns a reference to the Art object.
* @return A reference to the Art object.
*/
public Art getArt() {
return art;
}
/**
* Returns a reference to the Sound object.
* @return A reference to the Sound object.
*/
public Sound getSound() {
return sound;
}
/**
* Returns a reference to the Input object.
* @return A reference to the Input object.
*/
public Input getInput() {
return input;
}
private static class ScreenInfo {
private Screen screen;
private ArrayList<InputListener> listeners = new ArrayList<InputListener>();
public ScreenInfo(Screen screen) {
this.screen = screen;
}
}
private static class Event {
int id;
AWTEvent event;
public Event(int id, AWTEvent event) {
this.id = id;
this.event = event;
}
}
private class Listener implements KeyListener, MouseListener, MouseMotionListener, MouseWheelListener {
public void keyTyped(KeyEvent key) {
if(isProcessingEvents) {
tempEvents.add(new Event(0,key));
}
else {
synchronized(events) {
events.add(new Event(0,key));
}
}
}
public void keyPressed(KeyEvent key) {
if(isProcessingEvents) {
tempEvents.add(new Event(1,key));
}
else {
synchronized(events) {
events.add(new Event(1,key));
}
}
}
public void keyReleased(KeyEvent key) {
if(isProcessingEvents) {
tempEvents.add(new Event(2,key));
}
else {
synchronized(events) {
events.add(new Event(2,key));
}
}
}
public void mouseClicked(MouseEvent me) {
if(isProcessingEvents) {
tempEvents.add(new Event(3,me));
}
else {
synchronized(events) {
events.add(new Event(3,me));
}
}
}
public void mouseEntered(MouseEvent me) {
if(isProcessingEvents) {
tempEvents.add(new Event(4,me));
}
else {
synchronized(events) {
events.add(new Event(4,me));
}
}
}
public void mouseExited(MouseEvent me) {
if(isProcessingEvents) {
tempEvents.add(new Event(5,me));
}
else {
synchronized(events) {
events.add(new Event(5,me));
}
}
}
public void mousePressed(MouseEvent me) {
if(isProcessingEvents) {
tempEvents.add(new Event(6,me));
}
else {
synchronized(events) {
events.add(new Event(6,me));
}
}
}
public void mouseReleased(MouseEvent me) {
if(isProcessingEvents) {
tempEvents.add(new Event(7,me));
}
else {
synchronized(events) {
events.add(new Event(7,me));
}
}
}
public void mouseDragged(MouseEvent me) {
if(isProcessingEvents) {
tempEvents.add(new Event(8,me));
}
else {
synchronized(events) {
events.add(new Event(8,me));
}
}
}
public void mouseMoved(MouseEvent me) {
if(isProcessingEvents) {
tempEvents.add(new Event(9,me));
}
else {
synchronized(events) {
events.add(new Event(9,me));
}
}
}
public void mouseWheelMoved(MouseWheelEvent mwe) {
if(isProcessingEvents) {
tempEvents.add(new Event(10,mwe));
}
else {
synchronized(events) {
events.add(new Event(10,mwe));
}
}
}
}
}
|
package grouplab;
import java.util.Hashtable;
public class Board {
Hashtable<Integer, Integer> store;
int size = 0;
// creates a standard checkers board of dimension 8
public Board() {
store = new Hashtable<Integer, Integer>(8*8);
}
// creates a checkers board of dimension size
public Board(int s) {
size = s;
store = new Hashtable<Integer, Integer>(s*s);
}
// creates a clone of board b
public Board(Board b) {
store = b.store;
size = b.size;
}
// converts x, y coords to board index
public int convertCoord(int x, int y) {
return (x + (y * size));
}
// places a piece with id at index
public void setPiece(int index, int id) {
if (store.get(index) != 0) {
System.out.printf("Piece already exists at %d!", index);
return;
}
store.put(index, id);
}
// get the piece at a given location
public int pieceAt(int index) {
return store.get(index);
}
// detects if a piece is on the last column
public boolean onLastCol(int index) {
if ((index + 1) % size == 0)
return true;
return false;
}
// detects if a piece is on the first column
public boolean onFirstCol(int index) {
if ((index == 0) or (index % size == 0))
return true;
return false;
}
// detects if a piece is on the first row
public boolean onFirstRow(int index) {
if (index < size)
return true;
return false;
}
// detects if a piece is on the last row
public boolean onLastRowint index) {
if ((index < Math.pow(size, 2) - size))
return true;
return false;
}
// prints the board to stdout
public void show() {
// TODO
}
// clears all pieces from the board
public void clear() {
for (int i = 0; i < size; i++) {
store.put(i, 0);
}
}
// TODO
// tests if two boards are equal
@Override
public boolean equals(Object o) {
return false;
}
}
|
package imagej.legacy.plugin;
import ij.IJ;
import ij.ImageJ;
import imagej.patcher.LegacyHooks;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.image.ImageProducer;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import javax.swing.SwingUtilities;
import org.scijava.Context;
/**
* The <i>ij1-patcher</i> defaults to running this class whenever a new
* {@code PluginClassLoader} is initialized.
*
* @author Johannes Schindelin
*/
public class LegacyInitializer implements Runnable {
@Override
public void run() {
final ClassLoader loader = IJ.getClassLoader();
Thread.currentThread().setContextClassLoader(loader);
if (!GraphicsEnvironment.isHeadless() &&
!SwingUtilities.isEventDispatchThread()) try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
Thread.currentThread().setContextClassLoader(loader);
}
});
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
// ignore
}
try {
/*
* Instantiate a Context if there is none; IJ.runPlugIn() will be intercepted
* by the legacy hooks if they are installed and return the current Context.
* If no legacy hooks are installed, ImageJ 1.x will instantiate the Context using
* the PluginClassLoader and the LegacyService will install the legacy hooks.
*/
IJ.runPlugIn(Context.class.getName(), null);
} catch (Throwable t) {
// do nothing; we're not in the PluginClassLoader's class path
return;
}
// make sure that the Event Dispatch Thread's class loader is set
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Thread.currentThread().setContextClassLoader(IJ.getClassLoader());
}
});
// set icon and title of main window (which are instantiated before the initializer is called)
final ImageJ ij = IJ.getInstance();
if (ij != null) try {
final LegacyHooks hooks = (LegacyHooks) IJ.class.getField("_hooks").get(null);
ij.setTitle(hooks.getAppName());
final URL iconURL = hooks.getIconURL();
if (iconURL != null) try {
Object producer = iconURL.getContent();
Image image = ij.createImage((ImageProducer)producer);
ij.setIconImage(image);
if (IJ.isMacOSX()) try {
// NB: We also need to set the dock icon
final Class<?> clazz = Class.forName("com.apple.eawt.Application");
final Object app = clazz.getMethod("getApplication").invoke(null);
clazz.getMethod("setDockIconImage", Image.class).invoke(app, image);
} catch (Throwable t) {
t.printStackTrace();
}
} catch (IOException e) {
IJ.handleException(e);
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}
|
package org.epics.util.array;
/**
* Utilities for manipulating ListNumbers.
*
* @author carcassi
*/
public class ListNumbers {
/**
* Creates a sorted view of the given ListNumber.
* <p>
* The ListNumber is not sorted in place, and the data is not copied out.
* Therefore it's intended that the ListNumber is not changed while
* the view is used.
*
* @param values the values to be sorted
* @return the sorted view
*/
public static SortedListView sortedView(ListNumber values) {
SortedListView view = new SortedListView(values);
if (values.size() <= 1) {
// Nothing to sort
return view;
}
double value = values.getDouble(0);
for (int i = 1; i < values.size(); i++) {
double newValue = values.getDouble(i);
if (value > newValue) {
SortedListView.quicksort(view);
return view;
}
value = newValue;
}
return view;
}
/**
* Creates a sorted view of the given ListNumber based on the indexes provided.
* This method can be used to sort the given values based on the ordering
* by another (sorted) list of values.
* <p>
* The ListNumber is not sorted in place, and the data is not copied out.
* Therefore it's intended that the ListNumber is not changed while
* the view is used.
*
* @param values the values to be sorted
* @param indexes the ordering to be used for the view
* @return the sorted view
*/
public static SortedListView sortedView(ListNumber values, ListInt indexes) {
SortedListView view = new SortedListView(values, indexes);
return view;
}
/**
* Finds the value in the list, or the one right below it.
*
* @param values a list of values
* @param value a value
* @return the index of the value
*/
public static int binarySearchValueOrLower(ListNumber values, double value) {
if (value <= values.getDouble(0)) {
return 0;
}
if (value >= values.getDouble(values.size() -1)) {
return values.size() - 1;
}
int index = binarySearch(0, values.size() - 1, values, value);
while (index != 0 && value == values.getDouble(index - 1)) {
index
}
return index;
}
/**
* Finds the value in the list, or the one right above it.
*
* @param values a list of values
* @param value a value
* @return the index of the value
*/
public static int binarySearchValueOrHigher(ListNumber values, double value) {
if (value <= values.getDouble(0)) {
return 0;
}
if (value >= values.getDouble(values.size() -1)) {
return values.size() - 1;
}
int index = binarySearch(0, values.size() - 1, values, value);
while (index != values.size() - 1 && value > values.getDouble(index)) {
index++;
}
while (index != values.size() - 1 && value == values.getDouble(index + 1)) {
index++;
}
return index;
}
private static int binarySearch(int low, int high, ListNumber values, double value) {
// Taken from JDK
while (low <= high) {
int mid = (low + high) >>> 1;
double midVal = values.getDouble(mid);
if (midVal < value)
low = mid + 1; // Neither val is NaN, thisVal is smaller
else if (midVal > value)
high = mid - 1; // Neither val is NaN, thisVal is larger
else {
long midBits = Double.doubleToLongBits(midVal);
long keyBits = Double.doubleToLongBits(value);
if (midBits == keyBits) // Values are equal
return mid; // Key found
else if (midBits < keyBits) // (-0.0, 0.0) or (!NaN, NaN)
low = mid + 1;
else // (0.0, -0.0) or (NaN, !NaN)
high = mid - 1;
}
}
return low - 1; // key not found.
}
/**
* Creates a list of equally spaced values given the range and the number of
* elements.
* <p>
* Note that, due to rounding errors in double precision, the difference
* between the elements may not be exactly the same.
*
* @param minValue the first value in the list
* @param maxValue the last value in the list
* @param size the size of the list
* @return a new list
*/
public static ListNumber linearListFromRange(final double minValue, final double maxValue, final int size) {
if (size <= 0) {
throw new IllegalArgumentException("Size must be positive (was " + size + " )");
}
return new LinearListDoubleFromRange(size, minValue, maxValue);
}
/**
* Creates a list of equally spaced values given the first value, the
* step between element and the size of the list.
*
* @param initialValue the first value in the list
* @param increment the difference between elements
* @param size the size of the list
* @return a new list
*/
public static ListNumber linearList(final double initialValue, final double increment, final int size) {
if (size <= 0) {
throw new IllegalArgumentException("Size must be positive (was " + size + " )");
}
return new LinearListDouble(size, initialValue, increment);
}
/**
* Tests whether the list contains a equally spaced numbers.
* <p>
* Always returns true if the list was created with {@link #linearList(double, double, int) }
* or {@link #linearListFromRange(double, double, int) }. For all other cases,
* takes the first and last value, creates a linearListFromRange, and checks
* whether the difference is greater than the precision allowed by double.
* Note that this method is really strict, and it may rule out cases
* that may be considered to be linear.
*
* @param listNumber
* @return
*/
public static boolean isLinear(ListNumber listNumber) {
if (listNumber instanceof LinearListDouble || listNumber instanceof LinearListDoubleFromRange) {
return true;
}
ListDouble diff = ListMath.subtract(listNumber, linearListFromRange(listNumber.getDouble(0), listNumber.getDouble(listNumber.size() - 1), listNumber.size()));
for (int i = 0; i < diff.size(); i++) {
if (Math.abs(diff.getDouble(i)) > Math.ulp(listNumber.getDouble(i))) {
return false;
}
}
return true;
}
/**
* Converts an array of primitive numbers to the appropriate ListNumber
* implementation.
*
* @param primitiveArray must be an array of primitive numbers (byte[],
* short[], int[], long[], float[] or double[])
* @return the wrapped array
*/
public static ListNumber toListNumber(Object primitiveArray) {
if (primitiveArray instanceof byte[]) {
return new ArrayByte((byte[]) primitiveArray);
} else if (primitiveArray instanceof short[]) {
return new ArrayShort((short[]) primitiveArray);
} else if (primitiveArray instanceof int[]) {
return new ArrayInt((int[]) primitiveArray);
} else if (primitiveArray instanceof long[]) {
return new ArrayLong((long[]) primitiveArray);
} else if (primitiveArray instanceof float[]) {
return new ArrayFloat((float[]) primitiveArray);
} else if (primitiveArray instanceof double[]) {
return new ArrayDouble((double[]) primitiveArray);
} else {
throw new IllegalArgumentException(primitiveArray + " is not a an array of primitive numbers");
}
}
private static class LinearListDoubleFromRange extends ListDouble {
private final int size;
private final double minValue;
private final double maxValue;
public LinearListDoubleFromRange(int size, double minValue, double maxValue) {
this.size = size;
this.minValue = minValue;
this.maxValue = maxValue;
}
@Override
public double getDouble(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
return minValue + (index * (maxValue - minValue)) / (size - 1);
}
@Override
public int size() {
return size;
}
}
private static class LinearListDouble extends ListDouble {
private final int size;
private final double initialValue;
private final double increment;
public LinearListDouble(int size, double initialValue, double increment) {
this.size = size;
this.initialValue = initialValue;
this.increment = increment;
}
@Override
public double getDouble(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
return initialValue + index * increment;
}
@Override
public int size() {
return size;
}
}
}
|
package com.hortonworks.iotas.catalog;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.hortonworks.iotas.storage.Storable;
import java.util.Collection;
/**
* <p>
* A wrapper entity for passing entities and status back to the client.
* </p>
*
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CatalogResponse {
/**
* ResponseMessage args if any should always be string to keep it simple.
*/
public enum ResponseMessage {
/* 1000 to 1100 reserved for success status messages */
SUCCESS(1000, "Success", 0),
/* 1101 onwards for error messages */
ENTITY_NOT_FOUND(1101, "Entity with id [%s] not found.", 1),
EXCEPTION(1102, "An exception with message [%s] was thrown while processing request.", 1),
BAD_REQUEST_PARAM_MISSING(1103, "Bad request. Param [%s] is missing or empty.", 1),
DATASOURCE_TYPE_FILTER_NOT_FOUND(1104, "Datasource not found for type [%s], query params [%s].", 2),
ENTITY_NOT_FOUND_FOR_FILTER(1105, "Entity not found for query params [%s].", 1);
private int code;
private String msg;
private int nargs;
ResponseMessage(int code, String msg, int nargs) {
this.code = code;
this.msg = msg;
this.nargs = nargs;
}
/*
* whether an error message or just a status.
*/
private boolean isError() {
return code > 1100;
}
public int getCode() {
return code;
}
public static String format(ResponseMessage responseMessage, String... args) {
//TODO: validate number of args
return String.format(responseMessage.msg, args);
}
}
/**
* Response code.
*/
private int responseCode;
/**
* Response message.
*/
private String responseMessage;
/**
* For response that returns a single entity.
*/
private Storable entity;
/**
* For response that returns a collection of entities.
*/
private Collection<? extends Storable> entities;
private CatalogResponse() {}
public static class Builder {
private ResponseMessage responseMessage;
private Storable entity;
private Collection<? extends Storable> entities;
private String DOC_LINK_MESSAGE = " Please check webservice/ErrorCodes.md for more details.";
public Builder(ResponseMessage responseMessage) {
this.responseMessage = responseMessage;
}
public Builder entity(Storable entity) {
this.entity = entity;
return this;
}
public Builder entities(Collection<? extends Storable> entities) {
this.entities = entities;
return this;
}
public CatalogResponse format(String... args) {
CatalogResponse response = new CatalogResponse();
response.responseCode = responseMessage.code;
StringBuilder msg = new StringBuilder(ResponseMessage.format(responseMessage, args));
if(responseMessage.isError()) {
msg.append(DOC_LINK_MESSAGE);
}
response.responseMessage = msg.toString();
response.entity = entity;
response.entities = entities;
return response;
}
}
public static Builder newResponse(ResponseMessage msg) {
return new Builder(msg);
}
public String getResponseMessage() {
return responseMessage;
}
public int getResponseCode() {
return responseCode;
}
public Storable getEntity() {
return entity;
}
public Collection<? extends Storable> getEntities() {
return entities;
}
}
|
package org.whiteboard.gradebook;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Scanner;
/** Course contains information related to the users contained within it, as
* well as methods for modifying fields directly contained within it.
*
* @author Daniel Wolf <wolf@ccs.neu.edu>
* @version April 11, 2014 */
public class MyGradeBook {
private Map<String, Student> students;
private Map<String, Assignment> assignments;
private List<String> assignmentOrder;
private MyGradeBook() {
students = new HashMap<String, Student>();
assignments = new HashMap<String, Assignment>();
assignmentOrder = new ArrayList<String>();
}
/** Get a list of all assignments stored in MyGradeBook
*
* @return a list of all assignments in MyGradeBook */
protected Map<String, Assignment> getAssignments() {
return assignments;
}
/** Get an Assignment object by its name in string form.
* Case-insensitive.
*
* @param name
* the name of the assignment.
* @return the resulting assignment,
* @throws a NoSuchElementException if the assignment does not exist.
*/
protected Assignment getAssignment(String name) throws NoSuchElementException{
if(assignments.containsKey(name)) {
return assignments.get(name);
}
else {
throw new NoSuchElementException("Assignment does not exist");
}
}
protected boolean addStudent(String name, Student student) {
students.put(name, student);
return true;
}
protected boolean dropStudent(Student student) {
students.remove(student);
return true;
}
protected boolean addAssignment(String name, Assignment assignment) {
assignments.put(name, assignment);
assignmentOrder.add(name);
return true;
}
protected boolean dropAssignment(String name) {
assignments.remove(name);
assignmentOrder.remove(name);
return true;
}
protected Student getStudent(String id) {
return students.get(id);
}
/** Factory method to construct an empty MyGradebook
*
* @return an empty MyGradeBook */
public static MyGradeBook initialize() {
return new MyGradeBook();
}
/** Factory method to construct a MyGradebook that contains the grade
* book from filename
*
* @param filename
* the filename for the file that contains the initial grade
* book, which is formatted like initial.txt
* @return a MyGradebook that contains the grade book from filename
* @throws FileNotFoundException */
public static MyGradeBook initializeWithFile(String filename)
throws FileNotFoundException {
File f = new File(filename);
Scanner s;
s = new Scanner(f);
String fileString = "";
while (s.hasNextLine()) {
fileString += s.nextLine() + "\n";
}
return initializeWithString(fileString);
}
/** Factory method to construct a MyGradebook that contains the grade
* book from startingString
*
* @param startingString
* String that contains the initial grade book, which is
* formatted like initial.txt
* @return a MyGradebook that contains the grade book from
* startingString */
public static MyGradeBook initializeWithString(String startingString) {
MyGradeBook gb = MyGradeBook.initialize();
String[] lines = startingString.split("\n");
try {
if (lines.length >= 4 && lines[0].equals("GRADEBOOK")) {
String[] assignments = lines[1].split("\t");
String[] pointsOutOf = lines[2].split("\t");
String[] pointsGrade = lines[3].split("\t");
for (int ai = 5; ai < assignments.length; ai++) {
gb.addAssignment(assignments[ai], new Assignment(
assignments[ai], "", "", new Double(
pointsOutOf[ai]), new Double(
pointsGrade[ai])));
}
// Parse assignment grades
for (int l = 4; l < lines.length; l++) {
String[] student = lines[l].split("\t");
gb.addStudent(student[0], new Student(student[1],
student[2], student[3], student[0], student[4],
student[0]));
for (int grade = 5; grade < student.length; grade++) {
gb.getAssignment(assignments[grade]).addGrade(
student[0], new Double(student[grade]));
}
}
return gb;
}
else {
throw new RuntimeException("File is not a valid Gradebook");
}
}
catch (IndexOutOfBoundsException e) {
throw new RuntimeException("File is not a valid Gradebook");
}
}
public void processFile(String filename) {
try {
File f = new File(filename);
Scanner s;
s = new Scanner(f);
String fileString = "";
while (s.hasNextLine()) {
fileString += s.nextLine() + "\n";
}
processString(fileString);
}
catch (FileNotFoundException e) {
throw new RuntimeException(e.getLocalizedMessage());
}
}
public void processString(String additionalString) {
String[] lines = additionalString.split("\n");
if (lines[0].equals("ASSIGNMENT")) {
addAssignment(lines[1], new Assignment(lines[1], "", "",
new Double(lines[2]), new Double(lines[3])));
for(Student student : students.values()) {
assignments.get(lines[1]).addGrade(student.id, 0);
}
// if more steps need to be taken, combine lines and pass
// recursively.
if (lines.length > 4) {
String next = "";
for (int i = 4; i < lines.length; i++) {
next += lines[i] + "\n";
}
processString(next);
}
}
else if (lines[0].equals("STUDENT")) {
addStudent(lines[1], new Student(lines[2], lines[3], lines[4],
lines[1], lines[5], lines[1]));
for(Assignment a : this.assignments.values()) {
a.addGrade(lines[1], 0);
}
// if more steps need to be taken, combine lines and pass
// recursively.
if (lines.length > 6) {
String next = "";
for (int i = 6; i < lines.length; i++) {
next += lines[i] + "\n";
}
processString(next);
}
}
else if (lines[0].equals("GRADES_FOR_ASSIGNMENT")) {
Assignment a = getAssignment(lines[1]);
for (int i = 2; i < lines.length; i = i + 2) {
a.addGrade(lines[i], new Double(lines[i + 1]));
}
}
else if (lines[0].equals("GRADES_FOR_STUDENT")) {
String student = lines[1];
for (int i = 2; i < lines.length; i = i + 2) {
Assignment a = getAssignment(lines[i]);
a.addGrade(student, new Double(lines[i + 1]));
}
}
else if (lines[0].equals("")) {
// no worries
}
else {
throw new RuntimeException("Unexpected Operation Type");
}
}
/** Changes the assignment (named assignmentName) grade for student
* (whose username is equal to username) to newGrade
*
* @param assignmentName
* name of the assignment
* @param username
* username for the student
* @param newGrade
* the new grade for the given assignment and student
* @return whether there was a grade to change. Returns true if the
* given assignment/student combination exists, returns false
* otherwise
* @throws NoSuchElementException if given assigmentName or username do
* not exist
* */
public boolean changeGrade(String assignmentName, String username,
double newGrade) throws NoSuchElementException {
if (assignments.containsKey(assignmentName)) {
assignments.get(assignmentName).setGrade(username, newGrade);
return true;
}
else {
throw new NoSuchElementException("Given username or assignment"
+ "does not exist");
}
}
/** Calculates the average across all students for a given assignment
*
* @param assignmentName
* name of the assignment
* @return the average across all students for assignmentName */
public double average(String assignmentName) {
return getAssignment(assignmentName).calculateAverage();
}
/** Calculates the median across all students for a given assignment
*
* @param assignmentName
* name of the assignment
* @return the median across all students for assignmentName */
public double median(String assignmentName) {
return getAssignment(assignmentName).calculateMedian();
}
/** Calculates the min across all students for a given assignment
*
* @param assignmentName
* name of the assignment
* @return the min across all students for assignmentName */
public double min(String assignmentName) {
return getAssignment(assignmentName).getMin();
}
/** Calculates the max across all students for a given assignment
*
* @param assignmentName
* name of the assignment
* @return the max across all students for assignmentName */
public double max(String assignmentName) {
return getAssignment(assignmentName).getMax();
}
/** Calculates the current grade for the given student
*
* @param username
* username for the student
* @return the current grade for student with username. The current
* grade is calculated based on the current assignment grades,
* assignment total points, assignment percent of semester. The
* current grade for a student is the sum of the relative
* assignment grades divided by the current percent of semester
* time 100. Since all grades may not currently be entered, we
* have to divide by the current percent. The relative
* assignment grade is the student's assignment grade divide by
* total point value for the assignment times the percent of
* semester. */
public double currentGrade(String username) {
Double sumRelativeAssignmentGrades = new Double(0);
Double sumWeights = new Double(0);
for (Assignment a : assignments.values()) {
try {
sumRelativeAssignmentGrades += ((a.getGrade(username) / a.getTotalPointsPossible()) * a.getWeight());
sumWeights += a.getWeight();
}
catch (NoSuchElementException e) {
// Do nothing, the student just missed this assignment and
// will be deducted full credit
}
}
Double ret = 100 * sumRelativeAssignmentGrades / sumWeights;
ret = Math.round(ret * 100) / 100.0;
return ret;
}
/** Calculates the current grade for all students
*
* @return HashMap of the current grades for all students. The key of
* the HashMap is the username of the student. The value is the
* current grade for the associated student. The current grade
* is calculated based on the current assignment grades,
* assignment total points, assignment percent of semester. The
* current grade for a student is the sum of the relative
* assignment grades divided by the current percent of semester
* time 100. Since all grades may not currently be entered, we
* have to divide by the current percent. The relative
* assignment grade is the student's assignment grade divide by
* total point value for the assignment times the percent of
* semester. */
public HashMap<String, Double> currentGrades() {
HashMap<String, Double> currentGrades = new HashMap<String, Double>();
for (String studentID : students.keySet()) {
currentGrades.put(studentID, currentGrade(studentID));
}
return currentGrades;
}
/** Provides the grade earned by the given student for the given
* assignment
*
* @param assignmentName
* name of the assignment
* @param username
* username for the student
* @return the grade earned by username for assignmentName */
public double assignmentGrade(String assignmentName, String username) {
return assignments.get(assignmentName).getGrade(username);
}
public String outputCurrentGrades() {
HashMap<String, Double> grades = currentGrades();
String output = "CURRENT_GRADES\n";
for (String student : grades.keySet()) {
output += student + "\t" + grades.get(student) + "\n";
}
return output;
}
public String outputStudentGrades(String username) throws NoSuchElementException{
if(students.containsKey(username)) {
Student s = getStudent(username);
String export = "STUDENT_GRADES\n";
export += s.getID() + "\n";
export += s.getFirstName() + "\n";
export += s.getLastName() + "\n";
export += s.getAdvisor() + "\n";
export += s.getGraduationYear() + "\n";
export += "
for (String assignmentName : assignmentOrder) {
export +=
assignmentName + "\t"
+ assignmentGrade(assignmentName, username)
+ "\n";
}
export += "
export += "CURRENT GRADE\t" + currentGrade(username);
return export;
}
else {
throw new NoSuchElementException("Student with given username "
+ "does not exist");
}
}
public String outputAssignmentGrades(String assignName) throws NoSuchElementException {
if(assignments.containsKey(assignName)) {
String export = "ASSIGNMENT_GRADES\n";
Assignment a = getAssignment(assignName);
export += assignName + "\n";
export += a.getTotalPointsPossible() + "\n";
export += a.getWeight() + "\n";
export += "
// Get and sort students by alphabetical, case insensitive order.
List<String> sts = new ArrayList<String>();
for(String str : students.keySet()) {
sts.add(str);
}
Collections.sort(sts, String.CASE_INSENSITIVE_ORDER);
for (String student : sts) {
export += student + "\t" + a.getGrade(student) + "\n";
}
export += "
export += "STATS\n";
export += "Average\t" + average(assignName) + "\n";
export += "Median\t" + median(assignName) + "\n";
export += "Max\t" + max(assignName) + "\n";
export += "Min\t" + min(assignName) + "\n";
return export;
}
else {
throw new NoSuchElementException("Assignment does not exist");
}
}
/** Provide a String that contains the current grade book. This String
* could be used to initialize a new grade book.
*
* @return a String that contains the current grade book. This String
* could be used to initialize a new grade book. The String
* should be formatted like gradebook.txt. The usernames will be
* listed alphabetically. */
public String outputGradebook() {
String export = "GRADEBOOK\n";
// Assignments
export += "\t\t\t\t";
for (String assn : assignmentOrder) {
export += "\t" + assn;
}
export += "\n";
// Max points
export += "\t\t\t\t";
for (String assn : assignmentOrder) {
export += "\t" + getAssignment(assn).getTotalPointsPossible();
}
export += "\n";
// Weights
export += "\t\t\t\t";
for (String assn : assignmentOrder) {
export += "\t" + getAssignment(assn).getWeight();
}
export += "\n";
// Students and grades
// Get and sort students by alphabetical, case insensitive order.
List<String> sts = new ArrayList<String>();
for(String str : students.keySet()) {
sts.add(str);
}
Collections.sort(sts, String.CASE_INSENSITIVE_ORDER);
for (String s : sts) {
Student st = getStudent(s);
export +=
s + "\t" + st.getFirstName() + "\t" + st.getLastName()
+ "\t" + st.getAdvisor() + "\t"
+ st.getGraduationYear();
for (String assn : assignmentOrder) {
export += "\t" + assignmentGrade(assn, s);
}
export += "\n";
}
return export;
}
public List<String> getAssignmentOrder() {
return this.assignmentOrder;
}
/**
* Checks if this MyGradeBook is equal to given Object
* @param obj the object equality is being checked agaist
*/
@Override
public boolean equals(Object obj) {
if(obj instanceof MyGradeBook) {
MyGradeBook temp = (MyGradeBook)obj;
if(this.students.equals(temp.students)
&& this.assignments.equals(temp.assignments)) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
/**
* creates an int hash of this MyGradeBook
* @retun an int hash
*/
@Override
public int hashCode() {
int hash = 0;
hash += assignments.hashCode() * 2411;
hash += students.hashCode() * 2371;
return hash;
}
}
|
package com.novoda.downloadmanager.lib;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
import java.io.InputStream;
class OkHttpNotificationImageRetriever implements NotificationImageRetriever {
private final OkHttpClient client;
private String imageUrl;
private Bitmap bitmap;
public OkHttpNotificationImageRetriever() {
client = new OkHttpClient();
}
@Override
public Bitmap retrieveImage(String imageUrl) {
if (imageUrl.equals(this.imageUrl)) {
return bitmap;
}
return fetchBitmap(imageUrl);
}
private Bitmap fetchBitmap(String imageUrl) {
Request request = new Request.Builder()
.get()
.url(this.imageUrl)
.build();
try {
Response response = client.newCall(request).execute();
InputStream inputStream = response.body().byteStream();
try {
this.imageUrl = imageUrl;
cleanupOldBitmap();
bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
inputStream.close();
}
} catch (IOException e) {
return null;
}
}
private void cleanupOldBitmap() {
if (bitmap == null) {
return;
}
if (!bitmap.isRecycled()) {
bitmap.recycle();
}
bitmap = null;
}
}
|
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import io.cloudracer.TestConstants;
import io.cloudracer.mocktcpserver.MockTCPServer;
import io.cloudracer.tcpclient.TCPClient;
public class TestRobustness {
private Logger logger = Logger.getLogger(this.getClass().getSimpleName());
private TCPClient client;
private MockTCPServer server;
@Before
public void setUp() throws Exception {
server = new MockTCPServer(TestConstants.MOCK_SERVER_PORT);
client = new TCPClient(TestConstants.MOCK_SERVER_PORT);
}
@After
public void tearDown() throws Exception {
client.close();
server.close();
}
@Test(timeout = TestConstants.TEST_TIMEOUT_10_MINUTE)
public void serverRestart() throws Exception {
final int totalServerRestarts = 1000;
for (int i = 0; i < totalServerRestarts; i++) {
logger.info(String.format("Restart itteration: %d", i));
client.close();
server.close();
server = new MockTCPServer(TestConstants.MOCK_SERVER_PORT);
client = new TCPClient(TestConstants.MOCK_SERVER_PORT);
}
}
}
|
package lombok;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.SOURCE)
public @interface Getter {
AccessLevel value() default lombok.AccessLevel.PUBLIC;
}
|
package com.zedeff.vendingma;
import android.app.Application;
import com.zedeff.vendingma.services.VendingMachine;
import com.zedeff.vendingma.services.VendingMachineImpl;
public class App extends Application {
private static VendingMachine vendingMachine = new VendingMachineImpl();
public static VendingMachine getVendingMachine() {
return vendingMachine;
}
}
|
package dateadog.dateadog;
import android.content.Context;
import android.provider.SyncStateContract;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.facebook.AccessToken;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.facebook.login.LoginManager;
import static dateadog.dateadog.LoginActivity.getUserLoginToken;
/**
* {@code DADAPI} interfaces with the Date-A-Dog server and the Petfinder API to retrieve and
* update information about the user and dogs available to them.
*/
public class DADAPI {
private static final String TAG = DADAPI.class.getName();
/*
private static DADAPI instance = null;
public static DADAPI getInstance() {
if (instance == null) {
instance = new DADAPI();
}
return instance;
}
*/
private static String PETFINDER_API_KEY = "d025e514d458e4366c42ea3006fd31b3";
private static String PETFINDER_URL_BASE = "http://api.petfinder.com/pet.find&format=json&animal=dog&output=full&count=100?key=" + PETFINDER_API_KEY;
private static String DAD_SERVER_URL_BASE = "http://ec2-35-160-226-75.us-west-2.compute.amazonaws.com/api/";
private static String FIND_DOGS_END_POINT = "getNextDogs";
private static String JUDGE__DOG_ENDPOINT = "judgeDog";
private static String DAD_SERVER_URL_BASE_DEMO = "http://ec2-35-160-226-75.us-west-2.compute.amazonaws.com/api/getNextDogsDemo";
private User user;
private int zipCode;
private int lastOffset;
private URL petfinderURL;
private Context context;
public DADAPI(Context context) {
this.context = context;
}
public void setUser(User user) {
this.user = user;
}
public void seenDog(Dog dog) {
JSONObject obj = new JSONObject();
// execute method and handle any error responses.
}
private Set<Dog> filterSeenDogs(Set<Dog> result) {
// backend.getSeenDogs(I) | filter result
return null;
}
public void setLocation(int zipCode) {
this.zipCode = zipCode;
this.lastOffset = 0;
try {
petfinderURL = new URL(PETFINDER_URL_BASE + "&location=" + zipCode + "&offset=" + lastOffset);
} catch (MalformedURLException e) {
Log.e(TAG, e.getMessage());
}
}
private void addDogsFromJSON(String data, Set<Dog> result) {
try {
JSONArray dogs = (JSONArray) new JSONTokener(Constants.DATA).nextValue();
for (int i = 0; i < dogs.length(); i++) {
result.add(new Dog((JSONObject) dogs.get(i)));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public Set<Dog> getNextDogs(int zipCode) {
final Set<Dog> result = new LinkedHashSet<>();
RequestQueue queue = Volley.newRequestQueue(context);
addDogsFromJSON("", result);
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,
DAD_SERVER_URL_BASE + FIND_DOGS_END_POINT,
new JSONObject(),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.v("Response = ", "It did something with response" + response.toString());
addDogsFromJSON(response.toString(), result);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error == null) {
Log.v("Null error", "it died with a null error");
} else if (error.getMessage() != null) {
// Log.v("Error message", error.getMessage());
} else {
Log.v("All are null", "");
}
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
params.put("access_token",getUserLoginToken());
return params;
}
};
Singleton.getInstance(context).addToRequestQueue(jsObjRequest);
return result;
// return filterSeenDogs(result);
}
public void judgeDog(Dog dog, boolean like) {
JSONObject dogLike = new JSONObject();
try {
dogLike.put("id", dog.getDogId());
dogLike.put("liked", like);
dogLike.put("epoch", System.currentTimeMillis());
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,
DAD_SERVER_URL_BASE + JUDGE__DOG_ENDPOINT,
dogLike,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.v("Response = ", "It did something with response" + response.toString());
//addDogsFromJSON(response.toString(), result);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error == null) {
Log.v("Null error", "it died with a null error");
} else if (error.getMessage() != null) {
// Log.v("Error message", error.getMessage());
} else {
Log.v("All are null", "");
}
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("access_token",getUserLoginToken());
return params;
}
};
Singleton.getInstance(context).addToRequestQueue(jsObjRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void createDogsListFromJSON(String json) {
}
public void likeDog(Dog dog) {
judgeDog(dog, true);
}
public void dislikeDog(Dog dog) {
judgeDog(dog, false);
}
public Set<DateRequest> getRequests() {
return null;
}
public void requestDate(Dog dog, Form form) {
}
}
|
package se.soy.gpg;
import java.util.List;
import java.util.ArrayList;
public class GPG {
// FIXME Remove when done
static<T> void println(T arg) { System.out.println(arg); }
public static void main(String[] args) {
println("main");
GPG.encrypt().armor().sign().recipient("0xrecipient").output();
/*
GPG.decrypt().armor().local-user("0xlocaluser").output("/tmp/a-file");
GPG.sign().armor().();
*/
}
private List<String> command = new ArrayList<String>();
private static GPG gpg = null;
public void output() {
println("OPTIONS:");
println("Command:");
println(command);
}
public static GPG encrypt() {
gpg = (null == gpg) ? new GPG() : gpg;
gpg.command.add("--encrypt");
return gpg;
}
public static GPG sign() {
gpg = (null == gpg) ? new GPG() : gpg;
gpg.command.add("--sign");
return gpg;
}
public GPG armor() {
command.add("--armor");
return this;
}
// TODO: Add recipients(List<String> recipients)
public GPG recipient(String recipient) {
command.add("-r " + recipient);
return this;
}
}
|
// M a i n //
// <editor-fold defaultstate="collapsed" desc="hdr"> //
// </editor-fold>
package omr;
import static omr.WellKnowns.*;
import omr.constant.Constant;
import omr.constant.ConstantManager;
import omr.constant.ConstantSet;
import omr.log.Logger;
import omr.score.Score;
import omr.script.Script;
import omr.script.ScriptManager;
import omr.step.ProcessingCancellationException;
import omr.step.Step;
import omr.step.Stepping;
import omr.step.Steps;
import omr.ui.MainGui;
import omr.ui.symbol.MusicFont;
import omr.util.Clock;
import omr.util.Dumping;
import omr.util.OmrExecutors;
import org.jdesktop.application.Application;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import javax.swing.JFrame;
public class Main
{
static {
/** Time stamp */
Clock.resetTime();
}
/** Build reference of the application as displayed to the user */
private static String toolBuild;
/** Name of the application as displayed to the user */
private static String toolName;
/** Version of the application as displayed to the user */
private static String toolVersion;
/** Master View */
private static MainGui gui;
/** Usual logger utility */
private static final Logger logger = Logger.getLogger(Main.class);
/** Specific application parameters */
private static final Constants constants = new Constants();
/** Parameters read from CLI */
private static CLI.Parameters parameters;
/** The application dumping service */
public static final Dumping dumping = new Dumping(Main.class.getPackage());
// Main //
private Main ()
{
}
// getBenchPath //
/**
* Report the bench path if present on the CLI
* @return the CLI bench path, or null
*/
public static String getBenchPath ()
{
return parameters.benchPath;
}
// getCliConstants //
/**
* Report the properties set at the CLI level
* @return the CLI-defined constant values
*/
public static Properties getCliConstants ()
{
if (parameters == null) {
return null;
} else {
return parameters.options;
}
}
// getExportPath //
/**
* Report the export path if present on the CLI
* @return the CLI export path, or null
*/
public static String getExportPath ()
{
return parameters.exportPath;
}
// getFilesTasks //
/**
* Prepare the processing of image files listed on command line
* @return the collection of proper callables
*/
public static List<Callable<Void>> getFilesTasks ()
{
List<Callable<Void>> tasks = new ArrayList<Callable<Void>>();
// Launch desired step on each score in parallel
for (final String name : parameters.inputNames) {
final File file = new File(name);
tasks.add(
new Callable<Void>() {
public Void call ()
throws Exception
{
logger.info(
"Launching " + parameters.desiredSteps +
" on " + name);
if (file.exists()) {
final Score score = new Score(file);
try {
Stepping.processScore(
parameters.desiredSteps,
score);
} catch (ProcessingCancellationException pce) {
logger.warning("Cancelled " + score, pce);
score.getBench()
.recordCancellation();
throw pce;
} catch (Exception ex) {
logger.warning("Exception occurred", ex);
throw ex;
} finally {
// Close (when in batch mode only)
if (gui == null) {
score.close();
}
return null;
}
} else {
String msg = "Could not find file " +
file.getCanonicalPath();
logger.warning(msg);
throw new RuntimeException(msg);
}
}
});
}
return tasks;
}
// setGui //
/**
* Register the GUI (done by the GUI itself when it is ready)
* @param gui the MainGui instance
*/
public static void setGui (MainGui gui)
{
Main.gui = gui;
}
// getGui //
/**
* Points to the single instance of the User Interface, if any.
*
* @return MainGui instance, which may be null
*/
public static MainGui getGui ()
{
return gui;
}
// getMidiPath //
/**
* Report the midi path if present on the CLI
* @return the CLI midi path, or null
*/
public static String getMidiPath ()
{
return parameters.midiPath;
}
// getPrintPath //
/**
* Report the print path if present on the CLI
* @return the CLI print path, or null
*/
public static String getPrintPath ()
{
return parameters.printPath;
}
// getScriptsTasks //
/**
* Prepare the processing of scripts listed on command line
* @return the collection of proper script callables
*/
public static List<Callable<Void>> getScriptsTasks ()
{
List<Callable<Void>> tasks = new ArrayList<Callable<Void>>();
// Launch desired scripts in parallel
for (String name : parameters.scriptNames) {
final String scriptName = name;
tasks.add(
new Callable<Void>() {
public Void call ()
throws Exception
{
long start = System.currentTimeMillis();
Script script = null;
File file = new File(scriptName);
logger.info("Loading script file " + file + " ...");
try {
FileInputStream fis = new FileInputStream(file);
script = ScriptManager.getInstance()
.load(fis);
fis.close();
script.run();
long stop = System.currentTimeMillis();
logger.info(
"Script file " + file + " run in " +
(stop - start) + " ms");
} catch (ProcessingCancellationException pce) {
Score score = script.getScore();
logger.warning("Cancelled " + score, pce);
if (score != null) {
score.getBench()
.recordCancellation();
}
} catch (FileNotFoundException ex) {
logger.warning(
"Cannot find script file " + file);
} catch (Exception ex) {
logger.warning("Exception occurred", ex);
} finally {
// Close when in batch mode
if ((gui == null) && (script != null)) {
Score score = script.getScore();
if (score != null) {
score.close();
}
}
}
return null;
}
});
}
return tasks;
}
// setToolBuild //
public static void setToolBuild (String toolBuild)
{
Main.toolBuild = toolBuild;
}
// getToolBuild //
/**
* Report the build reference of the application as displayed to the user
*
* @return Build reference of the application
*/
public static String getToolBuild ()
{
return toolBuild;
}
// setToolName //
public static void setToolName (String toolName)
{
Main.toolName = toolName;
}
// getToolName //
/**
* Report the name of the application as displayed to the user
*
* @return Name of the application
*/
public static String getToolName ()
{
return toolName;
}
// setToolVersion //
public static void setToolVersion (String toolVersion)
{
Main.toolVersion = toolVersion;
}
// getToolVersion //
/**
* Report the version of the application as displayed to the user
*
* @return version of the application
*/
public static String getToolVersion ()
{
return toolVersion;
}
// doMain //
/**
* Specific starting method for the application.
* @param args command line parameters
* @see omr.CLI the possible command line parameters
*/
public static void doMain (String[] args)
{
// Initialize tool parameters
initialize();
// Process CLI arguments
process(args);
// Locale to be used in the whole application ?
checkLocale();
if (!parameters.batchMode) {
// For interactive mode
if (logger.isFineEnabled()) {
logger.fine("Main. Launching MainGui");
}
Application.launch(MainGui.class, args);
} else {
// For batch mode
// Remember if at least one task has failed
boolean failure = false;
// Check MusicFont is loaded
MusicFont.checkMusicFont();
// Launch the required tasks, if any
List<Callable<Void>> tasks = new ArrayList<Callable<Void>>();
tasks.addAll(getFilesTasks());
tasks.addAll(getScriptsTasks());
if (!tasks.isEmpty()) {
try {
logger.info("Submitting " + tasks.size() + " task(s)");
List<Future<Void>> futures = OmrExecutors.getCachedLowExecutor()
.invokeAll(
tasks,
constants.processTimeOut.getValue(),
TimeUnit.SECONDS);
logger.info("Checking " + tasks.size() + " task(s)");
// Check for time-out
for (Future<Void> future : futures) {
try {
future.get();
} catch (Exception ex) {
logger.warning("Future exception", ex);
failure = true;
}
}
} catch (Exception ex) {
logger.warning("Error in processing tasks", ex);
failure = true;
}
}
// At this point all tasks have completed (normally or not)
// So shutdown immediately the executors
logger.info("SHUTTING DOWN ...");
OmrExecutors.shutdown(true);
// Store latest constant values on disk?
if (constants.persistBatchCliConstants.getValue()) {
ConstantManager.getInstance()
.storeResource();
}
// Stop the JVM with failure status?
if (failure) {
logger.warning("Exit with failure status");
System.exit(-1);
}
}
}
// checkLocale //
private static void checkLocale ()
{
final String localeStr = constants.locale.getValue()
.trim();
if (!localeStr.isEmpty()) {
for (Locale locale : Locale.getAvailableLocales()) {
if (locale.toString()
.equalsIgnoreCase(localeStr)) {
Locale.setDefault(locale);
if (logger.isFineEnabled()) {
logger.fine("Locale set to " + locale);
}
return;
}
}
logger.warning("Cannot set locale to " + localeStr);
}
}
// initialize //
private static void initialize ()
{
if (logger.isFineEnabled()) {
logger.fine("homeFolder=" + HOME_FOLDER);
logger.fine("classContainer=" + CLASS_CONTAINER);
logger.fine(
"classContainer.isDirectory=" + CLASS_CONTAINER.isDirectory());
}
// Tool name
final Package thisPackage = Main.class.getPackage();
toolName = thisPackage.getSpecificationTitle();
// Tool version
toolVersion = thisPackage.getSpecificationVersion();
// Tool build
toolBuild = thisPackage.getImplementationVersion();
}
// process //
private static void process (String[] args)
{
// First get the provided arguments if any
parameters = new CLI(toolName, args).getParameters();
if (parameters == null) {
logger.warning("Exiting ...");
// Stop the JVM, with failure status (1)
Runtime.getRuntime()
.exit(1);
}
// Interactive or Batch mode ?
if (parameters.batchMode) {
logger.info("Running in batch mode");
///System.setProperty("java.awt.headless", "true");
// Check MIDI output is not asked for
Step midiStep = Steps.valueOf(Steps.MIDI);
if ((midiStep != null) &&
parameters.desiredSteps.contains(midiStep)) {
logger.warning(
"MIDI output is not compatible with -batch mode." +
" MIDI output is ignored.");
parameters.desiredSteps.remove(midiStep);
}
} else {
logger.fine("Running in interactive mode");
// Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
}
}
// Constants //
private static final class Constants
extends ConstantSet
{
/** Selection of locale, or empty */
private final Constant.String locale = new Constant.String(
"en",
"Locale language to be used in the whole application (en, fr)");
/** "Should we persist CLI-defined options when running in batch? */
private final Constant.Boolean persistBatchCliConstants = new Constant.Boolean(
false,
"Should we persist CLI-defined constants when running in batch?");
/** Process time-out, specified in seconds */
private final Constant.Integer processTimeOut = new Constant.Integer(
"Seconds",
300,
"Process time-out, specified in seconds");
}
}
|
import java.lang.Exception;
import java.lang.IllegalArgumentException;
import java.util.List;
public class AssassinManager{
private AssassinNode first;
private AssassinNode current;
private AssassinNode nextOne;
private AssassinNode firstKilled;
private AssassinNode killed;
//Contructors
public AssassinManager(){
super();
}
public AssassinManager(List<String> names){
if (names != null && names.size() != 0){
for(int i = names.size()-1;i>=0;i
if(i == names.size()-1){
current = new AssassinNode(names.get(i));
nextOne = current;
}else{
current = new AssassinNode(names.get(i),nextOne);
nextOne = current;
if(i == 0){
first = current;
AssassinNode c2 = first;
AssassinNode c3 = null;
while(c2.next != null){
c3 = c2;
c2 = c2.next;
c2.killer = c3.name;
}
c2.killer = first.name;
first.killer = c2.name;
}
}
}
}else{
throw new IllegalArgumentException();
}
}
public void printKillRing(){
AssassinNode current = first;
while(current.next != null){
System.out.println(current.name+" is stalking "+current.next.name);
current = current.next;
}
System.out.println(current.name+" is stalking "+first.name);
}
public void printGraveyard(){
AssassinNode killed = firstKilled;
if(killed!=null){
System.out.println(killed.name+" was killed by "+killed.killer);
while(killed.next != null){
killed = killed.next;
System.out.println(killed.name+" was killed by "+killed.killer);
}
}
}
public boolean killRingContains(String name){
AssassinNode current = first;
boolean mark = false;
while (current.next != null){
if(name.toUpperCase().equals(current.name.toUpperCase())){
mark = true;
break;
}
current = current.next;
}
if(name.toUpperCase().equals(current.name.toUpperCase())) mark = true;
return mark;
}
public boolean graveyardContains(String name){
AssassinNode killed = firstKilled;
boolean mark = false;
if(killed != null){
while (killed.next != null){
if(name.toUpperCase().equals(killed.name.toUpperCase())){
mark = true;
break;
}
killed = killed.next;
}
if(name.toUpperCase().equals(killed.name.toUpperCase())) mark = true;
}
return mark;
}
public boolean isGameOver(){
boolean mark = false;
if (first.next == null){
mark = true;
}
return mark;
}
public String winner(){
return first.name;
}
public void kill(String name){
AssassinNode current = first;
String uName = name.toUpperCase();
String uCurrentName = first.name.toUpperCase() ;
if(uName.equals(uCurrentName)){
killed = new AssassinNode(current.name);
killed.killer = current.killer;
first = current.next;
if(firstKilled != null){
isFirstKilled(firstKilled,killed);
}else{
firstKilled = killed;
}
}
while (current.next != null){
nextOne = current;
current = current.next;
uCurrentName = current.name.toUpperCase();
if(uName.equals(uCurrentName)){
killed = new AssassinNode(current.name);
killed.killer = current.killer;
if(firstKilled != null){
isFirstKilled(firstKilled,killed);
}else{
firstKilled = killed;
}
nextOne.next = current.next;
}
}
uCurrentName = current.name.toUpperCase();
if(uName.equals(uCurrentName)){
first.killer = nextOne.name;
}
}
private void isFirstKilled(AssassinNode first,AssassinNode killed){
if(first.next == null){
first.next = killed;
}else{
isFirstKilled(first.next,killed);
}
}
}
|
package main.java;
import main.java.UnitConversion.Unit;
import main.java.UnitConversion.UnitConverter;
public class Item {
private Unit unit;
private String displayName;
private String itemName;
private double price;
public Item(String itemName, double quantity, String unit) {
this.displayName = itemName;
this.itemName = itemName;
this.unit = UnitConverter.getUnitFromString(unit, quantity);
this.price = 0.0;
}
public Item(String itemName, double quantity, String unit, double price) {
this.displayName = itemName;
this.itemName = itemName;
this.unit = UnitConverter.getUnitFromString(unit, quantity);
this.price = price;
}
public String getItemName() {
return this.itemName;
}
public void updateDisplayName(String displayName) {
this.displayName = displayName;
}
public Unit getUnit() {
return this.unit;
}
public void updateCurrentItem(Item item2) {
UnitConverter.convertToExistingUnit(this.getUnit(), item2.getUnit());
}
public String toString() {
if(this.unit.getQuantity() != 0.0) {
return (new DoubleToFraction(unit.getQuantity()).toString() + " " + unit.getName() + " -- " + displayName + " -- ") + ((price == 0.0) ? "Price Unavailable" : ("$" + String.valueOf(price)));
}
else {
return (displayName + " -- ") + ((price == 0.0) ? "Price Unavailable" : ("$" + String.valueOf(price)));
}
}
public static Item[] toItemArray(String[] recipe) {
Item[] result = new Item[recipe.length-1];
for(int x = 1; x<recipe.length; x++) {
String[] arrayStr = recipe[x].split(" ");
String itemName = "";
String itemUnit = "";
double itemQuantity = 0.0;
for(int i=0; i<arrayStr.length; i++) {
if(arrayStr[i].substring(0,1).equals("-")) {
arrayStr[i] = arrayStr[i].substring(1);
}
if(i == 0) {
if(isDouble(arrayStr[i])) {
itemQuantity = Double.parseDouble(arrayStr[i]);
System.out.println("Item Quantity: " + String.valueOf(itemQuantity));
continue;
}
else {
itemName = addArrToString(arrayStr);
break;
}
}
if(i == 1) {
itemUnit = arrayStr[i];
System.out.println("Unit Type: " + itemUnit);
continue;
}
if(i == 2) {
if(instanceOfUnitName(arrayStr[i].toLowerCase()) && isDouble(arrayStr[i-1])) {
itemUnit = arrayStr[i];
System.out.println("Unit Type: " + itemUnit);
itemQuantity = Double.parseDouble(arrayStr[i-1]);
System.out.println("Item Quantity: " + String.valueOf(itemQuantity));
continue;
}
itemName = arrayStr[i];
continue;
}
itemName = itemName + " " + arrayStr[i];
}
result[x-1] = new Item(itemName, itemQuantity, itemUnit);
}
return result;
}
private static boolean instanceOfUnitName(String unitName) {
switch(unitName) {
case "teaspoon": return true;
case "teaspoons": return true;
case "tablespoon": return true;
case "tablespoons": return true;
case "cups": return true;
case "ounce": return true;
case "ounces": return true;
case "drops": return true;
case "pound": return true;
case "pounds": return true;
case "gallon": return true;
case "gallons": return true;
case "fluid ounce": return true;
case "fluid ounces": return true;
case "fl. oz.": return true;
case "fl. oz": return true;
case "pint": return true;
case "pints": return true;
case "quart": return true;
case "quarts": return true;
case "sticks": return true;
}
return false;
}
private static String addArrToString(String[] arrayStr) {
String result = arrayStr[0];
for(int i=1; i<arrayStr.length; i++) {
result = result + " " + arrayStr[i];
}
return result;
}
private static boolean isDouble(String str) {
try {
Double.parseDouble(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
import org.bytedeco.javacpp.opencv_core;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static org.bytedeco.javacpp.opencv_imgcodecs.*;
public class Main {
public static void main(String[] args){
if(args.length > 0 && args[0] != null){
opencv_core.IplImage img = cvLoadImage(args[0]);
if (img != null) {
int width = img.width();
int height = img.height();
int pixelSize = 4;
if (args.length > 1) {
int ps = Integer.parseInt(args[1]);
if(ps > 0) {
pixelSize = ps;
}
}
List<String> pixels = new ArrayList<String>();
String firstPixel = "#000000";
for (int i = 0; i < width; i += pixelSize) {
for (int j = 0; j < height; j += pixelSize) {
opencv_core.CvScalar scalar = opencv_core.cvGet2D(img, j, i);
if(i == 0 && j == 0){
firstPixel = String.format(Locale.getDefault(), "#%02X%02X%02X",
(int) scalar.val(2), (int) scalar.val(1), (int) scalar.val(0));
}
String pixel = String.format("%dpx %dpx #%02X%02X%02X",
i, j, (int) scalar.val(2), (int) scalar.val(1), (int) scalar.val(0));
pixels.add(pixel);
}
}
img.release();
@SuppressWarnings("Since15") String css = String.format(Locale.getDefault(),
"<style>\n#pixel{\n\twidth:%dpx;\n\theight:%dpx;\n\t}\n#pixel:after{\n\tcontent:'';\n\tdisplay:block;\n\twidth:%dpx;\n\theight:%dpx;\n\tbackground:%s;\n\tbox-shadow:%s;\n}\n</style><div id=\"pixel\"></div>",
width, height, pixelSize, pixelSize, firstPixel, String.join(",\n\t", pixels));
System.out.println(css);
}
else{
System.err.println("Can't open file " + args[0]);
}
}
else{
System.err.println("img2pixel needs at least one argument which is the source image path");
}
}
}
|
import mm.display.MainWindow;
import mm.graph.SendInfinite;
import mm.graph.SocketServer;
import mm.structures.ColorField;
import mm.structures.ColorPixel;
import java.awt.*;
import java.util.Random;
public class Main {
public static void main(String[] args) throws InterruptedException {
int port = 8887;
SocketServer ws = new SocketServer(port);
ws.start();
final int N = 50;
final double FIELD_SIZE = N * N * 1.0;
final Random random = new Random("VojnaBarv".hashCode());
ColorPixel[] colors = new ColorPixel[]{
new ColorPixel(new Color(124, 7, 142), 0.3),
new ColorPixel(new Color(236, 74, 72), 0.05),
new ColorPixel(new Color(255, 252, 88), 0.05),
new ColorPixel(new Color(31, 162, 209), 0.1),
new ColorPixel(new Color(128, 207, 12), 0.1),
new ColorPixel(new Color(71, 34, 69), 0.05),
new ColorPixel(new Color(1, 153, 138), 0.125),
new ColorPixel(new Color(206, 23, 54), 0.075),
new ColorPixel(new Color(247, 88, 48), 0.05),
new ColorPixel(new Color(12, 8, 65), 0.1)
};
ColorPixel.setCodes(colors);
ColorField initialCf = ColorField.GenerateField(N, colors, random);
ColorField cf = initialCf;
MainWindow window = new MainWindow(cf);
String colorsJSON = String.format("{\"message\": \"init\", \"colors\": %s, \"p\": %s}",
ColorPixel.colorsAsJSONArray(cf.getColors()),
ColorPixel.getProbabilitesJSON(cf.getColors()));
System.out.println("send: " + colorsJSON);
new Thread(new SendInfinite(ws, colorsJSON)).start();
long ss = System.nanoTime();
for (int i = 0; i < 10000; i++) {
long allStart = System.nanoTime();
int iterations = 0;
while (!cf.isAllSame()) {
cf = cf.updateNeighbours();
window.updateField(cf);
if (iterations % 5 == 0) {
ws.sendToAll(ColorPixel.colorsCountAsJSONArray(cf.getColors(), iterations, FIELD_SIZE));
}
iterations++;
Thread.sleep(16);
}
System.out.printf("St iteracij: %,d\n", iterations);
System.out.printf("Celoten cas: %.3fs\n", (System.nanoTime() - allStart) / 1e9);
Thread.sleep(2000);
cf = initialCf;
}
System.out.printf("end: %.3fs\n", (System.nanoTime() - ss) / 1e9);
}
}
|
import java.sql.*;
import java.util.Date;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.eclipse.persistence.tools.file.FileUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import static spark.Spark.*;
import spark.template.freemarker.FreeMarkerEngine;
import spark.ModelAndView;
import spark.Session;
import static spark.Spark.get;
import com.heroku.sdk.jdbc.DatabaseUrl;
import de.fussballmanager.db.jpa.EmFactory;
public class Main {
public static void main(String[] args) {
port(Integer.valueOf(System.getenv("PORT")));
staticFileLocation("/public");
get("/intern/hello", (req, res) -> "Intern Hello World");
get("/hello", (req, res) -> "Hello World");
post("/loginaction",
(request, response) -> {
String body = request.body();
if (body == null || body.isEmpty()) {
throw new RuntimeException("body is null or empty");
}
String name = "?";
try {
JSONArray bodyJson = new JSONArray(body);
for (int i = 0; i < bodyJson.length(); i++) {
JSONObject tempSubmit = bodyJson.getJSONObject(i);
if (tempSubmit.has("name")
&& tempSubmit.getString("name") != null) {
name = tempSubmit.getString("name");
}
}
} catch (Exception e) {
throw new RuntimeException(
"JSON could not be interpreted.", e);
}
Map<String, Object> attributes = new HashMap<>();
attributes.put("url", "hello");
return new ModelAndView(attributes, "redirect.ftl");
}, new FreeMarkerEngine());
get("/", (request, response) -> {
Map<String, Object> attributes = new HashMap<>();
attributes.put("message", "Hello World!");
request.session(true);
return new ModelAndView(attributes, "login.ftl");
}, new FreeMarkerEngine());
exception(RuntimeException.class, (e, request, response) -> {
response.status(500);
response.body("Ein Fehler ist aufgetreten. ");
});
get("/file", (req, res) -> {
Map<String, Object> attributes = new HashMap<>();
try {
File createTempFile = File.createTempFile("comunio", "");
String path = createTempFile.getAbsolutePath();
String fileName = path + "/../cache/" ;
File tempFile = new File(fileName);
tempFile = new File(tempFile.getCanonicalPath());
tempFile.mkdir();
tempFile = new File(tempFile.getCanonicalPath() + "/test.data");
tempFile.setWritable(Boolean.TRUE);
tempFile.createNewFile();
FileUtils.writeByteArrayToFile(tempFile, new Date().toString().getBytes(), true);
String readFileToString = FileUtils.readFileToString(tempFile);
List<String> resultList = new ArrayList<String>();
resultList.add(readFileToString);
attributes.put("results", resultList );
return new ModelAndView(attributes, "db.ftl");
} catch (Exception e) {
e.printStackTrace();
attributes.put("message", "There was an error: " + e);
return new ModelAndView(attributes, "error.ftl");
} finally {
}
}, new FreeMarkerEngine());
get("/db",
(req, res) -> {
Map<String, Object> attributes = new HashMap<>();
try {
EntityManager em = EmFactory.getEntityManager();
em.getTransaction().begin();
Query createQuery = em
.createNativeQuery("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)");
createQuery.executeUpdate();
Query insertQuery = em
.createNativeQuery("INSERT INTO ticks VALUES (now())");
insertQuery.executeUpdate();
Query selectQuery = em
.createNativeQuery("SELECT tick FROM ticks");
List resultList = selectQuery.getResultList();
em.getTransaction().commit();
attributes.put("results", resultList);
return new ModelAndView(attributes, "db.ftl");
} catch (Exception e) {
attributes.put("message", "There was an error: " + e);
return new ModelAndView(attributes, "error.ftl");
} finally {
}
}, new FreeMarkerEngine());
}
}
|
import static spark.Spark.*;
import spark.ModelAndView;
import spark.template.freemarker.FreeMarkerEngine;
import java.sql.*;
import java.util.*;
import com.google.gson.Gson;
import com.heroku.sdk.jdbc.DatabaseUrl;
import skinstore.item.service.*;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class Main {
public static void main(String[] args) {
port(Integer.valueOf(System.getenv("PORT")));
staticFileLocation("/public");
//this is new added
//new UserController(new UserService());
/*get("/", (request, response) -> {
Map<String, Object> attributes = new HashMap<>();
attributes.put("message", "Hello World!");
return new ModelAndView(attributes, "index.ftl");
}, new FreeMarkerEngine());*/
get("/db", (req, res) -> {
Connection connection = null;
Map<String, Object> attributes = new HashMap<>();
try {
connection = DatabaseUrl.extract().getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)");
stmt.executeUpdate("INSERT INTO ticks VALUES (now())");
ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");
ArrayList<String> output = new ArrayList<String>();
while (rs.next()) {
output.add( "Read from DB: " + rs.getTimestamp("tick"));
}
attributes.put("results", output);
return new ModelAndView(attributes, "db.ftl");
} catch (Exception e) {
attributes.put("message", "There was an error: " + e);
return new ModelAndView(attributes, "error.ftl");
} finally {
if (connection != null) try{connection.close();} catch(SQLException e){}
}
}, new FreeMarkerEngine());
// get("/insertItems", (req, res) -> {
// Connection connection = null;
// Map<String, Object> attributes = new HashMap<>();
// try {
// connection = DatabaseUrl.extract().getConnection();
// Statement stmt = connection.createStatement();
// // stmt.executeUpdate("CREATE TABLE IF NOT EXISTS items (itemID int, itemName varchar(100), itemBrand varchar(100), itemCategory varchar(100), itemDescription varchar(200), itemColor varchar(50), itemRating float, itemStock int, itemGender varchar(20), itemSize float)");
// stmt.executeUpdate("INSERT INTO products VALUES (3, 62, 'Diorskin Forever Flawless Wear Makeup', 'Dior', 'Foundation', 'A couture inspire liquid foundation', 'Ivory', 3000, 25, 'Female', 1.0,'images/0003.jpg')");
// stmt.executeUpdate("INSERT INTO products VALUES (4, 35, 'Lock it Foundation', 'Kat Von D', 'Foundation', 'A high pigment foundation for full coverage', 'Ivory', 1500, 10, 'Female', 1.0, 'images/0004.jpg')");
// stmt.executeUpdate("INSERT INTO products VALUES (5, 43, 'Ultra HD Invisible Cover Foundation', 'Make Up For Ever', 'Foundation', 'A bestselling HD foundation', 'Ivory', 3500, 25, 'Female', 1.0,'images/0005.jpg')");
// stmt.executeUpdate("INSERT INTO products VALUES (6, 38, 'Double Wear Stay in Foundation', 'Estee Lauder', 'Foundation', 'A 15 hour flawless foundation', 'Deep', 1500, 10, 'Female', 1.0, 'images/0006.jpg')");
// ResultSet rs = stmt.executeQuery("SELECT * FROM products");
// ArrayList<String> output = new ArrayList<String>();
// while (rs.next()) {
// output.add( "Read from DB the name is : " + rs.getString("itemBrand"));
// attributes.put("results", output);
// return new ModelAndView(attributes, "db.ftl");
// } catch (Exception e) {
// attributes.put("message", "There was an error: " + e);
// return new ModelAndView(attributes, "error.ftl");
// } finally {
// if (connection != null) try{connection.close();} catch(SQLException e){}
// }, new FreeMarkerEngine());
get("/skinstore/getItems", (req, res) -> {
Connection connection = null;
Map<String, Object> attributes = new HashMap<>();
try {
connection = DatabaseUrl.extract().getConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM products");
ArrayList<String> output = new ArrayList<String>();
while (rs.next()) {
output.add( "Read from DB the name is : " + rs.getString("itemBrand"));
}
attributes.put("results", output);
return new ModelAndView(attributes, "db.ftl");
} catch (Exception e) {
attributes.put("message", "There was an error: " + e);
return new ModelAndView(attributes, "error.ftl");
} finally {
if (connection != null) try{connection.close();} catch(SQLException e){}
}
}, new FreeMarkerEngine());
}
}
|
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.*;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.twilio.sdk.verbs.TwiMLResponse;
import com.twilio.sdk.verbs.TwiMLException;
import com.twilio.sdk.verbs.Message;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Main extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (req.getRequestURI().endsWith("/db")) {
showDatabase(req,resp);
} else {
showHome(req,resp);
}
}
private void showHome(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().print("Hello from Java!");
}
private void showDatabase(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Connection connection = null;
try {
connection = getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)");
stmt.executeUpdate("INSERT INTO ticks VALUES (now())");
ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");
String out = "Hello!\n";
while (rs.next()) {
out += "Read from DB: " + rs.getTimestamp("tick") + "\n";
}
resp.getWriter().print(out);
} catch (Exception e) {
resp.getWriter().print("There was an error: " + e.getMessage());
} finally {
if (connection != null) try{connection.close();} catch(SQLException e){}
}
}
private Connection getConnection() throws URISyntaxException, SQLException {
URI dbUri = new URI(System.getenv("DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
int port = dbUri.getPort();
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ":" + port + dbUri.getPath();
return DriverManager.getConnection(dbUrl, username, password);
}
// service() responds to both GET and POST requests.
// You can also use doGet() or doPost()
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
String msg = request.getParameter("Body");
msg = msg.toLowerCase();
System.out.println("-->" + msg);
String cmd = msg.split(" ")[0];
msg = msg.substring(msg.indexOf(' ')+1);
String result = "";
if (cmd.equals("usage")) {
System.out.println("usage");
result = "Twilio Movie Assistant Usage Guide:"
+ "\nlist: Returns a list of movies available"
+ "\nshow <movie_num>: Returns the movie's showtimes"
+ "\nreview <movie_num>: Returns the movie's synopsis";
} else if (cmd.equals("list")) {
System.out.println("list");
Document doc;
try {
doc = Jsoup.connect("http:
Elements titles = doc.select(".info > h3 > span > a");
System.out.println(titles.size());
for (int i = 1; i <= titles.size(); i++) {
String title = titles.get(i-1).text().split("\\(")[0];
title = title.substring(0, title.length()-1);
result += "\n" + i + "-" + title;
}
} catch (IOException e) {
e.printStackTrace();
}
} else if (cmd.equals("show")){
System.out.println("showtimes");
Document doc;
try {
doc = Jsoup.connect("http:
Elements titles = doc.select(".info > h3 > span > a");
Elements showtimes = doc.getElementsByClass("showtimes");
System.out.println(showtimes.size() + " , " + titles.size());
for (int i = 0; i < titles.size(); i++) {
String title = titles.get(i).text().toLowerCase().split("\\(")[0];
title = title.substring(0, title.length()-1);
if ((""+(i+1)).equals(msg)) {
result = (titles.get(i).text() + " : " + showtimes.get(i).text());
}
}
} catch (IOException e) {
e.printStackTrace();
}
} else if (cmd.equals("review")) {
Document doc;
HttpURLConnection con;
try {
doc = Jsoup.connect("http:
Elements titles = doc.select(".info > h3 > span > a");
System.out.println(titles.size());
String title = "";
for (int i = 0; i < titles.size(); i++) {
title = titles.get(i).text().split("\\(")[0];
title = title.substring(0, title.length()-1);
if ((""+i).equals(msg)) {
result = title;
break;
}
}
result = result.replace(' ', '+');
String url = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=" + title + "&page_limit=10&page=1&apikey=69dxhndmtkxf7f8m8bertygz";
URL obj = new URL(url);
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer buf = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
buf.append(inputLine);
}
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(buf.toString());
JSONArray jsonArray = ((JSONArray)json.get("movies"));
JSONObject movie1 = (JSONObject)jsonArray.get(0);
result = (String)movie1.get("synopsis");
in.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
}
}
if (result.equals("")) {
result = "Cannot complete command: " + msg;
}
Message message = new Message(result);
TwiMLResponse twiml = new TwiMLResponse();
try {
twiml.append(message);
} catch (TwiMLException e) {
e.printStackTrace();
}
response.setContentType("application/xml");
response.getWriter().print(twiml.toXML());
}
public static void main(String[] args) throws Exception {
Server server = new Server(Integer.valueOf(System.getenv("PORT")));
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
|
package openmods;
import java.util.Map;
import java.util.Map.Entry;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.GameRegistry.UniqueIdentifier;
public class Mods {
public static final String APPLIEDENERGISTICS = "AppliedEnergistics";
public static final String ARSMAGICA2 = "arsmagica2";
public static final String BIBLIOCRAFT = "BiblioCraft";
public static final String BILLUND = "Billund";
public static final String BIOMESOPLENTY = "BiomesOPlenty";
public static final String BUILDCRAFT = "BuildCraft|Core";
public static final String BUILDCRAFT_BUILDERS = "BuildCraft|Builders";
public static final String BUILDCRAFT_CORE = "BuildCraft|Core";
public static final String BUILDCRAFT_ENERGY = "BuildCraft|Energy";
public static final String BUILDCRAFT_FACTORY = "BuildCraft|Factory";
public static final String BUILDCRAFT_SILICON = "BuildCraft|Factory";
public static final String BUILDCRAFT_TRANSPORT = "BuildCraft|Transport";
public static final String CHICKENCHUNKS = "ChickenChunks";
public static final String COMPUTERCRAFT = "ComputerCraft";
public static final String COMPUTERCRAFT_TURTLE = "CCTurtle";
public static final String ENDERSTORAGE = "EnderStorage";
public static final String EXTRABEES = "ExtraBees";
public static final String EXTRATREES = "ExtraTrees";
public static final String EXTRAUTILITIES = "ExtraUtilities";
public static final String FORESTRY = "Forestry";
public static final String GRAVITYGUN = "GraviGun";
public static final String HATSTAND = "HatStand";
public static final String IC2 = "IC2";
public static final String MAGICBEES = "MagicBees";
public static final String MPS = "powersuits";
public static final String MYSTCRAFT = "Mystcraft";
public static final String OPENBLOCKS = "OpenBlocks";
public static final String OPENPERIPHERAL = "OpenPeripheral";
public static final String PORTALGUN = "PortalGun";
public static final String PROJECTRED_TRANSMISSION = "ProjRed|Transmission";
public static final String RAILCRAFT = "Railcraft";
public static final String SGCRAFT = "SGCraft";
public static final String STEVESCARTS = "StevesCarts";
public static final String TINKERSCONSTRUCT = "TConstruct";
public static final String THAUMCRAFT = "Thaumcraft";
public static final String THERMALEXPANSION = "ThermalExpansion";
public static final String TRANSLOCATOR = "Translocator";
public static final String WIRELESSREDSTONECBE = "WR-CBE|Core";
public static ModContainer getModForItemStack(ItemStack stack) {
Item item = stack.getItem();
if (item == null)
return null;
Class<?> klazz = item.getClass();
if (klazz.getName().startsWith("net.minecraft"))
return null;
UniqueIdentifier identifier = GameRegistry.findUniqueIdentifierFor(item);
if (identifier == null && item instanceof ItemBlock) {
int blockId = ((ItemBlock)item).getBlockID();
Block block = Block.blocksList[blockId];
if (block != null) {
identifier = GameRegistry.findUniqueIdentifierFor(block);
klazz = block.getClass();
}
}
Map<String, ModContainer> modList = Loader.instance().getIndexedModList();
if (identifier != null) {
ModContainer container = modList.get(identifier.modId);
if (container != null)
return container;
}
String[] itemClassParts = klazz.getName().split("\\.");
ModContainer closestMatch = null;
int mostMatchingPackages = 0;
for (Entry<String, ModContainer> entry : modList.entrySet()) {
Object mod = entry.getValue().getMod();
if (mod == null)
continue;
String[] modClassParts = mod.getClass().getName().split("\\.");
int packageMatches = 0;
for (int i = 0; i < modClassParts.length; ++i) {
if (i < itemClassParts.length && itemClassParts[i] != null
&& itemClassParts[i].equals(modClassParts[i])) {
++packageMatches;
} else {
break;
}
}
if (packageMatches > mostMatchingPackages) {
mostMatchingPackages = packageMatches;
closestMatch = entry.getValue();
}
}
return closestMatch;
}
}
|
package sopc2dts.generators;
import java.util.Vector;
import sopc2dts.Logger;
import sopc2dts.Logger.LogLevel;
import sopc2dts.lib.AvalonSystem;
import sopc2dts.lib.AvalonSystem.SystemDataType;
import sopc2dts.lib.BoardInfo;
import sopc2dts.lib.Connection;
import sopc2dts.lib.BoardInfo.PovType;
import sopc2dts.lib.components.BasicComponent;
import sopc2dts.lib.components.Interface;
import sopc2dts.lib.components.MemoryBlock;
import sopc2dts.lib.devicetree.DTNode;
import sopc2dts.lib.devicetree.DTPropBool;
import sopc2dts.lib.devicetree.DTPropHexNumber;
import sopc2dts.lib.devicetree.DTPropNumber;
import sopc2dts.lib.devicetree.DTPropString;
public abstract class DTGenerator extends AbstractSopcGenerator {
Vector<BasicComponent> vHandled;
public DTGenerator(AvalonSystem s, boolean isText) {
super(s, isText);
}
protected synchronized DTNode getDTOutput(BoardInfo bi)
{
vHandled = new Vector<BasicComponent>();
DTNode rootNode = new DTNode("/");
BasicComponent povComponent = getPovComponent(bi);
DTNode sopcNode;
DTNode chosenNode;
if(povComponent!=null)
{
if(bi.getPovType().equals(PovType.CPU))
{
DTNode cpuNode = getCpuNodes(bi);
DTNode memNode = getMemoryNode(bi, povComponent);
sopcNode = new DTNode("sopc@0");
chosenNode = getChosenNode(bi);
DTPropString dtps = new DTPropString("model","ALTR," + sys.getSystemName());
rootNode.addProperty(dtps);
dtps = new DTPropString("compatible","ALTR," + sys.getSystemName());
rootNode.addProperty(dtps);
rootNode.addChild(cpuNode);
rootNode.addChild(memNode);
sopcNode.addProperty(new DTPropString("device_type", "soc"));
} else {
sopcNode = rootNode;
chosenNode = null;
}
DTPropNumber dtpn = new DTPropNumber("#address-cells",1L);
rootNode.addProperty(dtpn);
dtpn = new DTPropNumber("#size-cells",1L);
rootNode.addProperty(dtpn);
sopcNode = getSlavesFor(bi, povComponent, sopcNode);
sopcNode.addProperty(new DTPropBool("ranges"));
sopcNode.addProperty(new DTPropNumber("#address-cells",1L));
sopcNode.addProperty(new DTPropNumber("#size-cells",1L));
Vector<String> vCompat = new Vector<String>();
vCompat.add("ALTR,avalon");
vCompat.add("simple-bus");
sopcNode.addProperty(new DTPropString("compatible", vCompat));
sopcNode.addProperty(new DTPropNumber("bus-frequency", povComponent.getClockRate()));
if(bi.getPovType().equals(PovType.CPU))
{
rootNode.addChild(sopcNode);
rootNode.addChild(chosenNode);
}
}
return rootNode;
}
DTNode getChosenNode(BoardInfo bi)
{
DTNode chosenNode = new DTNode("chosen");
if((bi.getBootArgs()==null)||(bi.getBootArgs().length()==0))
{
bi.setBootArgs("debug console=ttyAL0,115200");
} else {
bi.setBootArgs(bi.getBootArgs().replaceAll("\"", ""));
}
chosenNode.addProperty(new DTPropString("bootargs", bi.getBootArgs()));
return chosenNode;
}
DTNode getCpuNodes(BoardInfo bi)
{
int numCPUs = 0;
DTNode cpuNode = new DTNode("cpus");
if(bi.getPovType() == PovType.CPU)
{
cpuNode.addProperty(new DTPropNumber("#address-cells",1L));
cpuNode.addProperty(new DTPropNumber("#size-cells",0L));
for(BasicComponent comp : sys.getSystemComponents())
{
if(comp.getScd().getGroup().equalsIgnoreCase("cpu"))
{
if(bi.getPov()==null) {
bi.setPov(comp.getInstanceName());
}
comp.setAddr(numCPUs);
cpuNode.addChild(comp.toDTNode(bi, null));
vHandled.add(comp);
numCPUs++;
}
}
}
if(cpuNode.getChildren().isEmpty())
{
cpuNode = null;
}
return cpuNode;
}
DTNode getMemoryNode(BoardInfo bi, BasicComponent master)
{
DTNode memNode = new DTNode("memory@0");
DTPropHexNumber dtpReg = new DTPropHexNumber("reg");
dtpReg.getValues().clear();
memNode.addProperty(new DTPropString("device_type", "memory"));
memNode.addProperty(dtpReg);
if(master!=null)
{
Vector<String> vMemoryMapped = bi.getMemoryNodes();
if(vMemoryMapped!=null)
{
for(Interface intf : master.getInterfaces())
{
if(intf.isMemoryMaster())
{
for(MemoryBlock mem : intf.getMemoryMap())
{
if(vMemoryMapped.contains(mem.getModule().getInstanceName()))
{
BasicComponent comp = mem.getModule();
if((comp!=null)&&(!vHandled.contains(comp)))
{
dtpReg.addValue(mem.getBase());
dtpReg.addValue(mem.getSize());
vHandled.add(comp);
}
}
}
}
}
}
if(dtpReg.getValues().size()==0)
{
Logger.logln("dts memory section: No memory nodes specified. " +
"Blindly adding them all", LogLevel.INFO);
/*
* manual memory-map failed or is not present.
* Just list all devices classified as "memory"
*/
vMemoryMapped = new Vector<String>();
for(Interface intf : master.getInterfaces())
{
if(intf.isMemoryMaster())
{
for(MemoryBlock mem : intf.getMemoryMap())
{
if(!vMemoryMapped.contains(mem.getModuleName()))
{
BasicComponent comp = mem.getModule();
if(comp!=null)
{
if(comp.getScd().getGroup().equalsIgnoreCase("memory"))
{
dtpReg.addValue(mem.getBase());
dtpReg.addValue(mem.getSize());
vMemoryMapped.add(mem.getModuleName());
vHandled.add(comp);
}
}
}
}
}
}
}
}
if(dtpReg.getValues().size()==0) {
return null;
} else {
return memNode;
}
}
DTNode getSlavesFor(BoardInfo bi, BasicComponent masterComp, DTNode masterNode)
{
if(masterComp!=null)
{
Vector<Connection> vSlaveConn = masterComp.getConnections(SystemDataType.MEMORY_MAPPED, true);
for(Connection conn : vSlaveConn)
{
BasicComponent slave = conn.getSlaveModule();
if((slave!=null)&&(!vHandled.contains(slave)))
{
vHandled.add(slave);
if(slave.getScd().getGroup().equals("bridge"))
{
DTNode bridgeNode = getSlavesFor(bi, slave, slave.toDTNode(bi, conn));
//Don't add empty bridges...
if(!bridgeNode.getChildren().isEmpty())
{
masterNode.addChild(bridgeNode);
}
} else {
masterNode.addChild(slave.toDTNode(bi, conn));
}
}
}
}
return masterNode;
}
}
|
package org.jasig.portal.jndi;
import java.util.Hashtable;
import java.util.Enumeration;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.CompositeName;
import javax.servlet.http.HttpSession;
import org.jasig.portal.security.IPerson;
import org.jasig.portal.services.LogService;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
/**
* JNDIManager
* @author Bernie Durfee, bdurfee@interactivebusiness.com
* @version $Revision$
*/
public class JNDIManager
{
public JNDIManager()
{
}
public static void initializePortalContext()
{
try
{
Context context = getContext();
// Create a subcontext for portal-wide services
context.createSubcontext("services");
// Bind in the logger service
LogService logger = LogService.instance();
context.bind("/services/logger", logger);
// Create a subcontext for user specific bindings
context.createSubcontext("users");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void initializeUserContext(Document userLayout, String sessionID, IPerson person)
throws PortalNamingException
{
try
{
// Throw an exception if the person object is not found
if(person == null)
{
throw new PortalNamingException("JNDIManager.initializeUserContext() - Cannot find person object!");
}
// Throw an exception if the user's layout cannot be found
if(userLayout == null)
{
throw new PortalNamingException("JNDIManager.initializeUserContext() - Cannot find user's layout!");
}
// Get the portal wide context
Context context = getContext();
// Get the list of channels in the user's layout
NodeList channelNodes = userLayout.getElementsByTagName("channel");
Node fname = null;
Node instanceid = null;
// Parse through the channels and populate the JNDI
for(int i = 0; i < channelNodes.getLength(); i++)
{
fname = channelNodes.item(i).getAttributes().getNamedItem("fname");
instanceid = channelNodes.item(i).getAttributes().getNamedItem("ID");
if(fname != null && instanceid != null)
{
// Create a new composite name from the fname
CompositeName cname = new CompositeName(fname.getNodeValue());
// Get a list of the name components
Enumeration e = cname.getAll();
// Get the root of the context
Context nextContext = (Context)context.lookup("");
// Add all of the subcontexts in the fname
while(e.hasMoreElements())
{
nextContext = nextContext.createSubcontext((String)e.nextElement());
}
// Bind the instance ID of the channel as a leaf
nextContext.rebind(cname.get(cname.size() - 1), instanceid.getNodeValue());
}
}
}
catch(Exception ne)
{
throw new PortalNamingException(ne.getMessage());
}
}
private static Context getContext()
throws NamingException
{
Hashtable environment = new Hashtable(5);
// Set up the path
environment.put(Context.INITIAL_CONTEXT_FACTORY, "org.jasig.portal.jndi.PortalInitialContextFactory");
Context ctx = new InitialContext(environment);
return(ctx);
}
}
|
package org.jfree.data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.chart.util.SortOrder;
/**
* An ordered list of (key, value) items. This class provides a default
* implementation of the {@link KeyedValues} interface.
*/
public class DefaultKeyedValues implements KeyedValues,
Cloneable, PublicCloneable,
Serializable {
/** For serialization. */
private static final long serialVersionUID = 8468154364608194797L;
/** Storage for the data. */
private ArrayList keys;
private ArrayList values;
private HashMap keyToValueMapping;
/**
* Creates a new collection (initially empty).
*/
public DefaultKeyedValues() {
this.keys = new ArrayList();
this.values = new ArrayList();
this.keyToValueMapping = new HashMap();
}
/**
* Returns the number of items (values) in the collection.
*
* @return The item count.
*/
public int getItemCount() {
return this.keyToValueMapping.size();
}
/**
* Returns a value.
*
* @param item the item of interest (zero-based index).
*
* @return The value.
*
* @throws IndexOutOfBoundsException if <code>item</code> is out of bounds.
*/
public Number getValue(int item) {
return (Number) this.values.get(item);
}
/**
* Returns a key.
*
* @param index the item index (zero-based).
*
* @return The row key.
*
* @throws IndexOutOfBoundsException if <code>item</code> is out of bounds.
*/
public Comparable getKey(int index) {
return (Comparable) this.keys.get(index);
}
public int getIndex(Comparable key) {
if (key == null) {
throw new IllegalArgumentException("Null 'key' argument.");
}
final Integer i = (Integer) keyToValueMapping.get(key);
if (i == null)
{
return -1; // key not found
}
return i.intValue();
}
/**
* Returns the keys for the values in the collection.
*
* @return The keys (never <code>null</code>).
*/
public List getKeys() {
return (List) keys.clone();
}
/**
* Returns the value for a given key.
*
* @param key the key (<code>null</code> not permitted).
*
* @return The value (possibly <code>null</code>).
*
* @throws UnknownKeyException if the key is not recognised.
*
* @see #getValue(int)
*/
public Number getValue(Comparable key) {
int index = getIndex(key);
if (index < 0) {
throw new UnknownKeyException("Key not found: " + key);
}
return getValue(index);
}
/**
* Updates an existing value, or adds a new value to the collection.
*
* @param key the key (<code>null</code> not permitted).
* @param value the value.
*
* @see #addValue(Comparable, Number)
*/
public void addValue(Comparable key, double value) {
addValue(key, new Double(value));
}
/**
* Adds a new value to the collection, or updates an existing value.
* This method passes control directly to the
* {@link #setValue(Comparable, Number)} method.
*
* @param key the key (<code>null</code> not permitted).
* @param value the value (<code>null</code> permitted).
*/
public void addValue(Comparable key, Number value) {
setValue(key, value);
}
/**
* Updates an existing value, or adds a new value to the collection.
*
* @param key the key (<code>null</code> not permitted).
* @param value the value.
*/
public void setValue(Comparable key, double value) {
setValue(key, new Double(value));
}
/**
* Updates an existing value, or adds a new value to the collection.
*
* @param key the key (<code>null</code> not permitted).
* @param value the value (<code>null</code> permitted).
*/
public void setValue(Comparable key, Number value) {
if (key == null) {
throw new IllegalArgumentException("Null 'key' argument.");
}
int keyIndex = getIndex(key);
if (keyIndex >= 0) {
keys.set(keyIndex, key);
values.set(keyIndex, value);
}
else {
keys.add(key);
values.add(value);
keyToValueMapping.put(key, new Integer(keys.size() - 1));
}
}
/**
* Inserts a new value at the specified position in the dataset or, if
* there is an existing item with the specified key, updates the value
* for that item and moves it to the specified position.
*
* @param position the position (in the range 0 to getItemCount()).
* @param key the key (<code>null</code> not permitted).
* @param value the value.
*
* @since 1.0.6
*/
public void insertValue(int position, Comparable key, double value) {
insertValue(position, key, new Double(value));
}
/**
* Inserts a new value at the specified position in the dataset or, if
* there is an existing item with the specified key, updates the value
* for that item and moves it to the specified position.
*
* @param position the position (in the range 0 to getItemCount()).
* @param key the key (<code>null</code> not permitted).
* @param value the value (<code>null</code> permitted).
*
* @since 1.0.6
*/
public void insertValue(int position, Comparable key, Number value) {
if (position < 0 || position > getItemCount()) {
throw new IllegalArgumentException("'position' out of bounds.");
}
if (key == null) {
throw new IllegalArgumentException("Null 'key' argument.");
}
int pos = this.getIndex(key);
if (pos == position) {
this.keys.set(pos, key);
this.values.set(pos, value);
}
else {
if (pos >= 0) {
this.keys.remove(pos);
this.values.remove(pos);
}
this.keys.add(position, key);
this.values.add(position, value);
rebuildIndex();
}
}
/**
* Rebuilds the key to indexed-position mapping after an positioned insert
* or a remove operation.
*/
private void rebuildIndex () {
keyToValueMapping.clear();
for (int i = 0; i < keys.size(); i++) {
final Object key = keys.get(i);
keyToValueMapping.put(key, new Integer(i));
}
}
/**
* Removes a value from the collection.
*
* @param index the index of the item to remove (in the range
* <code>0</code> to <code>getItemCount() - 1</code>).
*
* @throws IndexOutOfBoundsException if <code>index</code> is not within
* the specified range.
*/
public void removeValue(int index) {
this.keys.remove(index);
this.values.remove(index);
// did we remove the last item? If not, then rebuild the index ..
if (index < keys.size()) {
rebuildIndex();
}
}
public void removeValue(Comparable key) {
int index = getIndex(key);
if (index >= 0) {
removeValue(index);
}
}
/**
* Clears all values from the collection.
*
* @since 1.0.2
*/
public void clear() {
this.keys.clear();
this.values.clear();
this.keyToValueMapping.clear();
}
/**
* Sorts the items in the list by key.
*
* @param order the sort order (<code>null</code> not permitted).
*/
public void sortByKeys(SortOrder order) {
final int size = keys.size();
final DefaultKeyedValue[] data = new DefaultKeyedValue[size];
for (int i = 0; i < size; i++) {
data[i] = new DefaultKeyedValue((Comparable) keys.get(i), (Number) values.get(i));
}
Comparator comparator = new KeyedValueComparator(
KeyedValueComparatorType.BY_KEY, order);
Arrays.sort(data, comparator);
clear();
for (int i = 0; i < data.length; i++) {
final DefaultKeyedValue value = data[i];
addValue(value.getKey(), value.getValue());
}
}
/**
* Sorts the items in the list by value. If the list contains
* <code>null</code> values, they will sort to the end of the list,
* irrespective of the sort order.
*
* @param order the sort order (<code>null</code> not permitted).
*/
public void sortByValues(SortOrder order) {
final int size = keys.size();
final DefaultKeyedValue[] data = new DefaultKeyedValue[size];
for (int i = 0; i < size; i++) {
data[i] = new DefaultKeyedValue((Comparable) keys.get(i), (Number) values.get(i));
}
Comparator comparator = new KeyedValueComparator(
KeyedValueComparatorType.BY_VALUE, order);
Arrays.sort(data, comparator);
clear();
for (int i = 0; i < data.length; i++) {
final DefaultKeyedValue value = data[i];
addValue(value.getKey(), value.getValue());
}
}
/**
* Tests if this object is equal to another.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof KeyedValues)) {
return false;
}
KeyedValues that = (KeyedValues) obj;
int count = getItemCount();
if (count != that.getItemCount()) {
return false;
}
for (int i = 0; i < count; i++) {
Comparable k1 = getKey(i);
Comparable k2 = that.getKey(i);
if (!k1.equals(k2)) {
return false;
}
Number v1 = getValue(i);
Number v2 = that.getValue(i);
if (v1 == null) {
if (v2 != null) {
return false;
}
}
else {
if (!v1.equals(v2)) {
return false;
}
}
}
return true;
}
/**
* Returns a hash code.
*
* @return A hash code.
*/
public int hashCode() {
return (this.keys != null ? this.keys.hashCode() : 0);
}
/**
* Returns a clone.
*
* @return A clone.
*
* @throws CloneNotSupportedException this class will not throw this
* exception, but subclasses might.
*/
public Object clone() throws CloneNotSupportedException {
DefaultKeyedValues clone = (DefaultKeyedValues) super.clone();
clone.keys = (ArrayList) keys.clone();
clone.values = (ArrayList) values.clone();
clone.keyToValueMapping = (HashMap) keyToValueMapping.clone();
return clone;
}
}
|
package duro.runtime;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
import duro.debugging.Debug;
import duro.transcriber.Journal;
public class CustomProcess extends Process implements Iterable<Object> {
private static final long serialVersionUID = 1L;
private static final Instruction[] FORWARD_CALL_INSTRUCTIONS = new Instruction[] {
new Instruction(Instruction.OPCODE_FORWARD_CALL),
new Instruction(Instruction.OPCODE_RET_FORWARD)
};
public static class Frame implements Serializable {
private static final long serialVersionUID = 1L;
public final Process self;
public Object[] arguments;
public Object[] variables;
public final Instruction[] instructions;
public int instructionPointer;
public Stack<Object> stack = new Stack<Object>();
public Frame(Process self, Object[] arguments, int variableCount, Instruction[] instructions) {
this.self = self;
this.arguments = arguments;
variables = new Object[variableCount];
this.instructions = instructions;
}
public Frame(Process self, Object[] arguments, Object[] variables, Instruction[] instructions) {
this.self = self;
this.arguments = arguments;
this.variables = variables;
this.instructions = instructions;
}
}
private Frame currentFrame;
private Stack<Frame> frameStack = new Stack<Frame>();
public CustomProcess(int variableCount, Instruction[] instructions) {
currentFrame = new Frame(this, new Object[0], variableCount, instructions);
// Add Any prototype
DictionaryProcess any = new DictionaryProcess();
properties.put("Any", any);
// Add Iterable prototype
DictionaryProcess iterable = any.clone();
properties.put("Iterable", iterable);
// Add Iterator prototype
properties.put("Iterator", any.clone());
// Add Array prototype
properties.put("Array", iterable.clone());
}
@Override
public void replay(List<Instruction> commands) {
Debug.println(Debug.LEVEL_HIGH, "replay");
for(Instruction instruction: commands) {
Debug.println(Debug.LEVEL_HIGH, "stack: " + currentFrame.stack);
Debug.println(Debug.LEVEL_HIGH, "replay: " + instruction);
next(instruction);
}
if(currentFrame != null)
Debug.println(Debug.LEVEL_HIGH, "stack: " + currentFrame.stack);
Debug.println(Debug.LEVEL_HIGH, "/replay");
}
private boolean stopRequested;
private void next(Instruction instruction) {
switch(instruction.opcode) {
case Instruction.OPCODE_PAUSE: {
stopRequested = true;
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_INC_IP: {
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_FINISH: {
stopRequested = true;
currentFrame = null;
break;
} case Instruction.OPCODE_DUP: {
currentFrame.stack.push(currentFrame.stack.peek());
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_DUP1: {
int index = currentFrame.stack.size() - 2;
currentFrame.stack.add(index, currentFrame.stack.peek());
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_DUP2: {
int index = currentFrame.stack.size() - 3;
currentFrame.stack.add(index, currentFrame.stack.peek());
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_DUP_ANY: {
int sourceOffset = (int)instruction.operand1;
int insertionOffset = (int)instruction.operand2;
int top = currentFrame.stack.size() - 1;
Object sourceValue = currentFrame.stack.get(top - sourceOffset);
currentFrame.stack.add(top - insertionOffset, sourceValue);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_STORE_LOC: {
int ordinal = (int)instruction.operand1;
Object value = currentFrame.stack.pop();
currentFrame.variables[ordinal] = value;
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_POP: {
currentFrame.stack.pop();
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SWAP: {
Object tmp = currentFrame.stack.get(currentFrame.stack.size() - 1);
currentFrame.stack.set(currentFrame.stack.size() - 1, currentFrame.stack.get(currentFrame.stack.size() - 2));
currentFrame.stack.set(currentFrame.stack.size() - 2, tmp);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SWAP1: {
Object tmp = currentFrame.stack.get(currentFrame.stack.size() - 2);
currentFrame.stack.set(currentFrame.stack.size() - 2, currentFrame.stack.get(currentFrame.stack.size() - 3));
currentFrame.stack.set(currentFrame.stack.size() - 3, tmp);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SWAP_ANY: {
int top = currentFrame.stack.size() - 1;
int index1 = top - (int)instruction.operand1; // operand1: offsetFromTop0 for first index
int index2 = top - (int)instruction.operand2; // operand2: offsetFromTop0 for second index
Object tmp = currentFrame.stack.get(index1);
currentFrame.stack.set(index1, currentFrame.stack.get(index2));
currentFrame.stack.set(index2, tmp);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SEND: {
String key = (String)instruction.operand1;
int argumentCount = (int)instruction.operand2;
Object[] arguments = new Object[argumentCount];
for(int i = argumentCount - 1; i >= 0; i
arguments[i] = currentFrame.stack.pop();
Process receiver = (Process)currentFrame.stack.pop();
Object callable = receiver.getCallable(key);
if(callable instanceof CallFrameInfo) {
CallFrameInfo callFrameInfo = (CallFrameInfo)callable;
frameStack.push(currentFrame);
currentFrame = new Frame(receiver, arguments, callFrameInfo.variableCount, callFrameInfo.instructions);
} else {
Process process = (Process)callable;
Process self = new CallProcess(process, receiver);
frameStack.push(currentFrame);
currentFrame = new Frame(self, arguments, 0, FORWARD_CALL_INSTRUCTIONS);
}
break;
} case Instruction.OPCODE_CALL: {
int argumentCount = (int)instruction.operand1;
Object[] arguments = new Object[argumentCount];
for(int i = argumentCount - 1; i >= 0; i
arguments[i] = currentFrame.stack.pop();
Object callable = currentFrame.stack.pop();
if(callable instanceof CallFrameInfo) {
CallFrameInfo callFrameInfo = (CallFrameInfo)callable;
frameStack.push(currentFrame);
currentFrame = new Frame(currentFrame.self, arguments, callFrameInfo.variableCount, callFrameInfo.instructions);
} else {
Process process = (Process)callable;
Process self = new CallProcess(process, currentFrame.self);
frameStack.push(currentFrame);
currentFrame = new Frame(self, arguments, 0, FORWARD_CALL_INSTRUCTIONS);
}
break;
} case Instruction.OPCODE_FORWARD_CALL: {
Object[] arguments = currentFrame.arguments;
Process proxyCallable = currentFrame.self;
Object callable = proxyCallable.getCallable("call");
if(callable instanceof CallFrameInfo) {
CallFrameInfo callFrameInfo = (CallFrameInfo)callable;
frameStack.push(currentFrame);
currentFrame = new Frame(currentFrame.self, arguments, callFrameInfo.variableCount, callFrameInfo.instructions);
} else {
Process process = (Process)callable;
Process self = new CallProcess(process, currentFrame.self);
frameStack.push(currentFrame);
currentFrame = new Frame(self, arguments, 0, FORWARD_CALL_INSTRUCTIONS);
}
break;
} case Instruction.OPCODE_RESUME: {
Frame frame = (Frame)currentFrame.stack.pop();
frameStack.push(currentFrame);
currentFrame = frame;
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_RET: {
int returnCount = (int)instruction.operand1;
Frame outerFrame = frameStack.pop();
for(int i = 0; i < returnCount; i++)
outerFrame.stack.push(currentFrame.stack.pop());
currentFrame = outerFrame;
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_RET_THIS: {
Object result = currentFrame.self;
currentFrame = frameStack.pop();
currentFrame.stack.push(result);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_RET_FORWARD: {
Frame outerFrame = frameStack.pop();
outerFrame.stack.addAll(currentFrame.stack);
currentFrame = outerFrame;
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_DEF: {
Object value = currentFrame.stack.pop();
Object key = currentFrame.stack.pop();
Process receiver = (Process)currentFrame.stack.pop();
receiver.define(key, value);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_IF_TRUE: {
boolean value = (boolean)currentFrame.stack.pop();
if(value) {
int jump = (int)instruction.operand1;
currentFrame.instructionPointer += jump;
} else
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_IF_FALSE: {
boolean value = (boolean)currentFrame.stack.pop();
if(!value) {
int jump = (int)instruction.operand1;
currentFrame.instructionPointer += jump;
} else
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_JUMP: {
int jump = (int)instruction.operand1;
currentFrame.instructionPointer += jump;
break;
} case Instruction.OPCODE_SET: {
Object value = currentFrame.stack.pop();
Object key = currentFrame.stack.pop(); // Assumed to be string only
Process receiver = (Process)currentFrame.stack.pop();
receiver.define(key, value);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_GET: {
Object key = currentFrame.stack.pop(); // Assumed to be string only
Process receiver = (Process)currentFrame.stack.pop();
Object value = receiver.lookup(key);
currentFrame.stack.push(value);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_EXEC_ON_FRAME: {
CallFrameInfo callFrameInfo = (CallFrameInfo)currentFrame.stack.pop();
Frame frame = (Frame)currentFrame.stack.pop();
// Move forward arguments
Object[] arguments = new Object[frame.arguments.length + callFrameInfo.argumentCount];
System.arraycopy(currentFrame.arguments, 0, arguments, frame.arguments.length, currentFrame.arguments.length);
frameStack.push(currentFrame);
currentFrame = new Frame(frame.self, arguments, frame.variables, callFrameInfo.instructions);
break;
}
// public static final int OPCODE_FORWARD_ARGS = 25;
// public static final int OPCODE_EXEC_ON_FRAME = 26;
case Instruction.OPCODE_LOAD_THIS: {
currentFrame.stack.push(currentFrame.self);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_NULL: {
currentFrame.stack.push(new NullProcess());
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_LOC: {
int ordinal = (int)instruction.operand1;
Object value = currentFrame.variables[ordinal];
currentFrame.stack.push(value);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_ARG: {
int ordinal = (int)instruction.operand1;
Object value = currentFrame.arguments[ordinal];
currentFrame.stack.push(value);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_INT: {
currentFrame.stack.push(instruction.operand1);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_FUNC: {
currentFrame.stack.push(instruction.operand1);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_TRUE: {
currentFrame.stack.push(true);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_FALSE: {
currentFrame.stack.push(false);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_STRING: {
String string = (String)instruction.operand1;
currentFrame.stack.push(string);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_FRAME: {
Frame frame = (Frame)instruction.operand1;
currentFrame.stack.push(frame);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_ARRAY: {
Object[] array = (Object[])instruction.operand1;
currentFrame.stack.push(array);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_LOAD_ANY: {
Process process = (Process)instruction.operand1;
currentFrame.stack.push(process);
currentFrame.instructionPointer++;
break;
}
// Special opcodes
case Instruction.OPCODE_SP_OR: {
boolean rhs = (boolean)currentFrame.stack.pop();
boolean lhs = (boolean)currentFrame.stack.pop();
currentFrame.stack.push(lhs || rhs);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_AND: {
boolean rhs = (boolean)currentFrame.stack.pop();
boolean lhs = (boolean)currentFrame.stack.pop();
currentFrame.stack.push(lhs && rhs);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_EQUALS: {
Object rhs = (Object)currentFrame.stack.pop();
Object lhs = (Object)currentFrame.stack.pop();
currentFrame.stack.push(lhs.equals(rhs));
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_GREATER: {
@SuppressWarnings("rawtypes")
Comparable rhs = (Comparable)currentFrame.stack.pop();
@SuppressWarnings("rawtypes")
Comparable lhs = (Comparable)currentFrame.stack.pop();
@SuppressWarnings("unchecked")
boolean result = lhs.compareTo(rhs) > 0;
currentFrame.stack.push(result);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_GREATER_EQUALS: {
@SuppressWarnings("rawtypes")
Comparable rhs = (Comparable)currentFrame.stack.pop();
@SuppressWarnings("rawtypes")
Comparable lhs = (Comparable)currentFrame.stack.pop();
@SuppressWarnings("unchecked")
int comparison = lhs.compareTo(rhs);
boolean result = comparison >= 0;
currentFrame.stack.push(result);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_LESS: {
@SuppressWarnings("rawtypes")
Comparable rhs = (Comparable)currentFrame.stack.pop();
@SuppressWarnings("rawtypes")
Comparable lhs = (Comparable)currentFrame.stack.pop();
@SuppressWarnings("unchecked")
boolean result = lhs.compareTo(rhs) < 0;
currentFrame.stack.push(result);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_LESS_EQUALS: {
@SuppressWarnings("rawtypes")
Comparable rhs = (Comparable)currentFrame.stack.pop();
@SuppressWarnings("rawtypes")
Comparable lhs = (Comparable)currentFrame.stack.pop();
@SuppressWarnings("unchecked")
int comparison = lhs.compareTo(rhs);
boolean result = comparison <= 0;
currentFrame.stack.push(result);
currentFrame.instructionPointer++;
break;
}
case Instruction.OPCODE_SP_NOT: {
boolean b = (boolean)currentFrame.stack.pop();
currentFrame.stack.push(!b);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_ADD: {
Object rhs = currentFrame.stack.pop();
Object lhs = currentFrame.stack.pop();
if(lhs instanceof Integer && rhs instanceof Integer)
currentFrame.stack.push((int)lhs + (int)rhs);
else if(lhs instanceof String || rhs instanceof String)
currentFrame.stack.push(lhs.toString() + rhs.toString());
else {
Debug.println(Debug.LEVEL_LOW, "Invalid add operation.");
}
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_SUB: {
int rhs = (int)currentFrame.stack.pop();
int lhs = (int)currentFrame.stack.pop();
currentFrame.stack.push(lhs - rhs);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_MULT: {
int rhs = (int)currentFrame.stack.pop();
int lhs = (int)currentFrame.stack.pop();
currentFrame.stack.push(lhs * rhs);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_DIV: {
int rhs = (int)currentFrame.stack.pop();
int lhs = (int)currentFrame.stack.pop();
currentFrame.stack.push(lhs / rhs);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_REM: {
int rhs = (int)currentFrame.stack.pop();
int lhs = (int)currentFrame.stack.pop();
currentFrame.stack.push(lhs % rhs);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_ARRAY_GET: {
int index = (int)currentFrame.stack.pop();
ArrayProcess array = (ArrayProcess)currentFrame.stack.pop();
currentFrame.stack.push(array.get(index));
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_ARRAY_SET: {
Object value = (Object)currentFrame.stack.pop();
int index = (int)currentFrame.stack.pop();
ArrayProcess array = (ArrayProcess)currentFrame.stack.pop();
array.set(index, value);
currentFrame.instructionPointer++;
break;
}
case Instruction.OPCODE_SP_WRITE: {
Object value = currentFrame.stack.pop();
System.out.print(value);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_NEXT_LINE: {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
currentFrame.stack.push(line);
// Store the value for the replay instruction
lastReadLine = line;
} catch (IOException e) {
e.printStackTrace();
}
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_NEW_DICT: {
DictionaryProcess newDict = new DictionaryProcess();
currentFrame.stack.push(newDict);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_NEW_ARRAY: {
int length = (int)currentFrame.stack.pop();
ArrayProcess newArray = new ArrayProcess(length);
newArray.defineProto("prototype", properties.get("Array"));
currentFrame.stack.push(newArray);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_ARRAY_LENGTH: {
ArrayProcess newArray = (ArrayProcess)currentFrame.stack.pop();
currentFrame.stack.push(newArray.length());
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_LOAD: {
String path = (String)currentFrame.stack.pop();
try {
// What to do here during replay?
// or rather, what to replace this instruction with for replay?
path = "commons/gens/" + path;
Journal<duro.runtime.Process, Instruction> journal = Journal.read(path);
CustomProcess customProcess = (CustomProcess)journal.getRoot();
// Assumed to end with finish instruction. Replace finish with pop_frame.
customProcess.currentFrame.instructions[customProcess.currentFrame.instructions.length - 1] = new Instruction(Instruction.OPCODE_RET_THIS);
this.frameStack.push(currentFrame);
currentFrame = new Frame(this, customProcess.currentFrame.arguments, customProcess.currentFrame.variables.length, customProcess.currentFrame.instructions);
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
break;
} case Instruction.OPCODE_SP_NEW_GENERATOR: {
Object[] arguments = (Object[])currentFrame.stack.pop();
Process self = (Process)currentFrame.stack.pop();
CallFrameInfo callFrameInfo = (CallFrameInfo)currentFrame.stack.pop();
Frame generatorFrame = new Frame(self, arguments, callFrameInfo.variableCount, callFrameInfo.instructions);
GeneratorProcess generator = new GeneratorProcess(generatorFrame);
DictionaryProcess iteratorPrototype = (DictionaryProcess)properties.get("Iterator");
generator.defineProto("prototype", iteratorPrototype);
currentFrame.stack.push(generator);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_NEW_GENERATABLE: {
int argumentCount = (int)instruction.operand1;
Object[] arguments = new Object[argumentCount];
for(int i = argumentCount - 1; i >= 0; i
arguments[i] = currentFrame.stack.pop();
CallFrameInfo callFrameInfo = (CallFrameInfo)currentFrame.stack.pop();
GeneratableProcess generatable = new GeneratableProcess(callFrameInfo, currentFrame.self, arguments);
DictionaryProcess iterablePrototype = (DictionaryProcess)properties.get("Iterable");
generatable.defineProto("prototype", iterablePrototype);
currentFrame.stack.push(generatable);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_NEW_CLOSURE: {
CallFrameInfo callFrameInfo = (CallFrameInfo)currentFrame.stack.pop();
currentFrame.stack.push(new ClosureProcess(currentFrame, callFrameInfo));
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_SP_CLONE: {
DictionaryProcess dict = (DictionaryProcess)currentFrame.stack.pop();
DictionaryProcess clone = dict.clone();
currentFrame.stack.push(clone);
currentFrame.instructionPointer++;
break;
} case Instruction.OPCODE_BREAK_POINT: {
new String();
currentFrame.instructionPointer++;
break;
}
}
}
private String lastReadLine;
@Override
public void resume(List<Instruction> playedInstructions) {
Debug.println(Debug.LEVEL_HIGH, "play");
if(currentFrame != null) {
while(!stopRequested) {
Instruction instruction = currentFrame.instructions[currentFrame.instructionPointer];
Debug.println(Debug.LEVEL_HIGH, "stack: " + currentFrame.stack);
Debug.println(Debug.LEVEL_HIGH, "play: " + instruction);
next(instruction);
switch(instruction.opcode) {
case Instruction.OPCODE_PAUSE:
playedInstructions.add(new Instruction(Instruction.OPCODE_INC_IP));
break;
case Instruction.OPCODE_SP_WRITE:
// Don't manipulate peripherals on replay
break;
case Instruction.OPCODE_SP_NEXT_LINE:
// The replay instruction simply pushes the read key consistently
playedInstructions.add(new Instruction(Instruction.OPCODE_LOAD_STRING, lastReadLine));
// Don't manipulate peripherals on replay
break;
default:
playedInstructions.add(instruction);
break;
}
}
}
if(currentFrame != null && currentFrame.stack.size() > 0)
Debug.println(Debug.LEVEL_LOW, "stack isn't empty: " + currentFrame.stack);
if(currentFrame != null)
Debug.println(Debug.LEVEL_HIGH, "stack: " + currentFrame.stack);
Debug.println(Debug.LEVEL_HIGH, "/play");
}
private Hashtable<Object, Object> properties = new Hashtable<Object, Object>();
@Override
public Object getCallable(Object key) {
return properties.get(key);
}
@Override
public void define(Object key, Object value) {
properties.put(key, value);
}
@Override
public Object lookup(Object key) {
return properties.get(key);
}
@Override
public Iterator<Object> iterator() {
return properties.keySet().iterator();
}
}
|
package dynamake;
import java.awt.Color;
import java.awt.Font;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.Date;
import java.util.Hashtable;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import org.prevayler.Transaction;
import dynamake.Model.RemovableListener;
public class FloatingTextModel extends Model {
public static final String PROPERTY_CARET_COLOR = "Caret Color";
private static final long serialVersionUID = 1L;
private StringBuilder text = new StringBuilder();
@Override
public Model modelCloneIsolated() {
FloatingTextModel clone = new FloatingTextModel();
clone.text.append(this.text);
return clone;
}
@Override
protected void modelScale(Fraction hChange, Fraction vChange, PropogationContext propCtx, int propDistance) {
Fraction fontSize = (Fraction)getProperty("FontSize");
if(fontSize == null)
fontSize = new Fraction(12);
fontSize = fontSize.multiply(hChange);
setProperty("FontSize", fontSize, propCtx, propDistance);
}
public void setText(String text) {
this.text.setLength(0);
this.text.append(text);
}
public String getText() {
return text.toString();
}
public void remove(int start, int end) {
}
private static class InsertTransaction implements Command<Model> {
private static final long serialVersionUID = 1L;
private Location textLocation;
private int offset;
private String text;
public InsertTransaction(Location textLocation, int offset, String text) {
this.textLocation = textLocation;
this.offset = offset;
this.text = text;
}
public void executeOn(PropogationContext propCtx, Model prevalentSystem, Date executionTime) {
FloatingTextModel textModel = (FloatingTextModel)textLocation.getChild(prevalentSystem);
textModel.text.insert(offset, text);
}
// @Override
// public Command<FloatingTextModel> antagonist() {
// // TODO Auto-generated method stub
// return null;
}
private static class RemoveTransaction implements Command<Model> {
private static final long serialVersionUID = 1L;
private Location textLocation;
private int start;
private int end;
public RemoveTransaction(Location textLocation, int start, int end) {
this.textLocation = textLocation;
this.start = start;
this.end = end;
}
public void executeOn(PropogationContext propCtx, Model prevalentSystem, Date executionTime) {
FloatingTextModel textModel = (FloatingTextModel)textLocation.getChild(prevalentSystem);
textModel.text.delete(start, end);
}
// @Override
// public Command<FloatingTextModel> antagonist() {
// // TODO Auto-generated method stub
// return null;
}
private static class FloatingTextModelView extends JTextField implements ModelComponent {
private static final long serialVersionUID = 1L;
private FloatingTextModel model;
private TransactionFactory transactionFactory;
private JTextPane view;
public FloatingTextModelView(FloatingTextModel model, TransactionFactory transactionFactory, final ViewManager viewManager) {
this.model = model;
this.transactionFactory = transactionFactory;
this.setOpaque(false);
this.setBorder(null);
}
@Override
public Model getModelBehind() {
return model;
}
@Override
public TransactionFactory getTransactionFactory() {
return transactionFactory;
}
@Override
public void appendContainerTransactions(
TransactionMapBuilder transactions, ModelComponent child) {
}
@Override
public void appendTransactions(TransactionMapBuilder transactions) {
Model.appendComponentPropertyChangeTransactions(model, transactionFactory, transactions);
Color caretColor = (Color)model.getProperty(PROPERTY_CARET_COLOR);
if(caretColor == null)
caretColor = this.getCaretColor();
transactions.addTransaction("Set " + PROPERTY_CARET_COLOR, new ColorTransactionBuilder(caretColor, new Action1<Color>() {
@Override
public void run(Color color) {
transactionFactory.execute(new PropogationContext(), new Model.SetPropertyTransaction(PROPERTY_CARET_COLOR, color));
}
}));
}
@Override
public void appendDroppedTransactions(ModelComponent livePanel, final ModelComponent target, final Rectangle droppedBounds, TransactionMapBuilder transactions) {
Model.appendGeneralDroppedTransactions(livePanel, this, target, droppedBounds, transactions);
// if(target.getModelBehind() instanceof CanvasModel) {
// transactions.addTransaction("For new button", new Runnable() {
// @Override
// public void run() {
// Rectangle creationBounds = droppedBounds;
// Hashtable<String, Object> creationArgs = new Hashtable<String, Object>();
// creationArgs.put("Text", model.text.toString());
// getTransactionFactory().executeOnRoot(
// new CanvasModel.AddModelTransaction(target.getTransactionFactory().getLocation(), creationBounds, creationArgs, new ButtonModelFactory())
}
@Override
public void appendDropTargetTransactions(ModelComponent livePanel,
ModelComponent dropped, Rectangle droppedBounds, Point dropPoint, TransactionMapBuilder transactions) {
// TODO Auto-generated method stub
}
@Override
public Command<Model> getImplicitDropAction(ModelComponent target) {
// TODO Auto-generated method stub
return null;
}
@Override
public void initialize() {
// TODO Auto-generated method stub
}
}
@Override
public Binding<ModelComponent> createView(ModelComponent rootView, final ViewManager viewManager, final TransactionFactory transactionFactory) {
this.setLocation(transactionFactory.getModelLocator());
final FloatingTextModelView view = new FloatingTextModelView(this, transactionFactory, viewManager);
view.setText(text.toString());
// TODO: Investigate: Is caret color loaded anywhere?
final RemovableListener removeListenerForCaretColor = Model.bindProperty(this, PROPERTY_CARET_COLOR, new Action1<Color>() {
@Override
public void run(Color value) {
view.setCaretColor(value);
viewManager.repaint(view);
}
});
final RemovableListener removeListenerForBoundChanges = Model.wrapForBoundsChanges(this, view, viewManager);
final Model.RemovableListener removeListenerForComponentPropertyChanges = Model.wrapForComponentColorChanges(this, view, view, viewManager, Model.COMPONENT_COLOR_FOREGROUND);
final Binding<Model> removableListener = RemovableListener.addAll(this,
bindProperty(this, "FontSize", new Action1<Fraction>() {
public void run(Fraction value) {
Font font = view.getFont();
view.setFont(new Font(font.getFamily(), font.getStyle(), value.intValue()));
viewManager.refresh(view);
}
})
);
Model.loadComponentProperties(this, view, Model.COMPONENT_COLOR_FOREGROUND);
view.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
final int start = e.getOffset();
final int end = e.getOffset() + e.getLength();
transactionFactory.executeOnRoot(new PropogationContext(), new RemoveTransaction(transactionFactory.getModelLocation(), start, end));
}
@Override
public void insertUpdate(DocumentEvent e) {
final int offset = e.getOffset();
final String str;
try {
str = e.getDocument().getText(e.getOffset(), e.getLength());
transactionFactory.executeOnRoot(new PropogationContext(), new InsertTransaction(transactionFactory.getModelLocation(), offset, str));
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
@Override
public void changedUpdate(DocumentEvent e) { }
});
viewManager.wasCreated(view);
return new Binding<ModelComponent>() {
@Override
public void releaseBinding() {
removeListenerForCaretColor.releaseBinding();
removeListenerForBoundChanges.releaseBinding();
removeListenerForComponentPropertyChanges.releaseBinding();
removableListener.releaseBinding();
}
@Override
public ModelComponent getBindingTarget() {
return view;
}
};
}
}
|
package com.jme3.shader;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.export.InputCapsule;
import com.jme3.export.OutputCapsule;
import com.jme3.export.Savable;
import com.jme3.renderer.GLObject;
import com.jme3.renderer.Renderer;
import com.jme3.scene.VertexBuffer;
import com.jme3.util.IntMap;
import com.jme3.util.IntMap.Entry;
import com.jme3.util.ListMap;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
public final class Shader extends GLObject implements Savable {
private String language;
/**
* True if the shader is fully compiled & linked.
* (e.g no GL error will be invoked if used).
*/
private boolean usable = false;
/**
* A list of all shaders currently attached.
*/
private ArrayList<ShaderSource> shaderList;
/**
* Maps uniform name to the uniform variable.
*/
// private HashMap<String, Uniform> uniforms;
private ListMap<String, Uniform> uniforms;
/**
* Maps attribute name to the location of the attribute in the shader.
*/
private IntMap<Attribute> attribs;
/**
* Type of shader. The shader will control the pipeline of it's type.
*/
public static enum ShaderType {
/**
* Control fragment rasterization. (e.g color of pixel).
*/
Fragment,
/**
* Control vertex processing. (e.g transform of model to clip space)
*/
Vertex,
/**
* Control geometry assembly. (e.g compile a triangle list from input data)
*/
Geometry;
}
/**
* Shader source describes a shader object in OpenGL. Each shader source
* is assigned a certain pipeline which it controls (described by it's type).
*/
public static class ShaderSource extends GLObject implements Savable {
ShaderType shaderType;
boolean usable = false;
String name = null;
String source = null;
String defines = null;
public ShaderSource(ShaderType type){
super(Type.ShaderSource);
this.shaderType = type;
if (type == null)
throw new NullPointerException("The shader type must be specified");
}
protected ShaderSource(ShaderSource ss){
super(Type.ShaderSource, ss.id);
this.shaderType = ss.shaderType;
usable = false;
name = ss.name;
// forget source & defines
}
public ShaderSource(){
super(Type.ShaderSource);
}
public void write(JmeExporter ex) throws IOException{
OutputCapsule oc = ex.getCapsule(this);
oc.write(shaderType, "shaderType", null);
oc.write(name, "name", null);
oc.write(source, "source", null);
oc.write(defines, "defines", null);
}
public void read(JmeImporter im) throws IOException{
InputCapsule ic = im.getCapsule(this);
shaderType = ic.readEnum("shaderType", ShaderType.class, null);
name = ic.readString("name", null);
source = ic.readString("source", null);
defines = ic.readString("defines", null);
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public ShaderType getType() {
return shaderType;
}
public void setSource(String source){
if (source == null)
throw new NullPointerException("Shader source cannot be null");
this.source = source;
setUpdateNeeded();
}
public void setDefines(String defines){
if (defines == null)
throw new NullPointerException("Shader defines cannot be null");
this.defines = defines;
setUpdateNeeded();
}
public String getSource(){
return source;
}
public String getDefines(){
return defines;
}
public boolean isUsable(){
return usable;
}
public void setUsable(boolean usable){
this.usable = usable;
}
@Override
public String toString(){
String nameTxt = "";
if (name != null)
nameTxt = "name="+name+", ";
if (defines != null)
nameTxt += "defines, ";
return getClass().getSimpleName() + "["+nameTxt+"type="
+ shaderType.name()+"]";
}
public void resetObject(){
id = -1;
usable = false;
setUpdateNeeded();
}
public void deleteObject(Renderer r){
r.deleteShaderSource(ShaderSource.this);
}
public GLObject createDestructableClone(){
return new ShaderSource(ShaderSource.this);
}
}
/**
* Create an empty shader.
*/
public Shader(String language){
super(Type.Shader);
this.language = language;
shaderList = new ArrayList<ShaderSource>();
// uniforms = new HashMap<String, Uniform>();
uniforms = new ListMap<String, Uniform>();
attribs = new IntMap<Attribute>();
}
/**
* Do not use this constructor. Serialization purposes only.
*/
public Shader(){
super(Type.Shader);
}
protected Shader(Shader s){
super(Type.Shader, s.id);
shaderList = new ArrayList<ShaderSource>();
//uniforms = new ListMap<String, Uniform>();
//attribs = new IntMap<Attribute>();
// NOTE: Because ShaderSources are registered separately with
// the GLObjectManager
for (ShaderSource source : s.shaderList){
shaderList.add( (ShaderSource)source.createDestructableClone() );
}
}
public void write(JmeExporter ex) throws IOException{
OutputCapsule oc = ex.getCapsule(this);
oc.write(language, "language", null);
oc.writeSavableArrayList(shaderList, "shaderList", null);
oc.writeIntSavableMap(attribs, "attribs", null);
oc.writeStringSavableMap(uniforms, "uniforms", null);
}
public void read(JmeImporter im) throws IOException{
InputCapsule ic = im.getCapsule(this);
language = ic.readString("language", null);
shaderList = ic.readSavableArrayList("shaderList", null);
attribs = (IntMap<Attribute>) ic.readIntSavableMap("attribs", null);
HashMap<String, Uniform> uniMap = (HashMap<String, Uniform>) ic.readStringSavableMap("uniforms", null);
uniforms = new ListMap<String, Uniform>(uniMap);
}
/**
* Creates a deep clone of the shader, where the sources are available
* but have not been compiled yet. Does not copy the uniforms or attribs.
* @return
*/
// public Shader createDeepClone(String defines){
// Shader newShader = new Shader(language);
// for (ShaderSource source : shaderList){
// if (!source.getDefines().equals(defines)){
// // need to clone the shadersource so
// // the correct defines can be placed
// ShaderSource newSource = new ShaderSource(source.getType());
// newSource.setSource(source.getSource());
// newSource.setDefines(defines);
// newShader.addSource(newSource);
// }else{
// // no need to clone source, also saves
// // having to compile the shadersource
// newShader.addSource(source);
// return newShader;
/**
* Adds source code to a certain pipeline.
*
* @param type The pipeline to control
* @param source The shader source code (in GLSL).
*/
public void addSource(ShaderType type, String name, String source, String defines){
ShaderSource shader = new ShaderSource(type);
shader.setSource(source);
shader.setName(name);
if (defines != null)
shader.setDefines(defines);
shaderList.add(shader);
setUpdateNeeded();
}
public void addSource(ShaderType type, String source, String defines){
addSource(type, null, source, defines);
}
public void addSource(ShaderType type, String source){
addSource(type, source, null);
}
/**
* Adds an existing shader source to this shader.
* @param source
*/
private void addSource(ShaderSource source){
shaderList.add(source);
setUpdateNeeded();
}
public Uniform getUniform(String name){
Uniform uniform = uniforms.get(name);
if (uniform == null){
uniform = new Uniform();
uniform.name = name;
uniforms.put(name, uniform);
}
return uniform;
}
public void removeUniform(String name){
uniforms.remove(name);
}
public Attribute getAttribute(VertexBuffer.Type attribType){
int ordinal = attribType.ordinal();
Attribute attrib = attribs.get(ordinal);
if (attrib == null){
attrib = new Attribute();
attrib.name = attribType.name();
attribs.put(ordinal, attrib);
}
return attrib;
}
// public Collection<Uniform> getUniforms(){
// return uniforms.values();
public ListMap<String, Uniform> getUniformMap(){
return uniforms;
}
// public Collection<Attribute> getAttributes() {
// return attribs.
public Collection<ShaderSource> getSources(){
return shaderList;
}
public String getLanguage(){
return language;
}
@Override
public String toString(){
return getClass().getSimpleName() + "[language="+language
+ ", numSources="+shaderList.size()
+ ", numUniforms="+uniforms.size()
+ ", shaderSources="+getSources()+"]";
}
/**
* Clears all sources. Assuming that they have already been detached and
* removed on the GL side.
*/
public void resetSources(){
shaderList.clear();
}
/**
* Returns true if this program and all it's shaders have been compiled,
* linked and validated successfuly.
*/
public boolean isUsable(){
return usable;
}
/**
* Sets if the program can be used. Should only be called by the Renderer.
* @param usable
*/
public void setUsable(boolean usable){
this.usable = usable;
}
/**
* Usually called when the shader itself changes or during any
* time when the var locations need to be refreshed.
*/
public void resetLocations(){
// NOTE: Shader sources will be reset seperately from the shader itself.
for (Uniform uniform : uniforms.values()){
uniform.reset(); // fixes issue with re-initialization
}
for (Entry<Attribute> entry : attribs){
entry.getValue().location = -2;
}
}
@Override
public void setUpdateNeeded(){
super.setUpdateNeeded();
resetLocations();
}
/**
* Called by the object manager to reset all object IDs. This causes
* the shader to be reuploaded to the GPU incase the display was restarted.
*/
@Override
public void resetObject() {
this.id = -1;
this.usable = false;
for (ShaderSource source : shaderList){
source.resetObject();
}
setUpdateNeeded();
}
@Override
public void deleteObject(Renderer r) {
r.deleteShader(this);
}
public GLObject createDestructableClone(){
return new Shader(this);
}
}
|
package io.debezium.jdbc;
import static io.debezium.util.NumberConversions.BYTE_BUFFER_ZERO;
import static io.debezium.util.NumberConversions.BYTE_ZERO;
import static io.debezium.util.NumberConversions.SHORT_FALSE;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Types;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.ZoneOffset;
import java.time.temporal.TemporalAdjuster;
import java.util.BitSet;
import java.util.concurrent.TimeUnit;
import org.apache.kafka.connect.data.Field;
import org.apache.kafka.connect.data.SchemaBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.debezium.annotation.Immutable;
import io.debezium.data.Bits;
import io.debezium.data.SpecialValueDecimal;
import io.debezium.data.Xml;
import io.debezium.relational.Column;
import io.debezium.relational.ValueConverter;
import io.debezium.relational.ValueConverterProvider;
import io.debezium.time.Date;
import io.debezium.time.MicroTime;
import io.debezium.time.MicroTimestamp;
import io.debezium.time.NanoTime;
import io.debezium.time.NanoTimestamp;
import io.debezium.time.Time;
import io.debezium.time.Timestamp;
import io.debezium.time.ZonedTime;
import io.debezium.time.ZonedTimestamp;
import io.debezium.util.NumberConversions;
/**
* A provider of {@link ValueConverter}s and {@link SchemaBuilder}s for various column types. This implementation is aware
* of the most common JDBC types and values. Specializations for specific DBMSes can be addressed in subclasses.
* <p>
* Although it is more likely that values will correspond pretty closely to the expected JDBC types, this class assumes it is
* possible for some variation to occur when values originate in libraries that are not JDBC drivers. Specifically, the conversion
* logic for JDBC temporal types with timezones (e.g., {@link Types#TIMESTAMP_WITH_TIMEZONE}) do support converting values that
* don't have timezones (e.g., {@link java.sql.Timestamp}) by assuming a default time zone offset for values that don't have
* (but are expected to have) timezones. Again, when the values are highly-correlated with the expected SQL/JDBC types, this
* default timezone offset will not be needed.
*
* @author Randall Hauch
*/
@Immutable
public class JdbcValueConverters implements ValueConverterProvider {
public enum DecimalMode {
PRECISE,
DOUBLE,
STRING;
}
public enum BigIntUnsignedMode {
PRECISE,
LONG;
}
protected final Logger logger = LoggerFactory.getLogger(getClass());
private final ZoneOffset defaultOffset;
/**
* Fallback value for TIMESTAMP WITH TZ is epoch
*/
private final String fallbackTimestampWithTimeZone;
/**
* Fallback value for TIME WITH TZ is 00:00
*/
private final String fallbackTimeWithTimeZone;
protected final boolean adaptiveTimePrecisionMode;
protected final boolean adaptiveTimeMicrosecondsPrecisionMode;
protected final DecimalMode decimalMode;
private final TemporalAdjuster adjuster;
protected final BigIntUnsignedMode bigIntUnsignedMode;
/**
* Create a new instance that always uses UTC for the default time zone when converting values without timezone information
* to values that require timezones, and uses adapts time and timestamp values based upon the precision of the database
* columns.
*/
public JdbcValueConverters() {
this(null, TemporalPrecisionMode.ADAPTIVE, ZoneOffset.UTC, null, null);
}
/**
* Create a new instance, and specify the time zone offset that should be used only when converting values without timezone
* information to values that require timezones. This default offset should not be needed when values are highly-correlated
* with the expected SQL/JDBC types.
*
* @param decimalMode how {@code DECIMAL} and {@code NUMERIC} values should be treated; may be null if
* {@link DecimalMode#PRECISE} is to be used
* @param temporalPrecisionMode temporal precision mode based on {@link io.debezium.jdbc.TemporalPrecisionMode}
* @param defaultOffset the zone offset that is to be used when converting non-timezone related values to values that do
* have timezones; may be null if UTC is to be used
* @param adjuster the optional component that adjusts the local date value before obtaining the epoch day; may be null if no
* adjustment is necessary
* @param bigIntUnsignedMode how {@code BIGINT UNSIGNED} values should be treated; may be null if
* {@link BigIntUnsignedMode#PRECISE} is to be used
*/
public JdbcValueConverters(DecimalMode decimalMode, TemporalPrecisionMode temporalPrecisionMode, ZoneOffset defaultOffset,
TemporalAdjuster adjuster, BigIntUnsignedMode bigIntUnsignedMode) {
this.defaultOffset = defaultOffset != null ? defaultOffset : ZoneOffset.UTC;
this.adaptiveTimePrecisionMode = temporalPrecisionMode.equals(TemporalPrecisionMode.ADAPTIVE);
this.adaptiveTimeMicrosecondsPrecisionMode = temporalPrecisionMode.equals(TemporalPrecisionMode.ADAPTIVE_TIME_MICROSECONDS);
this.decimalMode = decimalMode != null ? decimalMode : DecimalMode.PRECISE;
this.adjuster = adjuster;
this.bigIntUnsignedMode = bigIntUnsignedMode != null ? bigIntUnsignedMode : BigIntUnsignedMode.PRECISE;
this.fallbackTimestampWithTimeZone = ZonedTimestamp.toIsoString(
OffsetDateTime.of(LocalDate.ofEpochDay(0), LocalTime.MIDNIGHT, defaultOffset),
defaultOffset,
adjuster);
this.fallbackTimeWithTimeZone = ZonedTime.toIsoString(
OffsetTime.of(LocalTime.MIDNIGHT, defaultOffset),
defaultOffset,
adjuster);
}
@Override
public SchemaBuilder schemaBuilder(Column column) {
switch (column.jdbcType()) {
case Types.NULL:
logger.warn("Unexpected JDBC type: NULL");
return null;
// Single- and multi-bit values ...
case Types.BIT:
if (column.length() > 1) {
return Bits.builder(column.length());
}
// otherwise, it is just one bit so use a boolean ...
case Types.BOOLEAN:
return SchemaBuilder.bool();
// Fixed-length binary values ...
case Types.BLOB:
case Types.BINARY:
return SchemaBuilder.bytes();
// Variable-length binary values ...
case Types.VARBINARY:
case Types.LONGVARBINARY:
return SchemaBuilder.bytes();
// Numeric integers
case Types.TINYINT:
// values are an 8-bit unsigned integer value between 0 and 255
return SchemaBuilder.int8();
case Types.SMALLINT:
// values are a 16-bit signed integer value between -32768 and 32767
return SchemaBuilder.int16();
case Types.INTEGER:
// values are a 32-bit signed integer value between - 2147483648 and 2147483647
return SchemaBuilder.int32();
case Types.BIGINT:
// values are a 64-bit signed integer value between -9223372036854775808 and 9223372036854775807
return SchemaBuilder.int64();
// Numeric decimal numbers
case Types.REAL:
// values are single precision floating point number which supports 7 digits of mantissa.
return SchemaBuilder.float32();
case Types.FLOAT:
case Types.DOUBLE:
// values are double precision floating point number which supports 15 digits of mantissa.
return SchemaBuilder.float64();
case Types.NUMERIC:
case Types.DECIMAL:
return SpecialValueDecimal.builder(decimalMode, column.length(), column.scale().get());
// Fixed-length string values
case Types.CHAR:
case Types.NCHAR:
case Types.NVARCHAR:
case Types.LONGNVARCHAR:
case Types.NCLOB:
return SchemaBuilder.string();
// Variable-length string values
case Types.VARCHAR:
case Types.LONGVARCHAR:
case Types.CLOB:
case Types.DATALINK:
return SchemaBuilder.string();
case Types.SQLXML:
return Xml.builder();
// Date and time values
case Types.DATE:
if (adaptiveTimePrecisionMode || adaptiveTimeMicrosecondsPrecisionMode) {
return Date.builder();
}
return org.apache.kafka.connect.data.Date.builder();
case Types.TIME:
if (adaptiveTimeMicrosecondsPrecisionMode) {
return MicroTime.builder();
}
if (adaptiveTimePrecisionMode) {
if (getTimePrecision(column) <= 3) {
return Time.builder();
}
if (getTimePrecision(column) <= 6) {
return MicroTime.builder();
}
return NanoTime.builder();
}
return org.apache.kafka.connect.data.Time.builder();
case Types.TIMESTAMP:
if (adaptiveTimePrecisionMode || adaptiveTimeMicrosecondsPrecisionMode) {
if (getTimePrecision(column) <= 3) {
return Timestamp.builder();
}
if (getTimePrecision(column) <= 6) {
return MicroTimestamp.builder();
}
return NanoTimestamp.builder();
}
return org.apache.kafka.connect.data.Timestamp.builder();
case Types.TIME_WITH_TIMEZONE:
return ZonedTime.builder();
case Types.TIMESTAMP_WITH_TIMEZONE:
return ZonedTimestamp.builder();
// Other types ...
case Types.ROWID:
// often treated as a string, but we'll generalize and treat it as a byte array
return SchemaBuilder.bytes();
case Types.DISTINCT:
return distinctSchema(column);
// Unhandled types
case Types.ARRAY:
case Types.JAVA_OBJECT:
case Types.OTHER:
case Types.REF:
case Types.REF_CURSOR:
case Types.STRUCT:
default:
break;
}
return null;
}
@Override
public ValueConverter converter(Column column, Field fieldDefn) {
switch (column.jdbcType()) {
case Types.NULL:
return (data) -> null;
case Types.BIT:
return convertBits(column, fieldDefn);
case Types.BOOLEAN:
return (data) -> convertBoolean(column, fieldDefn, data);
// Binary values ...
case Types.BLOB:
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
return (data) -> convertBinary(column, fieldDefn, data);
// Numeric integers
case Types.TINYINT:
return (data) -> convertTinyInt(column, fieldDefn, data);
case Types.SMALLINT:
return (data) -> convertSmallInt(column, fieldDefn, data);
case Types.INTEGER:
return (data) -> convertInteger(column, fieldDefn, data);
case Types.BIGINT:
return (data) -> convertBigInt(column, fieldDefn, data);
// Numeric decimal numbers
case Types.FLOAT:
return (data) -> convertFloat(column, fieldDefn, data);
case Types.DOUBLE:
return (data) -> convertDouble(column, fieldDefn, data);
case Types.REAL:
return (data) -> convertReal(column, fieldDefn, data);
case Types.NUMERIC:
return (data) -> convertNumeric(column, fieldDefn, data);
case Types.DECIMAL:
return (data) -> convertDecimal(column, fieldDefn, data);
// String values
case Types.CHAR: // variable-length
case Types.VARCHAR: // variable-length
case Types.LONGVARCHAR: // variable-length
case Types.CLOB: // variable-length
case Types.NCHAR: // fixed-length
case Types.NVARCHAR: // fixed-length
case Types.LONGNVARCHAR: // fixed-length
case Types.NCLOB: // fixed-length
case Types.DATALINK:
case Types.SQLXML:
return (data) -> convertString(column, fieldDefn, data);
// Date and time values
case Types.DATE:
if (adaptiveTimePrecisionMode || adaptiveTimeMicrosecondsPrecisionMode) {
return (data) -> convertDateToEpochDays(column, fieldDefn, data);
}
return (data) -> convertDateToEpochDaysAsDate(column, fieldDefn, data);
case Types.TIME:
return (data) -> convertTime(column, fieldDefn, data);
case Types.TIMESTAMP:
if (adaptiveTimePrecisionMode || adaptiveTimeMicrosecondsPrecisionMode) {
if (getTimePrecision(column) <= 3) {
return data -> convertTimestampToEpochMillis(column, fieldDefn, data);
}
if (getTimePrecision(column) <= 6) {
return data -> convertTimestampToEpochMicros(column, fieldDefn, data);
}
return (data) -> convertTimestampToEpochNanos(column, fieldDefn, data);
}
return (data) -> convertTimestampToEpochMillisAsDate(column, fieldDefn, data);
case Types.TIME_WITH_TIMEZONE:
return (data) -> convertTimeWithZone(column, fieldDefn, data);
case Types.TIMESTAMP_WITH_TIMEZONE:
return (data) -> convertTimestampWithZone(column, fieldDefn, data);
// Other types ...
case Types.ROWID:
return (data) -> convertRowId(column, fieldDefn, data);
case Types.DISTINCT:
return convertDistinct(column, fieldDefn);
// Unhandled types
case Types.ARRAY:
case Types.JAVA_OBJECT:
case Types.OTHER:
case Types.REF:
case Types.REF_CURSOR:
case Types.STRUCT:
default:
return null;
}
}
protected ValueConverter convertBits(Column column, Field fieldDefn) {
if (column.length() > 1) {
int numBits = column.length();
int numBytes = numBits / Byte.SIZE + (numBits % Byte.SIZE == 0 ? 0 : 1);
return (data) -> convertBits(column, fieldDefn, data, numBytes);
}
return (data) -> convertBit(column, fieldDefn, data);
}
protected Object convertTimestampWithZone(Column column, Field fieldDefn, Object data) {
return convertValue(column, fieldDefn, data, fallbackTimestampWithTimeZone, (r) -> {
try {
r.deliver(ZonedTimestamp.toIsoString(data, defaultOffset, adjuster));
}
catch (IllegalArgumentException e) {
}
});
}
protected Object convertTimeWithZone(Column column, Field fieldDefn, Object data) {
return convertValue(column, fieldDefn, data, fallbackTimeWithTimeZone, (r) -> {
try {
r.deliver(ZonedTime.toIsoString(data, defaultOffset, adjuster));
}
catch (IllegalArgumentException e) {
}
});
}
protected Object convertTime(Column column, Field fieldDefn, Object data) {
if (adaptiveTimeMicrosecondsPrecisionMode) {
return convertTimeToMicrosPastMidnight(column, fieldDefn, data);
}
if (adaptiveTimePrecisionMode) {
if (getTimePrecision(column) <= 3) {
return convertTimeToMillisPastMidnight(column, fieldDefn, data);
}
if (getTimePrecision(column) <= 6) {
return convertTimeToMicrosPastMidnight(column, fieldDefn, data);
}
return convertTimeToNanosPastMidnight(column, fieldDefn, data);
}
// "connect" mode
else {
return convertTimeToMillisPastMidnightAsDate(column, fieldDefn, data);
}
}
protected Object convertTimestampToEpochMillis(Column column, Field fieldDefn, Object data) {
// epoch is the fallback value
return convertValue(column, fieldDefn, data, 0L, (r) -> {
try {
r.deliver(Timestamp.toEpochMillis(data, adjuster));
}
catch (IllegalArgumentException e) {
}
});
}
protected Object convertTimestampToEpochMicros(Column column, Field fieldDefn, Object data) {
// epoch is the fallback value
return convertValue(column, fieldDefn, data, 0L, (r) -> {
try {
r.deliver(MicroTimestamp.toEpochMicros(data, adjuster));
}
catch (IllegalArgumentException e) {
}
});
}
protected Object convertTimestampToEpochNanos(Column column, Field fieldDefn, Object data) {
// epoch is the fallback value
return convertValue(column, fieldDefn, data, 0L, (r) -> {
try {
r.deliver(NanoTimestamp.toEpochNanos(data, adjuster));
}
catch (IllegalArgumentException e) {
}
});
}
protected Object convertTimestampToEpochMillisAsDate(Column column, Field fieldDefn, Object data) {
// epoch is the fallback value
return convertValue(column, fieldDefn, data, new java.util.Date(0L), (r) -> {
try {
r.deliver(new java.util.Date(Timestamp.toEpochMillis(data, adjuster)));
}
catch (IllegalArgumentException e) {
}
});
}
protected Object convertTimeToMillisPastMidnight(Column column, Field fieldDefn, Object data) {
// epoch is the fallback value
return convertValue(column, fieldDefn, data, 0, (r) -> {
try {
r.deliver(Time.toMilliOfDay(data, supportsLargeTimeValues()));
}
catch (IllegalArgumentException e) {
}
});
}
protected Object convertTimeToMicrosPastMidnight(Column column, Field fieldDefn, Object data) {
// epoch is the fallback value
return convertValue(column, fieldDefn, data, 0L, (r) -> {
try {
r.deliver(MicroTime.toMicroOfDay(data, supportsLargeTimeValues()));
}
catch (IllegalArgumentException e) {
}
});
}
protected Object convertTimeToNanosPastMidnight(Column column, Field fieldDefn, Object data) {
// epoch is the fallback value
return convertValue(column, fieldDefn, data, 0L, (r) -> {
try {
r.deliver(NanoTime.toNanoOfDay(data, supportsLargeTimeValues()));
}
catch (IllegalArgumentException e) {
}
});
}
protected Object convertTimeToMillisPastMidnightAsDate(Column column, Field fieldDefn, Object data) {
// epoch is the fallback value
return convertValue(column, fieldDefn, data, new java.util.Date(0L), (r) -> {
try {
r.deliver(new java.util.Date(Time.toMilliOfDay(data, supportsLargeTimeValues())));
}
catch (IllegalArgumentException e) {
}
});
}
protected Object convertDateToEpochDays(Column column, Field fieldDefn, Object data) {
// epoch is the fallback value
return convertValue(column, fieldDefn, data, 0, (r) -> {
try {
r.deliver(Date.toEpochDay(data, adjuster));
}
catch (IllegalArgumentException e) {
logger.warn("Unexpected JDBC DATE value for field {} with schema {}: class={}, value={}", fieldDefn.name(),
fieldDefn.schema(), data.getClass(), data);
}
});
}
protected Object convertDateToEpochDaysAsDate(Column column, Field fieldDefn, Object data) {
// epoch is the fallback value
return convertValue(column, fieldDefn, data, new java.util.Date(0L), (r) -> {
try {
int epochDay = Date.toEpochDay(data, adjuster);
long epochMillis = TimeUnit.DAYS.toMillis(epochDay);
r.deliver(new java.util.Date(epochMillis));
}
catch (IllegalArgumentException e) {
logger.warn("Unexpected JDBC DATE value for field {} with schema {}: class={}, value={}", fieldDefn.name(),
fieldDefn.schema(), data.getClass(), data);
}
});
}
protected Object convertBinary(Column column, Field fieldDefn, Object data) {
return convertValue(column, fieldDefn, data, BYTE_ZERO, (r) -> {
Object dataMut = data;
if (dataMut instanceof char[]) {
dataMut = new String((char[]) dataMut); // convert to string
}
if (dataMut instanceof String) {
// This was encoded as a hexadecimal string, but we receive it as a normal string ...
dataMut = ((String) dataMut).getBytes();
}
if (dataMut instanceof byte[]) {
r.deliver(convertByteArray(column, (byte[]) dataMut));
}
else {
// An unexpected value
r.deliver(unexpectedBinary(dataMut, fieldDefn));
}
});
}
/**
* Converts the given byte array value into a byte buffer as preferred by Kafka Connect. Specific connectors
* can perform value adjustments based on the column definition, e.g. right-pad with 0x00 bytes in case of
* fixed length BINARY in MySQL.
*/
protected ByteBuffer convertByteArray(Column column, byte[] data) {
// Kafka Connect would support raw byte arrays, too, but byte buffers are recommended
return ByteBuffer.wrap(data);
}
protected byte[] unexpectedBinary(Object value, Field fieldDefn) {
logger.warn("Unexpected JDBC BINARY value for field {} with schema {}: class={}, value={}", fieldDefn.name(),
fieldDefn.schema(), value.getClass(), value);
return null;
}
protected Object convertTinyInt(Column column, Field fieldDefn, Object data) {
return convertSmallInt(column, fieldDefn, data);
}
protected Object convertSmallInt(Column column, Field fieldDefn, Object data) {
return convertValue(column, fieldDefn, data, SHORT_FALSE, (r) -> {
if (data instanceof Short) {
r.deliver(data);
}
else if (data instanceof Number) {
Number value = (Number) data;
r.deliver(Short.valueOf(value.shortValue()));
}
else if (data instanceof Boolean) {
r.deliver(NumberConversions.getShort((Boolean) data));
}
else if (data instanceof String) {
r.deliver(Short.valueOf((String) data));
}
});
}
protected Object convertInteger(Column column, Field fieldDefn, Object data) {
return convertValue(column, fieldDefn, data, 0, (r) -> {
if (data instanceof Integer) {
r.deliver(data);
}
else if (data instanceof Number) {
Number value = (Number) data;
r.deliver(Integer.valueOf(value.intValue()));
}
else if (data instanceof Boolean) {
r.deliver(NumberConversions.getInteger((Boolean) data));
}
else if (data instanceof String) {
r.deliver(Integer.valueOf((String) data));
}
});
}
protected Object convertBigInt(Column column, Field fieldDefn, Object data) {
return convertValue(column, fieldDefn, data, 0L, (r) -> {
if (data instanceof Long) {
r.deliver(data);
}
else if (data instanceof Number) {
Number value = (Number) data;
r.deliver(Long.valueOf(value.longValue()));
}
else if (data instanceof Boolean) {
r.deliver(NumberConversions.getLong((Boolean) data));
}
else if (data instanceof String) {
r.deliver(Long.valueOf((String) data));
}
});
}
protected Object convertFloat(Column column, Field fieldDefn, Object data) {
return convertDouble(column, fieldDefn, data);
}
protected Object convertDouble(Column column, Field fieldDefn, Object data) {
return convertValue(column, fieldDefn, data, 0.0d, (r) -> {
if (data instanceof Double) {
r.deliver(data);
}
else if (data instanceof Number) {
// Includes BigDecimal and other numeric values ...
Number value = (Number) data;
r.deliver(Double.valueOf(value.doubleValue()));
}
else if (data instanceof SpecialValueDecimal) {
r.deliver(((SpecialValueDecimal) data).toDouble());
}
else if (data instanceof Boolean) {
r.deliver(NumberConversions.getDouble((Boolean) data));
}
});
}
protected Object convertReal(Column column, Field fieldDefn, Object data) {
return convertValue(column, fieldDefn, data, 0.0f, (r) -> {
if (data instanceof Float) {
r.deliver(data);
}
else if (data instanceof Number) {
// Includes BigDecimal and other numeric values ...
Number value = (Number) data;
r.deliver(Float.valueOf(value.floatValue()));
}
else if (data instanceof Boolean) {
r.deliver(NumberConversions.getFloat((Boolean) data));
}
});
}
protected Object convertNumeric(Column column, Field fieldDefn, Object data) {
return convertDecimal(column, fieldDefn, data);
}
protected Object convertDecimal(Column column, Field fieldDefn, Object data) {
if (data instanceof SpecialValueDecimal) {
return SpecialValueDecimal.fromLogical((SpecialValueDecimal) data, decimalMode, column.name());
}
Object decimal = toBigDecimal(column, fieldDefn, data);
if (decimal instanceof BigDecimal) {
return SpecialValueDecimal.fromLogical(new SpecialValueDecimal((BigDecimal) decimal), decimalMode, column.name());
}
return decimal;
}
protected Object toBigDecimal(Column column, Field fieldDefn, Object data) {
return convertValue(column, fieldDefn, data, BigDecimal.ZERO, (r) -> {
if (data instanceof BigDecimal) {
r.deliver(data);
}
else if (data instanceof Boolean) {
r.deliver(NumberConversions.getBigDecimal((Boolean) data));
}
else if (data instanceof Short) {
r.deliver(new BigDecimal(((Short) data).intValue()));
}
else if (data instanceof Integer) {
r.deliver(new BigDecimal(((Integer) data).intValue()));
}
else if (data instanceof Long) {
r.deliver(BigDecimal.valueOf(((Long) data).longValue()));
}
else if (data instanceof Float) {
r.deliver(BigDecimal.valueOf(((Float) data).doubleValue()));
}
else if (data instanceof Double) {
r.deliver(BigDecimal.valueOf(((Double) data).doubleValue()));
}
else if (data instanceof String) {
r.deliver(new BigDecimal((String) data));
}
});
}
protected BigDecimal withScaleAdjustedIfNeeded(Column column, BigDecimal data) {
if (column.scale().isPresent() && column.scale().get() > data.scale()) {
data = data.setScale(column.scale().get());
}
return data;
}
protected Object convertString(Column column, Field fieldDefn, Object data) {
return convertValue(column, fieldDefn, data, "", (r) -> {
if (data instanceof SQLXML) {
try {
r.deliver(((SQLXML) data).getString());
}
catch (SQLException e) {
throw new RuntimeException("Error processing data from " + column.jdbcType() + " and column " + column +
": class=" + data.getClass(), e);
}
}
else {
r.deliver(data.toString());
}
});
}
protected Object convertRowId(Column column, Field fieldDefn, Object data) {
return convertValue(column, fieldDefn, data, BYTE_BUFFER_ZERO, (r) -> {
if (data instanceof java.sql.RowId) {
java.sql.RowId row = (java.sql.RowId) data;
r.deliver(ByteBuffer.wrap(row.getBytes()));
}
});
}
protected Object convertBit(Column column, Field fieldDefn, Object data) {
return convertValue(column, fieldDefn, data, false, (r) -> {
if (data instanceof Boolean) {
r.deliver(data);
}
else if (data instanceof Short) {
r.deliver(((Short) data).intValue() == 0 ? Boolean.FALSE : Boolean.TRUE);
}
else if (data instanceof Integer) {
r.deliver(((Integer) data).intValue() == 0 ? Boolean.FALSE : Boolean.TRUE);
}
else if (data instanceof Long) {
r.deliver(((Long) data).intValue() == 0 ? Boolean.FALSE : Boolean.TRUE);
}
else if (data instanceof BitSet) {
BitSet value = (BitSet) data;
r.deliver(value.get(0));
}
});
}
protected Object convertBits(Column column, Field fieldDefn, Object data, int numBytes) {
return convertValue(column, fieldDefn, data, new byte[0], (r) -> {
if (data instanceof Boolean) {
Boolean value = (Boolean) data;
r.deliver(new byte[]{ value.booleanValue() ? (byte) 1 : (byte) 0 });
}
else if (data instanceof Short) {
Short value = (Short) data;
ByteBuffer buffer = ByteBuffer.allocate(Short.BYTES);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.putShort(value.shortValue());
r.deliver(buffer.array());
}
else if (data instanceof Integer) {
Integer value = (Integer) data;
ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(value.intValue());
r.deliver(buffer.array());
}
else if (data instanceof Long) {
Long value = (Long) data;
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.putLong(value.longValue());
r.deliver(buffer.array());
}
else if (data instanceof byte[]) {
byte[] bytes = (byte[]) data;
if (bytes.length == 1) {
r.deliver(bytes);
}
if (byteOrderOfBitType() == ByteOrder.BIG_ENDIAN) {
// Reverse it to little endian ...
int i = 0;
int j = bytes.length - 1;
byte tmp;
while (j > i) {
tmp = bytes[j];
bytes[j] = bytes[i];
bytes[i] = tmp;
++i;
--j;
}
}
r.deliver(padLittleEndian(numBytes, bytes));
}
else if (data instanceof BitSet) {
byte[] bytes = ((BitSet) data).toByteArray();
r.deliver(padLittleEndian(numBytes, bytes));
}
});
}
protected byte[] padLittleEndian(int numBytes, byte[] data) {
if (data.length < numBytes) {
byte[] padded = new byte[numBytes];
System.arraycopy(data, 0, padded, 0, data.length);
for (int i = data.length; i != numBytes; ++i) {
padded[i] = 0;
}
return padded;
}
return data;
}
/**
* Determine whether the {@code byte[]} values for columns of type {@code BIT(n)} are {@link ByteOrder#BIG_ENDIAN big-endian}
* or {@link ByteOrder#LITTLE_ENDIAN little-endian}. All values for {@code BIT(n)} columns are to be returned in
* {@link ByteOrder#LITTLE_ENDIAN little-endian}.
* <p>
* By default, this method returns {@link ByteOrder#LITTLE_ENDIAN}.
*
* @return little endian or big endian; never null
*/
protected ByteOrder byteOrderOfBitType() {
return ByteOrder.LITTLE_ENDIAN;
}
protected Object convertBoolean(Column column, Field fieldDefn, Object data) {
return convertValue(column, fieldDefn, data, false, (r) -> {
if (data instanceof Boolean) {
r.deliver(data);
}
else if (data instanceof Short) {
r.deliver(((Short) data).intValue() == 0 ? Boolean.FALSE : Boolean.TRUE);
}
else if (data instanceof Integer) {
r.deliver(((Integer) data).intValue() == 0 ? Boolean.FALSE : Boolean.TRUE);
}
else if (data instanceof Long) {
r.deliver(((Long) data).intValue() == 0 ? Boolean.FALSE : Boolean.TRUE);
}
});
}
protected Object handleUnknownData(Column column, Field fieldDefn, Object data) {
if (column.isOptional() || fieldDefn.schema().isOptional()) {
Class<?> dataClass = data.getClass();
if (logger.isWarnEnabled()) {
logger.warn("Unexpected value for JDBC type {} and column {}: class={}", column.jdbcType(), column,
dataClass.isArray() ? dataClass.getSimpleName() : dataClass.getName()); // don't include value in case its
// sensitive
}
return null;
}
throw new IllegalArgumentException("Unexpected value for JDBC type " + column.jdbcType() + " and column " + column +
": class=" + data.getClass()); // don't include value in case its sensitive
}
protected int getTimePrecision(Column column) {
return column.length();
}
/**
* Converts the given value for the given column/field.
*
* @param column
* describing the {@code data} value; never null
* @param fieldDefn
* the field definition; never null
* @param data
* the data object to be converted into a {@link Date Kafka Connect date} type
* @param fallback
* value that will be applied in case the column is defined as NOT NULL without a default value, but we
* still received no value; may happen e.g. when enabling MySQL's non-strict mode
* @param callback
* conversion routine that will be invoked in case the value is not null
*
* @return The converted value. Will be {@code null} if the inbound value was {@code null} and the column is
* optional. Will be the column's default value (converted to the corresponding KC type, if the inbound
* value was {@code null}, the column is non-optional and has a default value. Will be {@code fallback} if
* the inbound value was {@code null}, the column is non-optional and has no default value. Otherwise, it
* will be the value produced by {@code callback} and lastly the result returned by
* {@link #handleUnknownData(Column, Field, Object)}.
*/
protected Object convertValue(Column column, Field fieldDefn, Object data, Object fallback, ValueConversionCallback callback) {
if (data == null) {
if (column.isOptional()) {
return null;
}
final Object schemaDefault = fieldDefn.schema().defaultValue();
return schemaDefault != null ? schemaDefault : fallback;
}
logger.trace("Value from data object: *** {} ***", data);
final ResultReceiver r = ResultReceiver.create();
callback.convert(r);
logger.trace("Callback is: {}", callback);
logger.trace("Value from ResultReceiver: {}", r);
return r.hasReceived() ? r.get() : handleUnknownData(column, fieldDefn, data);
}
private boolean supportsLargeTimeValues() {
return adaptiveTimePrecisionMode || adaptiveTimeMicrosecondsPrecisionMode;
}
protected SchemaBuilder distinctSchema(Column column) {
return null;
}
protected ValueConverter convertDistinct(Column column, Field fieldDefn) {
return null;
}
}
|
//FILE: MainFrame.java
//PROJECT: Micro-Manager
//SUBSYSTEM: mmstudio
// This file is distributed in the hope that it will be useful,
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
package org.micromanager;
import com.google.common.eventbus.Subscribe;
import com.swtdesigner.SwingResourceManager;
import ij.gui.ImageCanvas;
import ij.gui.ImageWindow;
import ij.WindowManager;
import java.awt.Dimension;
import java.awt.dnd.DropTarget;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Font;
import java.awt.KeyboardFocusManager;
import java.awt.Rectangle;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.prefs.Preferences;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import mmcorej.CMMCore;
import mmcorej.MMCoreJ;
import mmcorej.StrVector;
import org.micromanager.api.events.ConfigGroupChangedEvent;
import org.micromanager.events.EventManager;
import org.micromanager.imagedisplay.MetadataPanel;
import org.micromanager.imagedisplay.VirtualAcquisitionDisplay;
import org.micromanager.internalinterfaces.LiveModeListener;
import org.micromanager.utils.DragDropUtil;
import org.micromanager.utils.GUIUtils;
import org.micromanager.utils.MMKeyDispatcher;
import org.micromanager.utils.NumberUtils;
import org.micromanager.utils.ReportingUtils;
/**
* GUI code for the primary window of the program. And nothing else.
*/
public class MainFrame extends JFrame implements LiveModeListener {
private static final String MICRO_MANAGER_TITLE = "Micro-Manager";
private static final String MAIN_FRAME_X = "x";
private static final String MAIN_FRAME_Y = "y";
private static final String MAIN_FRAME_WIDTH = "width";
private static final String MAIN_FRAME_HEIGHT = "height";
private static final String MAIN_FRAME_DIVIDER_POS = "divider_pos";
private static final String MAIN_EXPOSURE = "exposure";
// GUI components
private JComboBox comboBinning_;
private JComboBox shutterComboBox_;
private JTextField textFieldExp_;
private JLabel labelImageDimensions_;
private JToggleButton liveButton_;
private JCheckBox autoShutterCheckBox_;
private JButton snapButton_;
private JButton autofocusNowButton_;
private JButton autofocusConfigureButton_;
private JButton saveConfigButton_;
private JToggleButton toggleShutterButton_;
private ConfigGroupPad configPad_;
private final Font defaultFont_ = new Font("Arial", Font.PLAIN, 10);
private final CMMCore core_;
private final MMStudio studio_;
private final SnapLiveManager snapLiveManager_;
private ConfigPadButtonPanel configPadButtonPanel_;
private final MetadataPanel metadataPanel_;
private final JSplitPane splitPane_;
private AbstractButton setRoiButton_;
private AbstractButton clearRoiButton_;
@SuppressWarnings("LeakingThisInConstructor")
public MainFrame(MMStudio studio, CMMCore core, SnapLiveManager manager,
Preferences prefs) {
org.micromanager.diagnostics.ThreadExceptionLogger.setUp();
studio_ = studio;
core_ = core;
snapLiveManager_ = manager;
snapLiveManager_.addLiveModeListener(this);
setTitle(MICRO_MANAGER_TITLE + " " + MMVersion.VERSION_STRING);
setMinimumSize(new Dimension(605,480));
splitPane_ = createSplitPane(
prefs.getInt(MAIN_FRAME_DIVIDER_POS, 200));
getContentPane().add(splitPane_);
createTopPanelWidgets((JPanel) splitPane_.getComponent(0));
metadataPanel_ = createMetadataPanel((JPanel) splitPane_.getComponent(1));
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setupWindowHandlers();
EventManager.register(this);
// Add our own keyboard manager that handles Micro-Manager shortcuts
MMKeyDispatcher mmKD = new MMKeyDispatcher();
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(mmKD);
DropTarget dropTarget = new DropTarget(this, new DragDropUtil());
setVisible(true);
}
private void setupWindowHandlers() {
// add window listeners
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent event) {
studio_.closeSequence(false);
}
});
}
public void loadApplicationPrefs(Preferences prefs,
boolean shouldCloseOnExit) {
int x = prefs.getInt(MAIN_FRAME_X, 100);
int y = prefs.getInt(MAIN_FRAME_Y, 100);
int width = prefs.getInt(MAIN_FRAME_WIDTH, 644);
int height = prefs.getInt(MAIN_FRAME_HEIGHT, 570);
setBounds(x, y, width, height);
setExitStrategy(shouldCloseOnExit);
}
public void paintToFront() {
toFront();
paint(getGraphics());
}
public void initializeConfigPad() {
configPad_.setCore(core_);
configPad_.setParentGUI(studio_);
configPadButtonPanel_.setCore(core_);
}
private static JLabel createLabel(String text, boolean big,
JPanel parentPanel, int west, int north, int east, int south) {
final JLabel label = new JLabel();
label.setFont(new Font("Arial",
big ? Font.BOLD : Font.PLAIN,
big ? 11 : 10));
label.setText(text);
GUIUtils.addWithEdges(parentPanel, label, west, north, east, south);
return label;
}
private void createActiveShutterChooser(JPanel topPanel) {
createLabel("Shutter", false, topPanel, 111, 73, 158, 86);
shutterComboBox_ = new JComboBox();
shutterComboBox_.setName("Shutter");
shutterComboBox_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
try {
if (shutterComboBox_.getSelectedItem() != null) {
core_.setShutterDevice((String) shutterComboBox_.getSelectedItem());
}
} catch (Exception e) {
ReportingUtils.showError(e);
}
}
});
GUIUtils.addWithEdges(topPanel, shutterComboBox_, 170, 70, 275, 92);
}
private void createBinningChooser(JPanel topPanel) {
createLabel("Binning", false, topPanel, 111, 43, 199, 64);
comboBinning_ = new JComboBox();
comboBinning_.setName("Binning");
comboBinning_.setFont(defaultFont_);
comboBinning_.setMaximumRowCount(4);
comboBinning_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
studio_.changeBinning();
}
});
GUIUtils.addWithEdges(topPanel, comboBinning_, 200, 43, 275, 66);
}
private void createExposureField(JPanel topPanel) {
createLabel("Exposure [ms]", false, topPanel, 111, 23, 198, 39);
textFieldExp_ = new JTextField();
textFieldExp_.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent fe) {
studio_.setExposure();
}
});
textFieldExp_.setFont(defaultFont_);
textFieldExp_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
studio_.setExposure();
}
});
GUIUtils.addWithEdges(topPanel, textFieldExp_, 203, 21, 276, 40);
}
private void createShutterControls(JPanel topPanel) {
autoShutterCheckBox_ = new JCheckBox();
autoShutterCheckBox_.setFont(defaultFont_);
autoShutterCheckBox_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
studio_.toggleAutoShutter();
}
});
autoShutterCheckBox_.setIconTextGap(6);
autoShutterCheckBox_.setHorizontalTextPosition(SwingConstants.LEADING);
autoShutterCheckBox_.setText("Auto shutter");
GUIUtils.addWithEdges(topPanel, autoShutterCheckBox_, 107, 96, 199, 119);
toggleShutterButton_ = (JToggleButton) GUIUtils.createButton(true,
"toggleShutterButton", "Open", "Open/close the shutter",
new Runnable() {
@Override
public void run() {
toggleShutter();
}
},
null, topPanel, 203, 96, 275, 117);
}
private void createCameraSettingsWidgets(JPanel topPanel) {
createLabel("Camera settings", true, topPanel, 109, 2, 211, 22);
createExposureField(topPanel);
createBinningChooser(topPanel);
createActiveShutterChooser(topPanel);
createShutterControls(topPanel);
}
private void createConfigurationControls(JPanel topPanel) {
createLabel("Configuration settings", true, topPanel, 280, 2, 430, 22);
saveConfigButton_ = (JButton) GUIUtils.createButton(false,
"saveConfigureButton", "Save",
"Save current presets to the configuration file",
new Runnable() {
@Override
public void run() {
studio_.saveConfigPresets();
}
},
null, topPanel, -80, 2, -5, 20);
configPad_ = new ConfigGroupPad();
configPadButtonPanel_ = new ConfigPadButtonPanel();
configPadButtonPanel_.setConfigPad(configPad_);
configPadButtonPanel_.setGUI(studio_);
configPad_.setFont(defaultFont_);
GUIUtils.addWithEdges(topPanel, configPad_, 280, 21, -4, -44);
GUIUtils.addWithEdges(topPanel, configPadButtonPanel_, 280, -40, -4, -20);
}
/**
* Generate the "Snap", "Live", "Snap to album", "MDA", and "Refresh"
* buttons.
*/
private void createCommonActionButtons(JPanel topPanel) {
snapButton_ = (JButton) GUIUtils.createButton(false, "Snap", "Snap",
"Snap single image",
new Runnable() {
@Override
public void run() {
studio_.doSnap();
}
},
"camera.png", topPanel, 7, 4, 95, 25);
liveButton_ = (JToggleButton) GUIUtils.createButton(true,
"Live", "Live", "Continuous live view",
new Runnable() {
@Override
public void run() {
studio_.enableLiveMode(!studio_.isLiveModeOn());
}
},
"camera_go.png", topPanel, 7, 26, 95, 47);
GUIUtils.createButton(false, "Album", "Album",
"Acquire single frame and add to an album",
new Runnable() {
@Override
public void run() {
snapLiveManager_.snapAndAddToImage5D();
}
},
"camera_plus_arrow.png", topPanel, 7, 48, 95, 69);
GUIUtils.createButton(false,
"Multi-D Acq.", "Multi-D Acq.",
"Open multi-dimensional acquisition window",
new Runnable() {
@Override
public void run() {
studio_.openAcqControlDialog();
}
},
"film.png", topPanel, 7, 70, 95, 91);
GUIUtils.createButton(false, "Refresh", "Refresh",
"Refresh all GUI controls directly from the hardware",
new Runnable() {
@Override
public void run() {
core_.updateSystemStateCache();
studio_.updateGUI(true);
}
},
"arrow_refresh.png", topPanel, 7, 92, 95, 113);
}
private static MetadataPanel createMetadataPanel(JPanel bottomPanel) {
MetadataPanel metadataPanel = new MetadataPanel();
GUIUtils.addWithEdges(bottomPanel, metadataPanel, 0, 0, 0, 0);
metadataPanel.setBorder(BorderFactory.createEmptyBorder());
return metadataPanel;
}
private void createPleaLabel(JPanel topPanel) {
JLabel citePleaLabel = new JLabel("<html>Please <a href=\"http://micro-manager.org\">cite Micro-Manager</a> so funding will continue!</html>");
citePleaLabel.setFont(new Font("Arial", Font.PLAIN, 11));
GUIUtils.addWithEdges(topPanel, citePleaLabel, 7, 119, 270, 139);
// When users click on the citation plea, we spawn a new thread to send
// their browser to the MM wiki.
citePleaLabel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
new Thread(GUIUtils.makeURLRunnable("https://micro-manager.org/wiki/Citing_Micro-Manager")).start();
}
});
}
private JSplitPane createSplitPane(int dividerPos) {
JPanel topPanel = new JPanel();
JPanel bottomPanel = new JPanel();
topPanel.setLayout(new SpringLayout());
topPanel.setMinimumSize(new Dimension(580, 195));
bottomPanel.setLayout(new SpringLayout());
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true,
topPanel, bottomPanel);
splitPane.setBorder(BorderFactory.createEmptyBorder());
splitPane.setDividerLocation(dividerPos);
splitPane.setResizeWeight(0.0);
return splitPane;
}
private void createTopPanelWidgets(JPanel topPanel) {
createCommonActionButtons(topPanel);
createCameraSettingsWidgets(topPanel);
createPleaLabel(topPanel);
createUtilityButtons(topPanel);
createConfigurationControls(topPanel);
labelImageDimensions_ = createLabel("", false, topPanel, 5, -20, 0, 0);
}
private void createUtilityButtons(JPanel topPanel) {
// ROI
createLabel("ROI", true, topPanel, 8, 140, 71, 154);
setRoiButton_ = GUIUtils.createButton(false, "setRoiButton", null,
"Set Region Of Interest to selected rectangle",
new Runnable() {
@Override
public void run() {
studio_.setROI();
}
},
"shape_handles.png", topPanel, 7, 154, 37, 174);
clearRoiButton_ = GUIUtils.createButton(false, "clearRoiButton", null,
"Reset Region of Interest to full frame",
new Runnable() {
@Override
public void run() {
studio_.clearROI();
}
},
"arrow_out.png", topPanel, 40, 154, 70, 174);
// Zoom
createLabel("Zoom", true, topPanel, 81, 140, 139, 154);
GUIUtils.createButton(false, "zoomInButton", null,
"Zoom in",
new Runnable() {
@Override
public void run() {
zoomIn();
}
},
"zoom_in.png", topPanel, 80, 154, 110, 174);
GUIUtils.createButton(false, "zoomOutButton", null,
"Zoom out",
new Runnable() {
@Override
public void run() {
zoomOut();
}
},
"zoom_out.png", topPanel, 113, 154, 143, 174);
// Line profile.
createLabel("Profile", true, topPanel, 154, 140, 217, 154);
GUIUtils.createButton(false, "lineProfileButton", null,
"Open line profile window (requires line selection)",
new Runnable() {
@Override
public void run() {
studio_.openLineProfileWindow();
}
},
"chart_curve.png", topPanel, 153, 154, 183, 174);
// Autofocus
createLabel("Autofocus", true, topPanel, 194, 140, 276, 154);
autofocusNowButton_ = (JButton) GUIUtils.createButton(false,
"autofocusNowButton", null, "Autofocus now",
new Runnable() {
@Override
public void run() {
studio_.autofocusNow();
}
},
"find.png", topPanel, 193, 154, 223, 174);
autofocusConfigureButton_ = (JButton) GUIUtils.createButton(false,
"autofocusConfigureButton", null,
"Set autofocus options",
new Runnable() {
@Override
public void run() {
studio_.showAutofocusDialog();
}
},
"wrench_orange.png", topPanel, 226, 154, 256, 174);
}
public void updateTitle(String configFile) {
this.setTitle(MICRO_MANAGER_TITLE + " " + MMVersion.VERSION_STRING + " - " + configFile);
}
public final void setExitStrategy(boolean closeOnExit) {
if (closeOnExit) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
else {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
protected void setConfigSaveButtonStatus(boolean changed) {
saveConfigButton_.setEnabled(changed);
}
/**
* Updates Status line in main window.
* @param text text to be shown
*/
public void updateInfoDisplay(String text) {
labelImageDimensions_.setText(text);
}
public void setShutterButton(boolean state) {
if (state) {
toggleShutterButton_.setText("Close");
} else {
toggleShutterButton_.setText("Open");
}
}
public void toggleShutter() {
try {
if (!toggleShutterButton_.isEnabled())
return;
toggleShutterButton_.requestFocusInWindow();
if (toggleShutterButton_.getText().equals("Open")) {
setShutterButton(true);
core_.setShutterOpen(true);
} else {
core_.setShutterOpen(false);
setShutterButton(false);
}
} catch (Exception e1) {
ReportingUtils.showError(e1);
}
}
public void toggleAutoShutter(boolean enabled) {
StaticInfo.shutterLabel_ = core_.getShutterDevice();
if (StaticInfo.shutterLabel_.length() == 0) {
setToggleShutterButtonEnabled(false);
} else {
setToggleShutterButtonEnabled(enabled);
try {
setShutterButton(core_.getShutterOpen());
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
if (!enabled) {
toggleShutterButton_.setSelected(false);
}
}
}
@Override
public void liveModeEnabled(boolean isEnabled) {
autoShutterCheckBox_.setEnabled(!isEnabled);
if (core_.getAutoShutter()) {
toggleShutterButton_.setText(isEnabled ? "Close" : "Open" );
}
snapButton_.setEnabled(!isEnabled);
liveButton_.setIcon(isEnabled ? SwingResourceManager.getIcon(MainFrame.class,
"/org/micromanager/icons/cancel.png")
: SwingResourceManager.getIcon(MainFrame.class,
"/org/micromanager/icons/camera_go.png"));
liveButton_.setSelected(false);
liveButton_.setText(isEnabled ? "Stop Live" : "Live");
}
public void initializeShutterGUI(String[] items) {
GUIUtils.replaceComboContents(shutterComboBox_, items);
String activeShutter = core_.getShutterDevice();
if (activeShutter != null) {
shutterComboBox_.setSelectedItem(activeShutter);
} else {
shutterComboBox_.setSelectedItem("");
}
}
public void updateAutofocusButtons(boolean isEnabled) {
autofocusConfigureButton_.setEnabled(isEnabled);
autofocusNowButton_.setEnabled(isEnabled);
}
@Subscribe
public void onConfigGroupChanged(ConfigGroupChangedEvent event) {
configPad_.refreshGroup(event.getGroupName(), event.getNewConfig());
}
private List<String> sortBinningItems(final List<String> items) {
ArrayList<Integer> binSizes = new ArrayList<Integer>();
// Check if all items are valid integers
for (String s : items) {
Integer i;
try {
i = Integer.valueOf(s);
}
catch (NumberFormatException e) {
// Not a number; give up sorting and return original list
return items;
}
binSizes.add(i);
}
Collections.sort(binSizes);
ArrayList<String> ret = new ArrayList<String>();
for (Integer i : binSizes) {
ret.add(i.toString());
}
return ret;
}
public void configureBinningComboForCamera(String cameraLabel) {
ActionListener[] listeners;
if (comboBinning_.getItemCount() > 0) {
comboBinning_.removeAllItems();
}
try {
StrVector binSizes = core_.getAllowedPropertyValues(
cameraLabel, MMCoreJ.getG_Keyword_Binning());
List<String> items = sortBinningItems(Arrays.asList(binSizes.toArray()));
listeners = comboBinning_.getActionListeners();
for (int i = 0; i < listeners.length; i++) {
comboBinning_.removeActionListener(listeners[i]);
}
for (String item : items) {
comboBinning_.addItem(item);
}
comboBinning_.setMaximumRowCount((int) items.size());
if (items.isEmpty()) {
comboBinning_.setEditable(true);
} else {
comboBinning_.setEditable(false);
}
for (int i = 0; i < listeners.length; i++) {
comboBinning_.addActionListener(listeners[i]);
}
} catch (Exception e) {
// getAllowedPropertyValues probably failed.
ReportingUtils.showError(e);
}
}
public void setBinSize(String binSize) {
GUIUtils.setComboSelection(comboBinning_, binSize);
}
/**
* Return the current selection from the comboBinning_ menu, or null.
* @return bin setting in UI as a String
*/
public String getBinMode() {
Object item = comboBinning_.getSelectedItem();
if (item != null) {
return item.toString();
}
return (String) null;
}
public void setAutoShutterSelected(boolean isSelected) {
autoShutterCheckBox_.setSelected(isSelected);
}
public void setToggleShutterButtonEnabled(boolean isEnabled) {
toggleShutterButton_.setEnabled(isEnabled);
}
public void setShutterComboSelection(String activeShutter) {
shutterComboBox_.setSelectedItem(activeShutter);
if (activeShutter.equals("") || core_.getAutoShutter()) {
setToggleShutterButtonEnabled(false);
} else {
setToggleShutterButtonEnabled(true);
}
}
public boolean getAutoShutterChecked() {
return autoShutterCheckBox_.isSelected();
}
public ConfigGroupPad getConfigPad() {
return configPad_;
}
/**
* Save our settings to the provided Preferences object.
* @param prefs local preferences to be saved
*/
public void savePrefs(Preferences prefs) {
Rectangle r = getBounds();
prefs.putInt(MAIN_FRAME_X, r.x);
prefs.putInt(MAIN_FRAME_Y, r.y);
prefs.putInt(MAIN_FRAME_WIDTH, r.width);
prefs.putInt(MAIN_FRAME_HEIGHT, r.height);
prefs.putInt(MAIN_FRAME_DIVIDER_POS, splitPane_.getDividerLocation());
prefs.put(MAIN_EXPOSURE, textFieldExp_.getText());
}
public void setDisplayedExposureTime(double exposure) {
textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure));
}
public double getDisplayedExposureTime() {
try {
return NumberUtils.displayStringToDouble(textFieldExp_.getText());
} catch (ParseException e) {
ReportingUtils.logError(e, "Couldn't convert displayed exposure time to double");
}
return -1;
}
public void enableRoiButtons(final boolean enabled) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setRoiButton_.setEnabled(enabled);
clearRoiButton_.setEnabled(enabled);
}
});
}
public MetadataPanel getMetadataPanel() {
return metadataPanel_;
}
protected void zoomOut() {
ImageWindow curWin = WindowManager.getCurrentWindow();
if (curWin != null) {
ImageCanvas canvas = curWin.getCanvas();
Rectangle r = canvas.getBounds();
canvas.zoomOut(r.width / 2, r.height / 2);
// Fix the window title, which IJ just mangled.
VirtualAcquisitionDisplay display = VirtualAcquisitionDisplay.getDisplay(curWin.getImagePlus());
if (display != null) {
display.updateWindowTitleAndStatus();
}
}
}
protected void zoomIn() {
ImageWindow curWin = WindowManager.getCurrentWindow();
if (curWin != null) {
ImageCanvas canvas = curWin.getCanvas();
Rectangle r = canvas.getBounds();
canvas.zoomIn(r.width / 2, r.height / 2);
// Fix the window title, which IJ just mangled.
VirtualAcquisitionDisplay display = VirtualAcquisitionDisplay.getDisplay(curWin.getImagePlus());
if (display != null) {
display.updateWindowTitleAndStatus();
}
}
}
}
|
package com.google.maps.android.utils.demo;
import android.graphics.Color;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.TileOverlay;
import com.google.android.gms.maps.model.TileOverlayOptions;
import com.google.maps.android.heatmaps.Gradient;
import com.google.maps.android.heatmaps.HeatmapTileProvider;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
/**
* A demo of the Heatmaps library. Demonstrates how the HeatmapTileProvider can be used to create
* a colored map overlay that visualises many points of weighted importance/intensity, with
* different colors representing areas of high and low concentration/combined intensity of points.
*/
public class HeatmapsDemoActivity extends BaseDemoActivity {
/**
* Alternative radius for convolution
*/
private static final int ALT_HEATMAP_RADIUS = 10;
/**
* Alternative opacity of heatmap overlay
*/
private static final double ALT_HEATMAP_OPACITY = 0.4;
/**
* Alternative heatmap gradient (blue -> red)
* Copied from Javascript version
*/
private static final int[] ALT_HEATMAP_GRADIENT_COLORS = {
Color.argb(0, 0, 255, 255),// transparent
Color.argb(255 / 3 * 2, 0, 255, 255),
Color.rgb(0, 191, 255),
Color.rgb(0, 0, 127),
Color.rgb(255, 0, 0)
};
public static final float[] ALT_HEATMAP_GRADIENT_START_POINTS = {
0.0f, 0.10f, 0.20f, 0.60f, 1.0f
};
public static final Gradient ALT_HEATMAP_GRADIENT = new Gradient(ALT_HEATMAP_GRADIENT_COLORS, ALT_HEATMAP_GRADIENT_START_POINTS);
private HeatmapTileProvider mProvider;
private TileOverlay mOverlay;
private boolean defaultGradient = true;
private boolean defaultRadius = true;
private boolean defaultOpacity = true;
/**
* Maps name of data set to data (list of WeightedLatLngs)
* Each WeightedLatLng contains a LatLng as well as corresponding intensity value (which
* represents "importance" of this LatLng) - see the class for more details
*/
private HashMap<String, ArrayList<LatLng>> mLists =
new HashMap<String, ArrayList<LatLng>>();
@Override
protected int getLayoutId() {
return R.layout.heatmaps_demo;
}
@Override
protected void startDemo() {
getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-25, 135), 4));
// Set up the spinner/dropdown list
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.heatmaps_datasets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new SpinnerActivity());
try {
mLists.put(getString(R.string.police_stations), readItems(R.raw.police));
mLists.put(getString(R.string.medicare), readItems(R.raw.medicare));
} catch (JSONException e) {
Toast.makeText(this, "Problem reading list of markers.", Toast.LENGTH_LONG).show();
}
// Make the handler deal with the map
// Input: list of WeightedLatLngs, minimum and maximum zoom levels to calculate custom
// intensity from, and the map to draw the heatmap on
// radius, gradient and opacity not specified, so default are used
}
public void changeRadius(View view) {
if (defaultRadius) {
mProvider.setRadius(ALT_HEATMAP_RADIUS);
} else {
mProvider.setRadius(HeatmapTileProvider.DEFAULT_RADIUS);
}
mOverlay.clearTileCache();
defaultRadius = !defaultRadius;
}
public void changeGradient(View view) {
if (defaultGradient) {
mProvider.setGradient(ALT_HEATMAP_GRADIENT);
} else {
mProvider.setGradient(HeatmapTileProvider.DEFAULT_GRADIENT);
}
mOverlay.clearTileCache();
defaultGradient = !defaultGradient;
}
public void changeOpacity(View view) {
if (defaultOpacity) {
mProvider.setOpacity(ALT_HEATMAP_OPACITY);
} else {
mProvider.setOpacity(HeatmapTileProvider.DEFAULT_OPACITY);
}
mOverlay.clearTileCache();
defaultOpacity = !defaultOpacity;
}
// Dealing with spinner choices
public class SpinnerActivity implements AdapterView.OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
String dataset = parent.getItemAtPosition(pos).toString();
// Check if need to instantiate (avoid setData etc twice)
if (mProvider == null) {
mProvider = new HeatmapTileProvider.Builder().data(
mLists.get(getString(R.string.police_stations))).build();
mOverlay = getMap().addTileOverlay(new TileOverlayOptions().tileProvider(mProvider));
} else {
mProvider.setData(mLists.get(dataset));
mOverlay.clearTileCache();
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
// Datasets:
private ArrayList<LatLng> readItems(int resource) throws JSONException {
ArrayList<LatLng> list = new ArrayList<LatLng>();
InputStream inputStream = getResources().openRawResource(resource);
String json = new Scanner(inputStream).useDelimiter("\\A").next();
JSONArray array = new JSONArray(json);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
double lat = object.getDouble("lat");
double lng = object.getDouble("lng");
list.add(new LatLng(lat, lng));
}
return list;
}
}
|
package nl.mpi.kinnate.gedcomimport;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import javax.swing.JProgressBar;
import javax.swing.JTextArea;
import nl.mpi.arbil.userstorage.SessionStorage;
import nl.mpi.kinnate.kindata.DataTypes.RelationType;
import nl.mpi.kinnate.kindata.EntityData;
import nl.mpi.kinnate.kindata.EntityDate;
import nl.mpi.kinnate.kindata.EntityDateException;
import nl.mpi.kinnate.kindocument.EntityDocument;
import nl.mpi.kinnate.kindocument.ImportTranslator;
import nl.mpi.kinnate.ui.entityprofiles.ProfileRecord;
import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier;
public class GedcomImporter extends EntityImporter implements GenericImporter {
public GedcomImporter(JProgressBar progressBarLocal, JTextArea importTextAreaLocal, boolean overwriteExistingLocal, SessionStorage sessionStorage) {
super(progressBarLocal, importTextAreaLocal, overwriteExistingLocal, sessionStorage);
}
@Override
public boolean canImport(String inputFileString) {
return (inputFileString.toLowerCase().endsWith(".ged") || inputFileString.toLowerCase().endsWith(".gedcom"));
}
class SocialMemberElement {
public SocialMemberElement(String typeString, EntityData memberEntity) {
this.typeString = typeString;
this.memberEntity = memberEntity;
}
String typeString;
EntityData memberEntity;
}
protected ImportTranslator getImportTranslator() {
ImportTranslator importTranslator = new ImportTranslator(true);
// todo: add the translator values if required
importTranslator.addTranslationEntry("SEX", "F", "Gender", "Female");
importTranslator.addTranslationEntry("SEX", "M", "Gender", "Male");
importTranslator.addTranslationEntry("NAME", null, "Name", null);
importTranslator.addTranslationEntry("chro", null, "Chromosome", null);
return importTranslator;
}
protected ImportLineStructure getImportLineStructure(String lineString, ArrayList<String> gedcomLevelStrings) throws ImportException {
return new GedcomLineStructure(lineString, gedcomLevelStrings);
}
@Override
public UniqueIdentifier[] importFile(InputStreamReader inputStreamReader, String profileId) throws IOException, ImportException {
ArrayList<UniqueIdentifier> createdNodes = new ArrayList<UniqueIdentifier>();
HashMap<UniqueIdentifier, ArrayList<SocialMemberElement>> socialGroupRoleMap = new HashMap<UniqueIdentifier, ArrayList<SocialMemberElement>>(); // GroupID: @XX@, RoleType: WIFE HUSB CHIL, EntityData
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
ImportTranslator importTranslator = getImportTranslator();
String strLine;
ArrayList<String> gedcomLevelStrings = new ArrayList<String>();
EntityDocument currentEntity = null;
EntityDocument fileHeaderEntity = null;
boolean skipFileEntity = false;
String currentEntityType = "";
while ((strLine = bufferedReader.readLine()) != null) {
if (skipFileEntity) {
skipFileEntity = false;
while ((strLine = bufferedReader.readLine()) != null) {
if (strLine.startsWith("0")) {
break;
}
}
}
ImportLineStructure lineStructure = getImportLineStructure(strLine, gedcomLevelStrings);
if (lineStructure.isIncompleteLine()) {
appendToTaskOutput("Incomplete line found");
} else {
System.out.println(strLine);
// System.out.println("gedcomLevelString: " + gedcomLevelStrings);
// appendToTaskOutput(importTextArea, strLine);
boolean lastFieldContinued = false;
if (lineStructure.isContinueLineBreak()) {
// todo: if the previous field is null this should be caught and handled as an error in the source file
currentEntity.appendValueToLast(currentEntityType, "\n" + lineStructure.getEscapedLineContents());
lastFieldContinued = true;
} else if (lineStructure.isContinueLine()) {
// todo: if the previous field is null this should be caught and handled as an error in the source file
currentEntity.appendValueToLast(currentEntityType, lineStructure.getEscapedLineContents());
lastFieldContinued = true;
}
if (lastFieldContinued == false) {
if (lineStructure.getGedcomLevel() == 0) {
if (lineStructure.isEndOfFileMarker()) {
appendToTaskOutput("End of file found");
} else {
// set the profile from the entity type
// todo: this profile setting is failing because entities are created via links from other entities without the required information
String typeString = lineStructure.getProfileForEntityType(profileId, ProfileRecord.getDefaultImportProfile().profileId);
currentEntity = getEntityDocument(createdNodes, typeString, lineStructure.getCurrentID(), importTranslator);
currentEntityType = lineStructure.entityType;
if (lineStructure.isFileHeader()) {
fileHeaderEntity = currentEntity;
// because the schema specifies 1:1 of both head and entity we find rather than create the head and entity nodes
// appendToTaskOutput("Reading Gedcom Header");
// todo: maybe replace this "Gedcom Header" string with the file name of the import file
currentEntity.insertValue("Type", "Imported File Header"); // inserting a value will only add that value once, if the value already exists then no action is taken
if (lineStructure.hasLineContents()) {
// throw new ImportException("Unexpeted header parameter: " + lineStructure.getCurrentName() + " " + lineStructure.getLineContents());
// TIP files provide comments in the header and they are adde here
currentEntity.insertValue(lineStructure.getCurrentName(), lineStructure.getLineContents().trim());
} else {
// currentEntity.appendValue(lineStructure.getCurrentName(), null, lineStructure.getGedcomLevel());
}
} else {
fileHeaderEntity.entityData.addRelatedNode(currentEntity.entityData, RelationType.other, null, null, null, "source");
if (lineStructure.getEntityType() != null) {
currentEntity.insertValue("Type", lineStructure.getEntityType());
}
if (lineStructure.hasLineContents()) {
currentEntity.insertValue(lineStructure.getCurrentName(), lineStructure.getLineContents());
}
}
}
while (lineStructure.hasCurrentField()) {
if (lineStructure.hasLineContents()) {
currentEntity.insertValue(lineStructure.getCurrentName(), lineStructure.getLineContents());
}
lineStructure.moveToNextField();
} // end skip overwrite
} else {
while (lineStructure.hasCurrentField()) {
// if the current line has a value then enter it into the node
if (!lineStructure.hasLineContents()) {
currentEntity.appendValue(lineStructure.getCurrentName(), null, lineStructure.getGedcomLevel());
} else {
boolean notConsumed = true;
if (gedcomLevelStrings.size() == 3) {
if (gedcomLevelStrings.get(2).equals("DATE")) {
if (gedcomLevelStrings.get(1).equals("BIRT") || gedcomLevelStrings.get(1).equals("DEAT")) {
String dateText = lineStructure.getLineContents().trim();
String qualifierString = null;
String yearString = null;
String monthString = null;
String dayString = null;
for (String prefixString : new String[]{"ABT", "BEF", "AFT"}) {
if (dateText.startsWith(prefixString)) {
qualifierString = prefixString.toLowerCase();
// appendToTaskOutput("Unsupported Date Type: " + dateText);
dateText = dateText.substring(prefixString.length()).trim();
}
}
SimpleDateFormat formatter;
try {
if (dateText.matches("[0-9]{1,4}")) {
while (dateText.length() < 4) {
// make sure that 812 has four digits like 0812
dateText = "0" + dateText;
}
yearString = dateText;
// formatter = new SimpleDateFormat("yyyy");
} else if (dateText.matches("[a-zA-Z]{3} [0-9]{4}")) {
formatter = new SimpleDateFormat("MMM yyyy");
Date parsedDate = formatter.parse(dateText);
monthString = new SimpleDateFormat("MM").format(parsedDate);
yearString = new SimpleDateFormat("yyyy").format(parsedDate);
} else {
formatter = new SimpleDateFormat("dd MMM yyyy");
Date parsedDate = formatter.parse(dateText);
dayString = new SimpleDateFormat("dd").format(parsedDate);
monthString = new SimpleDateFormat("MM").format(parsedDate);
yearString = new SimpleDateFormat("yyyy").format(parsedDate);
}
EntityDate entityDate = new EntityDate(yearString, monthString, dayString, qualifierString);
if (gedcomLevelStrings.get(1).equals("BIRT")) {
currentEntity.insertValue("DateOfBirth", entityDate.getDateString());
} else {
currentEntity.insertValue("DateOfDeath", entityDate.getDateString());
}
notConsumed = false;
} catch (ParseException exception) {
System.out.println(exception.getMessage());
appendToTaskOutput("Failed to parse date: " + strLine);
appendToTaskOutput("The date data will been imported anyway and can be corrected manually later.");
} catch (EntityDateException exception) {
System.out.println(exception.getMessage());
appendToTaskOutput("Failed to parse date: " + strLine + " " + exception.getMessage());
appendToTaskOutput("The date data will been imported anyway and can be corrected manually later.");
}
}
}
}
if (gedcomLevelStrings.size() == 2) {
if (gedcomLevelStrings.get(1).equals("SEX") || gedcomLevelStrings.get(1).equals("NAME")) {
if (lineStructure.getGedcomLevel() == 1) {
currentEntity.insertValue(lineStructure.getCurrentName(), lineStructure.getLineContents());
} else {
currentEntity.appendValue(lineStructure.getCurrentName(), lineStructure.getLineContents(), lineStructure.getGedcomLevel());
}
notConsumed = false;
}
}
if (gedcomLevelStrings.size() == 2) {
if (gedcomLevelStrings.get(1).equals("chro")) {
if (lineStructure.getGedcomLevel() == 1) {
currentEntity.insertValue(lineStructure.getCurrentName(), lineStructure.getLineContents());
notConsumed = false;
}
}
}
if (gedcomLevelStrings.get(gedcomLevelStrings.size() - 1).equals("FILE")) {
// todo: check if the FILE value can contain a path or just the file name and handle the path correctly if required
// todo: copy the file or not according to user options
if (lineStructure.getLineContents().toLowerCase().startsWith("mailto:")) {
currentEntity.insertValue("mailto", lineStructure.getLineContents()); // todo: check that this is not already inserted
} else {
try {
URI resolvedUri;
if ("jar".equals(inputFileUri.getScheme())) { // "jar:file:"
// when the application is running from a jar file the uri resolve fails as designed by Sun, also we do not include the media files in the jar, so for sample files we must replace the uri with the documentation uri example.net
resolvedUri = URI.create("http://example.net/example/files/not/included/demo").resolve(lineStructure.getLineContents());
} else {
resolvedUri = inputFileUri.resolve(lineStructure.getLineContents());
}
currentEntity.entityData.addArchiveLink(resolvedUri);
notConsumed = false;
} catch (java.lang.IllegalArgumentException exception) {
appendToTaskOutput("Unsupported File Path: " + lineStructure.getLineContents());
}
}
}
// create the socal link node when required from gedcom file format
if (lineStructure.isRelation()) {
// todo: move this into the gedcom line structure class and use lineStructure.getRelationList() to later retrieve the list
// appendToTaskOutput("--> adding social relation");
// here the following five relation types are mapped to the correct relation types after this the association is cretaed and later the indigiduals are linked with sanguine relations
if (lineStructure.getCurrentName().equals("FAMS") || lineStructure.getCurrentName().equals("FAMC") || lineStructure.getCurrentName().equals("HUSB") || lineStructure.getCurrentName().equals("WIFE") || lineStructure.getCurrentName().equals("CHIL")) {
UniqueIdentifier socialGroupIdentifier;
EntityData socialGroupMember;
if (lineStructure.getCurrentName().equals("FAMS") || lineStructure.getCurrentName().equals("FAMC")) {
socialGroupIdentifier = getEntityDocument(createdNodes, profileId, lineStructure.getLineContents(), importTranslator).entityData.getUniqueIdentifier();
socialGroupMember = currentEntity.entityData;
} else {
socialGroupIdentifier = currentEntity.entityData.getUniqueIdentifier();
socialGroupMember = getEntityDocument(createdNodes, profileId, lineStructure.getLineContents(), importTranslator).entityData;
}
if (!socialGroupRoleMap.containsKey(socialGroupIdentifier)) {
socialGroupRoleMap.put(socialGroupIdentifier, new ArrayList<SocialMemberElement>());
}
socialGroupRoleMap.get(socialGroupIdentifier).add(new SocialMemberElement(lineStructure.getCurrentName(), socialGroupMember));
// the fam relations to consist of associations with implied sanuine links to the related entities, these sangine relations are handled later when all members are known
currentEntity.entityData.addRelatedNode(getEntityDocument(createdNodes, profileId, lineStructure.getLineContents(), importTranslator).entityData, RelationType.other, null, null, null, lineStructure.getCurrentName());
notConsumed = false;
} else {
// todo: check this change
// capture the custom types from .kinoath format export files
String currentName = lineStructure.getCurrentName();
String customType = null;
String dcrString = null;
RelationType targetRelation = RelationType.other;
String[] currentNameParts = currentName.split(":");
try {
if (currentNameParts.length > 0) {
targetRelation = RelationType.valueOf(currentNameParts[0]);
}
} catch (IllegalArgumentException exception) {
appendToTaskOutput("Unsupported Relation Type: " + currentName);
}
if (currentNameParts.length == 3) {
customType = currentNameParts[1];
dcrString = currentNameParts[2];
}
currentEntity.entityData.addRelatedNode(getEntityDocument(createdNodes, profileId, lineStructure.getLineContents(), importTranslator).entityData, targetRelation, null, null, dcrString, customType);
notConsumed = false;
}
}
if (notConsumed) {
// any unprocessed elements should now be added as they are into the metadata
// any gedcom chars should be escaped such as @@ etc.
currentEntity.appendValue(lineStructure.getCurrentName(), lineStructure.getEscapedLineContents(), lineStructure.getGedcomLevel());
}
}
lineStructure.moveToNextField();
}
}
for (ImportLineStructure.RelationEntry relationEntry : lineStructure.getRelationList()) {
getEntityDocument(createdNodes, profileId, relationEntry.egoIdString, importTranslator).entityData.addRelatedNode(getEntityDocument(createdNodes, profileId, relationEntry.alterIdString, importTranslator).entityData, relationEntry.relationType, null, null, null, relationEntry.customType);
}
}
super.incrementLineProgress();
}
}
for (ArrayList<SocialMemberElement> currentSocialGroup : socialGroupRoleMap.values()) {
for (SocialMemberElement outerMemberElement : currentSocialGroup) {
for (SocialMemberElement innerMemberElement : currentSocialGroup) {
if (!innerMemberElement.memberEntity.equals(outerMemberElement.memberEntity)) {
if (innerMemberElement.typeString.equals("FAMC") || innerMemberElement.typeString.equals("CHIL")) {
if (outerMemberElement.typeString.equals("FAMC") || outerMemberElement.typeString.equals("CHIL")) {
innerMemberElement.memberEntity.addRelatedNode(outerMemberElement.memberEntity, RelationType.sibling, null, null, null, null);
} else {
innerMemberElement.memberEntity.addRelatedNode(outerMemberElement.memberEntity, RelationType.ancestor, null, null, null, null);
}
} else {
if (outerMemberElement.typeString.equals("FAMC") || outerMemberElement.typeString.equals("CHIL")) {
innerMemberElement.memberEntity.addRelatedNode(outerMemberElement.memberEntity, RelationType.descendant, null, null, null, null);
} else {
innerMemberElement.memberEntity.addRelatedNode(outerMemberElement.memberEntity, RelationType.union, null, null, null, null);
}
}
// appendToTaskOutput("--> adding sanguine relation");
}
}
}
}
// add the header to all entities
saveAllDocuments();
return createdNodes.toArray(new UniqueIdentifier[]{});
}
}
|
package io.quarkus.maven;
import java.io.IOException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import io.quarkus.cli.commands.ListExtensions;
import io.quarkus.cli.commands.writer.FileProjectWriter;
import io.quarkus.generators.BuildTool;
/**
* List the available extensions.
* You can add one or several extensions in one go, with the 2 following mojos:
* {@code add-extensions} and {@code add-extension}.
* You can list all extension or just installable and choose simple or full format.
*/
@Mojo(name = "list-extensions", requiresProject = false)
public class ListExtensionsMojo extends AbstractMojo {
/**
* The Maven project which will define and configure the quarkus-maven-plugin
*/
@Parameter(defaultValue = "${project}")
protected MavenProject project;
/**
* List all extensions or just the installable.
*/
@Parameter(property = "quarkus.extension.all", alias = "quarkus.extension.all", defaultValue = "true")
protected boolean all;
/**
* Display in simplified format.
*/
@Parameter(property = "quarkus.extension.format", alias = "quarkus.extension.format", defaultValue = "simple")
protected String format;
/**
* Search filter on extension list. The format is based on Java Pattern.
*/
@Parameter(property = "searchPattern", alias = "quarkus.extension.searchPattern")
protected String searchPattern;
@Override
public void execute() throws MojoExecutionException {
try {
FileProjectWriter writer = null;
// Even when we have no pom, the project is not null, but it's set to `org.apache.maven:standalone-pom:1`
// So we need to also check for the project's file (the pom.xml file).
if (project != null && project.getFile() != null) {
writer = new FileProjectWriter(project.getBasedir());
}
new ListExtensions(writer, BuildTool.MAVEN).listExtensions(all, format,
searchPattern);
} catch (IOException e) {
throw new MojoExecutionException("Unable to list extensions", e);
}
}
}
|
package com.baidu.disconf.client;
import java.util.Timer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baidu.disconf.client.addons.properties.ReloadConfigurationMonitor;
import com.baidu.disconf.client.config.ConfigMgr;
import com.baidu.disconf.client.config.DisClientConfig;
import com.baidu.disconf.client.core.DisconfCoreFactory;
import com.baidu.disconf.client.core.DisconfCoreMgr;
import com.baidu.disconf.client.scan.ScanFactory;
import com.baidu.disconf.client.scan.ScanMgr;
import com.baidu.disconf.client.store.DisconfStoreProcessorFactory;
/**
* Disconf Client
*
* @author liaoqiqi
* @version 2014-5-23
*/
public class DisconfMgr {
protected static final Logger LOGGER = LoggerFactory.getLogger(DisconfMgr.class);
private static boolean isFirstInit = false;
private static boolean isSecondeInit = false;
private static ScanMgr scanMgr = null;
private static DisconfCoreMgr disconfCoreMgr = null;
// timer
private static Timer timer = new Timer();
/**
*
*
* @param scanPackage
*/
public synchronized static void start(String scanPackage) {
firstScan(scanPackage);
secondScan();
}
/**
*
*
* @param scanPackage
*/
public synchronized static void firstScan(String scanPackage) {
if (isFirstInit == true) {
LOGGER.info("DisConfMgr has been init, ignore........");
return;
}
try {
ConfigMgr.init();
if (DisClientConfig.getInstance().ENABLE_DISCONF == false) {
LOGGER.info("FIRST_SCAN, ENABLE_REMOTE_CONF==0, we use Local Configuration.");
return;
}
LOGGER.info("******************************* DISCONF START FIRST SCAN *******************************");
scanMgr = ScanFactory.getScanMgr();
scanMgr.firstScan(scanPackage);
// //Watch
disconfCoreMgr = DisconfCoreFactory.getDisconfCoreMgr();
disconfCoreMgr.process();
isFirstInit = true;
LOGGER.info("******************************* DISCONF END FIRST SCAN *******************************");
} catch (Exception e) {
LOGGER.error(e.toString(), e);
}
}
/**
* reloadable config file scan
*/
public synchronized static void reloadableScan(String filename) {
if (DisClientConfig.getInstance().ENABLE_DISCONF == false) {
return;
}
if (!isFirstInit) {
return;
}
try {
if (scanMgr != null) {
scanMgr.reloadableScan(filename);
}
if (disconfCoreMgr != null) {
disconfCoreMgr.processFile(filename);
}
LOGGER.debug("disconf reloadable file:" + filename);
} catch (Exception e) {
LOGGER.error(e.toString(), e);
}
}
/**
* ,
*
* @param
*/
public synchronized static void secondScan() {
if (DisClientConfig.getInstance().ENABLE_DISCONF == false) {
LOGGER.info("SECOND_SCAN, ENABLE_REMOTE_CONF==0, we use Local Configuration.");
return;
}
if (isFirstInit == false) {
LOGGER.info("should run First Scan before Second Scan.");
return;
}
if (isSecondeInit == true) {
LOGGER.info("should not run twice.");
return;
}
LOGGER.info("******************************* DISCONF START SECOND SCAN *******************************");
try {
scanMgr.secondScan();
disconfCoreMgr.inject2DisconfInstance();
} catch (Exception e) {
LOGGER.error(e.toString(), e);
}
isSecondeInit = true;
// start timer
startTimer();
LOGGER.info("Conf File Map: " + DisconfStoreProcessorFactory.getDisconfStoreFileProcessor().confToString());
LOGGER.info("Conf Item Map: " + DisconfStoreProcessorFactory.getDisconfStoreItemProcessor().confToString());
LOGGER.info("******************************* DISCONF END *******************************");
}
private static void startTimer() {
if (timer != null) {
timer.schedule(new ReloadConfigurationMonitor(), 2000, 1000);
} else {
LOGGER.error("timer is null");
}
}
/**
* @return void
*
* @Description:
* @author liaoqiqi
* @date 2013-6-14
*/
public synchronized static void close() {
try {
// disconfCoreMgr
LOGGER.info("******************************* DISCONF CLOSE *******************************");
if (disconfCoreMgr != null) {
disconfCoreMgr.release();
}
// timer
if (timer != null) {
timer.cancel();
timer = null;
}
// close, False,
isFirstInit = false;
isSecondeInit = false;
} catch (Exception e) {
LOGGER.error("DisConfMgr close Failed.", e);
}
}
}
|
package ai.elimu.appstore;
import android.app.Application;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import org.greenrobot.greendao.database.Database;
import ai.elimu.appstore.dao.CustomDaoMaster;
import ai.elimu.appstore.dao.DaoSession;
import ai.elimu.appstore.util.VersionHelper;
import timber.log.Timber;
public class BaseApplication extends Application {
public static final String PREF_APP_VERSION_CODE = "pref_app_version_code";
private DaoSession daoSession;
@Override
public void onCreate() {
super.onCreate();
// Log config
if (BuildConfig.DEBUG) {
// Log everything
Timber.plant(new Timber.DebugTree());
} else {
// Only log warnings and errors
Timber.plant(new Timber.Tree() {
@Override
protected void log(int priority, String tag, String message, Throwable throwable) {
if (priority == Log.WARN) {
Log.w(tag, message);
} else if (priority == Log.ERROR) {
Log.e(tag, message);
}
}
});
}
Timber.i("onCreate");
// greenDAO config
CustomDaoMaster.DevOpenHelper helper = new CustomDaoMaster.DevOpenHelper(this, "appstore-db");
Database db = helper.getWritableDb();
daoSession = new CustomDaoMaster(db).newSession();
// Check if the application's versionCode was upgraded
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int oldVersionCode = sharedPreferences.getInt(PREF_APP_VERSION_CODE, 0);
int newVersionCode = VersionHelper.getAppVersionCode(getApplicationContext());
if (oldVersionCode == 0) {
sharedPreferences.edit().putInt(PREF_APP_VERSION_CODE, newVersionCode).commit();
oldVersionCode = newVersionCode;
}
if (oldVersionCode < newVersionCode) {
Timber.i("Upgrading application from version " + oldVersionCode + " to " + newVersionCode);
// if (newVersionCode == ???) {
// // Put relevant tasks required for upgrading here
sharedPreferences.edit().putInt(PREF_APP_VERSION_CODE, newVersionCode).commit();
}
}
public DaoSession getDaoSession() {
return daoSession;
}
}
|
package com.mahali.gpslogger;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDeviceConnection;
import android.content.SharedPreferences;
import android.hardware.usb.UsbManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ToggleButton;
// Dropbox Includes
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.exception.DropboxException;
import com.dropbox.client2.session.AppKeyPair;
import com.dropbox.client2.session.Session;
// usbSerialForAndroid Includes
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.util.SerialInputOutputManager;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MainActivity extends ActionBarActivity {
private final String TAG = MainActivity.class.getSimpleName();
private UsbManager mUsbManager;
// The directory, in external storage, where mahali files will be stored
private final String mahali_directory = "mahali";
// The directory for the user's public documents directory.
File dirFile;
File sessFile;
BufferedOutputStream bufOS = null;
//for holding a reference to the file that we're currently reading from/writing to
// private File currentFile = null;
GPSSession mCurrentSession = null;
// List of the previous sessions found by the app
private ArrayList<GPSSession> sessionList = null;
//Required dropbox fields. Get app key, app secret, and access type from App Console on dropbox website. Make sure the key matches the key in AndroidManifest.xml!
private static final String APP_KEY = "2wmhe173wllfuwz";
private static final String APP_SECRET = "2h6bixl3fsaxx6m";
private static final Session.AccessType ACCESS_TYPE = Session.AccessType.APP_FOLDER;
private DropboxAPI<AndroidAuthSession> mDBApi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// TODO: pull a GPS recvr config file from dropbox
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
//Setup for DropBox connection
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
// See if we already have information about a dropbox connection stored in the shared preferences file
// SharedPreferences is a simple way to store basic key-value pairs. In this case we're using it to store dropbox configuration info
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
// get value of DB OAuth2AccessToken from shared preferences file. If it's not present, will take value "not_created"
String OAuth2AccessToken = sharedPref.getString("OAuth2AccessToken","not_authenticated");
Log.i(TAG,"OAuth2AccessToken at startup: "+OAuth2AccessToken);
// if we do already have info about a DB session stored, set that up
if (!OAuth2AccessToken.equals("not_authenticated")) {
Log.i(TAG,"authenticated, at startup: ");
//sets the OAuth2AccessToken, causing the mDBApi AndroidAuthSession object to be linked (and thus useable for dropbox transactions)
mDBApi.getSession().setOAuth2AccessToken(OAuth2AccessToken);
assert mDBApi.getSession().isLinked();
}
// TODO: make sure external storage is mounted/available see info here:
// http://developer.android.com/training/basics/data-storage/files.html#WriteExternalStorage
dirFile = new File(Environment.getExternalStorageDirectory(),mahali_directory);
if (!dirFile.mkdirs()) {
Log.i(TAG, "Directory not created - it already exists!");
}
Log.i(TAG, "Directory loaded: "+dirFile.exists());
sessionList = loadGPSSessions();
final ListView lv = (ListView) findViewById(R.id.sessionListView);
lv.setAdapter(new GPSSessionBaseAdaptor(this,sessionList));
// this method handles the selection of sessions from the list
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv.getItemAtPosition(position);
GPSSession fullObject = (GPSSession)o;
Log.i(TAG, "You have chosen: " + " " + fullObject.getFileName());
//TODO: implement a selection menu in front of these options...
// Try to upload the file to dropbox for the time being
sendToDB(fullObject.getAbsolutePath());
// Stub for deleting the file
deleteFile();
}
});
}
private void updateSessionListView() {
sessionList = loadGPSSessions();
// TODO: display meaningful message in ListView when there are no sessions found
final ListView lv = (ListView) findViewById(R.id.sessionListView);
lv.setAdapter(new GPSSessionBaseAdaptor(this,sessionList));
}
public void startSession(View v) throws IOException {
// Throws IOException when something goes wrong
// Probe for devices
final List<UsbSerialDriver> drivers =
UsbSerialProber.getDefaultProber().findAllDrivers(mUsbManager);
// Get the first port of the first driver
// TODO: probably shouldn't be hard-coded, but multiple cables are unlikely
try {
sPort = drivers.get(0).getPorts().get(0);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG,"Serial port not available");
throw new IOException("Serial port not available");
}
// Open a connection
UsbDeviceConnection connection = mUsbManager.openDevice(sPort.getDriver().getDevice());
if (connection == null) {
Log.e(TAG, "Error opening USB device");
throw new IOException("Error opening USB device");
}
try {
sPort.open(connection);
// TODO: port configuration should almost certainly be configuration
sPort.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
} catch (IOException e) {
Log.e(TAG, "Error setting up device: " + e.getMessage(), e);
try {
sPort.close();
} catch (IOException e2) {
// Ignore.
}
sPort = null;
throw new IOException("Error configuring USB device:" + e.getMessage());
}
Log.i(TAG,"startSession: creating new GPS session");
mCurrentSession = new GPSSession();
sessFile = new File(dirFile.getPath(),mCurrentSession.getFileName());
if (sessFile.exists()) {
Log.e(TAG,"Session file already exists!");
throw new IOException("Session file already exists: " + mCurrentSession.getFileName());
}
// Create file
try {
boolean fileCreated = sessFile.createNewFile();
Log.i(TAG, "fileCreated: " + fileCreated);
} catch (IOException e) {
Log.e(TAG, "Failed to create new file: " + e.getMessage());
throw new IOException("Failed to create new file: " + e.getMessage());
}
// Create output buffer
try {
bufOS = new BufferedOutputStream(new FileOutputStream(sessFile));
} catch (FileNotFoundException e) {
Log.e(TAG, "File not found exception: " + e.getMessage());
throw new IOException("File not found exception during buffer creation");
}
// Start the IO manager thread
startIoManager();
}
public void stopSession(View v) {
stopIoManager();
// Block until mSerialIoManager has finished writing and has shutdown?
//mSerialIoManager.waitForStop();
try {
bufOS.flush();
bufOS.close();
} catch (IOException e) {
Log.e(TAG, "stopSession failed to flush or close file" + e.getMessage());
}
// TODO: Probably want to call lv.setAdapter(...) again, to update the list. See code in onCreate. Will have to create a new GPSSession object
updateSessionListView();
}
public void onSessionToggleClicked(View view) {
// Is the toggle on?
boolean on = ((ToggleButton) view).isChecked();
if (on) {
// Handle toggle on
Log.i(TAG,"Starting session.");
try {
startSession(view);
} catch (IOException e) {
// Failed to start session
Toast.makeText(this, e.getLocalizedMessage(),Toast.LENGTH_LONG).show();
((ToggleButton) view).setChecked(false);
}
} else {
// Handle toggle off
Log.i(TAG, "Stopping session.");
stopSession(view);
}
}
/// Serial Port code
private static UsbSerialPort sPort = null;
private SerialInputOutputManager mSerialIoManager;
private final ExecutorService mExecutor = Executors.newSingleThreadExecutor();
// SerialInputOutputManager.Listen is a subclass of Runnable (this makes it's own thread!)
private final SerialInputOutputManager.Listener mListener =
new SerialInputOutputManager.Listener() {
@Override
public void onRunError(Exception e) {
Log.d(TAG, "Runner stopped.");
}
@Override
public void onNewData(final byte[] data) {
// Write data to session file
try {
bufOS.write(data);
} catch (IOException e) {
Log.e(TAG, "mListener failed to write data to output buffer" + e.getMessage());
}
// Also push the bytes out to the log
String decoded = new String(data);
Log.d(TAG, '\n'+decoded+'\n');
}
};
private void stopIoManager() {
if (mSerialIoManager != null) {
Log.i(TAG, "Stopping io manager ..");
mSerialIoManager.stop();
mSerialIoManager = null;
}
}
private void startIoManager() {
if (sPort != null) {
Log.i(TAG, "Starting io manager ..");
mSerialIoManager = new SerialInputOutputManager(sPort, mListener);
mExecutor.submit(mSerialIoManager);
// TODO: send actual GPS configuration string.
// NOTE: writeAsync writes into a smallish buffer that we may want to make bigger,
// otherwise an exception will be thrown.
String msg = "unlogall\r\nlog,com1,version,ontime,5\r\n"; // causes GPS to spit out its version string every five seconds
mSerialIoManager.writeAsync(msg.getBytes());
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent settingsIntent = new Intent(this, SettingsActivity.class);
startActivity(settingsIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
protected void onResume() {
super.onResume();
Log.i(TAG,"calling onResume");
// The only way this if block should be able to execute is if we just returned from authorizing the app for dropbox access
if ( !mDBApi.getSession().isLinked() && mDBApi.getSession().authenticationSuccessful()) {
Log.i(TAG,"onResume, inside authenticationSuccessful code");
String accessToken = null;
try {
// Required to complete auth, sets the access token on the session
mDBApi.getSession().finishAuthentication();
accessToken = mDBApi.getSession().getOAuth2AccessToken();
} catch (IllegalStateException e) {
Log.i("DbAuthLog", "Error authenticating", e);
}
Log.i(TAG,"onResume, after startOAuth2Authentication");
//Assuming onResume has been called at this point
Log.i(TAG,"accessToken: "+accessToken);
//need to store accessToken in shared preferences
if (!(accessToken==null)) {
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("OAuth2AccessToken", accessToken);
editor.commit();
Log.i(TAG,"stored as: "+sharedPref.getString("OAuth2AccessToken","not_authenticated"));
Toast.makeText(MainActivity.this,"Now linked with DropBox. OAuth2 access token stored for future use", Toast.LENGTH_LONG).show();
}
}
}
public ArrayList<GPSSession> loadGPSSessions() {
Log.i(TAG,"loadGPSSessions");
File gps_files[] = dirFile.listFiles();
ArrayList<GPSSession> sessions = new ArrayList<GPSSession>();
for (int i=0;i<gps_files.length;i++) {
File f = gps_files[i];
String fileName = f.getName();
// First check if file name is long enough to be a mahali gps data file
if (fileName.length() >= 17) {
// Grab what should be the '.nvd' file extension, if it's a mahali file
String test = fileName.substring(13, 17);
if (test.equals(".nvd")) {
// Create new GPS sessions with the file name and length of file in bytes
sessions.add(new GPSSession(fileName,f.getAbsolutePath(),f.length()));
}
}
}
// Reverse order so most recent session is at top of list
Collections.reverse(sessions);
return sessions;
}
private void deleteFile() {
// TODO: write code for file deletion. Note that we'll have to call lv.setAdapter(...) again, to update the list
}
// Send file to DropBox
public void sendToDB(String absolutePath) {
Log.i(TAG, "calling sendToDB");
File fileToSend = new File(absolutePath);
if ( fileToSend==null ) {
Toast.makeText(MainActivity.this, "No file selected", Toast.LENGTH_LONG).show();
return;
}
if ( ! (mDBApi.getSession().isLinked())) {
connectToDB();
if ( ! (mDBApi.getSession().isLinked())) {
return;
}
}
if (fileToSend.exists()) {
Toast.makeText(MainActivity.this,"Attempting to send to DropBox", Toast.LENGTH_LONG).show();
// Have to call an asynchronous task for this
new DBSendFileTask().execute(fileToSend);
} else {
Toast.makeText(MainActivity.this,"No content in file to send", Toast.LENGTH_LONG).show();
}
}
private class DBSendFileTask extends AsyncTask<File, Void, DropboxAPI.Entry> {
// This function is called in the background thread
protected DropboxAPI.Entry doInBackground(File... files) {
FileInputStream inputStream = null;
File fileToSend = files[0];
try {
inputStream = new FileInputStream(fileToSend);
} catch (FileNotFoundException e) {
Log.e(TAG,e.getMessage());
}
Log.i(TAG,"length of file: "+fileToSend.length());
DropboxAPI.Entry response = null;
try {
response = mDBApi.putFile("/"+fileToSend.getName(), inputStream, fileToSend.length(), null, null);
} catch (DropboxException e) {
Log.e(TAG,"DropBox putfile failed!");
}
return response;
}
// This function is called in the UI (main) thread, after doInBackground returns
protected void onPostExecute(DropboxAPI.Entry response) {
if (! (response==null)) {
Log.i("DbExampleLog", "The uploaded file's rev is: " + response.rev);
Toast.makeText(MainActivity.this,"File uploaded to DropBox. Path: "+response.path, Toast.LENGTH_LONG).show();
}
}
}
// Starts Dropbox authentication if has not occurred yet
public void connectToDB() {
Log.i(TAG, "calling connectToDB");
if (!mDBApi.getSession().isLinked()) {
//get user to authorize app. Will prompt the user to login to dropbox externally, either through browser or dropbox app
mDBApi.getSession().startOAuth2Authentication(MainActivity.this);
}
else {
// Toast.makeText(MainActivity.this,"Already linked with DropBox!", Toast.LENGTH_LONG).show();
}
}
}
|
package com.pr0gramm.app.feed;
import android.support.annotation.Nullable;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.pr0gramm.app.Settings;
import com.pr0gramm.app.Stats;
import com.pr0gramm.app.api.categories.ExtraCategoryApi;
import com.pr0gramm.app.api.categories.ExtraCategoryApiProvider;
import com.pr0gramm.app.api.pr0gramm.Api;
import com.pr0gramm.app.services.Track;
import com.pr0gramm.app.services.config.ConfigService;
import org.immutables.value.Value;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
import rx.Observable;
/**
* Performs the actual request to get the items for a feed.
*/
@Singleton
public class FeedService {
private static final Logger logger = LoggerFactory.getLogger("FeedService");
private final Api mainApi;
private final ExtraCategoryApi categoryApi;
private final Settings settings;
private final ConfigService configService;
@Inject
public FeedService(Api mainApi, ExtraCategoryApiProvider categoryApi, Settings settings,
ConfigService configService) {
this.mainApi = mainApi;
this.categoryApi = categoryApi.get();
this.settings = settings;
this.configService = configService;
}
public Observable<Api.Feed> getFeedItems(FeedQuery query) {
FeedFilter feedFilter = query.feedFilter();
// filter by feed-type
Integer promoted = (feedFilter.getFeedType() == FeedType.PROMOTED) ? 1 : null;
Integer following = (feedFilter.getFeedType() == FeedType.PREMIUM) ? 1 : null;
int flags = ContentType.combine(query.contentTypes());
String tags = feedFilter.getTags().orNull();
String user = feedFilter.getUsername().orNull();
// FIXME this is quite hacky right now.
String likes = feedFilter.getLikes().orNull();
Boolean self = Strings.isNullOrEmpty(likes) ? null : true;
FeedType feedType = feedFilter.getFeedType();
// statistics
Stats.get().incrementCounter("feed.loaded", "type:" + feedType.name().toLowerCase());
// get extended tag query
SearchQuery q = new SearchQuery(tags);
switch (feedType) {
case RANDOM:
return categoryApi.random(q.tags, flags);
case BESTOF:
int benisScore = settings.bestOfBenisThreshold();
return categoryApi.bestof(q.tags, user, flags, query.older().orNull(), benisScore);
case CONTROVERSIAL:
return categoryApi.controversial(q.tags, flags, query.older().orNull());
case TEXT:
return categoryApi.text(q.tags, flags, query.older().orNull());
default:
// prepare the call to the official api. The call is only made on subscription.
Observable<Api.Feed> officialCall = mainApi.itemsGet(promoted, following,
query.older().orNull(), query.newer().orNull(), query.around().orNull(),
flags, q.tags, likes, self, user);
if (likes == null && configService.config().searchUsingTagService()) {
return categoryApi
.general(promoted, q.tags, user, flags,
query.older().orNull(), query.newer().orNull(),
query.around().orNull())
.onErrorResumeNext(officialCall);
} else if (!query.around().isPresent() && !query.newer().isPresent()) {
if (q.advanced) {
// track the advanced search
Track.advancedSearch(tags);
logger.info("Using general search api, but falling back on old one in case of an error.");
return categoryApi
.general(promoted, tags, user, flags, query.older().orNull(), query.newer().orNull(), query.around().orNull())
.onErrorResumeNext(officialCall);
}
}
return officialCall;
}
}
public Observable<Api.Post> loadPostDetails(long id) {
return mainApi.info(id);
}
@Value.Immutable
public interface FeedQuery {
FeedFilter feedFilter();
Set<ContentType> contentTypes();
Optional<Long> newer();
Optional<Long> older();
Optional<Long> around();
}
private static class SearchQuery {
final boolean advanced;
@Nullable
final String tags;
SearchQuery(@Nullable String tags) {
if (tags == null || !tags.trim().startsWith("?")) {
this.advanced = false;
this.tags = tags;
} else {
this.advanced = true;
this.tags = tags.replaceFirst("\\s*\\?\\s*", "");
}
}
}
}
|
package com.qiang.workout;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import com.qiang.workout.Interfaces.TimeSelectFragmentListener;
import com.qiang.workout.Models.Profile;
import com.qiang.workout.Utilities.DBHandler;
import com.qiang.workout.Utilities.TextTimeClickListener;
public class ProfileActivity extends AppCompatActivity implements TimeSelectFragmentListener
{
public static final int PROFILE_ADDED = 1;
public static final int PROFILE_EDITED = 2;
private EditText name;
private EditText repeatNumber;
private TextView textTimeMinutes;
private TextView textTimeSeconds;
private TextView timeError;
private CheckBox repeat;
private DBHandler dbHandler;
private Profile profile;
private boolean isEditingProfile = false;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Sets the activity_profile as this activity's display
setContentView(R.layout.activity_profile);
// Initialises variables
name = (EditText) findViewById(R.id.profile_text_name);
repeatNumber = (EditText) findViewById(R.id.profile_text_repeat);
textTimeMinutes = (TextView) findViewById(R.id.profile_text_time_minutes);
textTimeSeconds = (TextView) findViewById(R.id.profile_text_time_seconds);
timeError = (TextView) findViewById(R.id.profile_text_time_error);
repeat = (CheckBox) findViewById(R.id.profile_checkbox_repeat);
dbHandler = new DBHandler(this, null, null, 1);
// Handles click events for textTimeMinutes and textTimeSeconds
textTimeMinutes.setOnClickListener(new TextTimeClickListener(true, this));
textTimeSeconds.setOnClickListener(new TextTimeClickListener(false, this));
if (getIntent().hasExtra("profileID"))
{
isEditingProfile = true;
// Changes activity's title to @string/title_edit_profile
setTitle(R.string.title_edit_profile);
// Creates new chosen profile object
profile = dbHandler.getProfile(getIntent().getIntExtra("profileID", 1));
// Sets input box values for profile loaded from database
name.setText(profile.getName());
setTextTime(textTimeMinutes, profile.getMinutes());
setTextTime(textTimeSeconds, profile.getSeconds());
repeat.setChecked(profile.isRepeat());
repeatNumber.setText(Integer.toString(profile.getRepeatNumber()));
}
else
{
// Changes activity's title to @string/title_new_profile
setTitle(R.string.title_new_profile);
}
}
private void setTextTime(TextView textTime, int timeChosen)
{
// Appends 0 in front of timeChosen if less than 10 before setting textTime
if (timeChosen < 10)
{
textTime.setText("0" + Integer.toString(timeChosen));
}
else
{
textTime.setText(Integer.toString(timeChosen));
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handles item selection in action bar
if (item.getItemId() == R.id.action_save_profile)
{
/*
Performs validation of input data
*/
boolean isError = false;
if (name.getText().length() == 0)
{
isError = true;
name.setError("Name is required");
}
if (name.getText().toString().trim().length() > 50)
{
isError = true;
name.setError("Name can't be longer than 50 characters");
}
if (textTimeMinutes.getText().equals("00") && textTimeSeconds.getText().equals("00"))
{
isError = true;
timeError.setError("Time is required");
}
if (repeat.isChecked() && repeatNumber.getText().length() == 0)
{
isError = true;
repeatNumber.setError("Number of laps is required");
}
/*
Produces an error if:
- name of profile is taken and adding a new profile
- changed profile name is taken
*/
if (dbHandler.profileExists(name.getText().toString().trim()))
{
if (!isEditingProfile || !name.getText().toString().trim().equals(profile.getName()))
{
isError = true;
name.setError("Name already exists");
}
}
if (!isError)
{
if (isEditingProfile)
{
setResult(PROFILE_EDITED);
updateProfile();
}
else
{
setResult(PROFILE_ADDED);
addProfile();
}
finish();
}
}
else if (item.getItemId() == android.R.id.home) // If user clicked back arrow
{
// Prompts user to either discard or continue editing
displayCancelDialog();
return true;
}
return super.onOptionsItemSelected(item);
}
private void addProfile()
{
// Creates a profile object with user's settings (to be inserted to the database)
Profile newProfile = new Profile(name.getText().toString().trim());
newProfile.setMinutes(Integer.parseInt(textTimeMinutes.getText().toString()));
newProfile.setSeconds(Integer.parseInt(textTimeSeconds.getText().toString()));
newProfile.setRepeat(repeat.isChecked());
// Only set user's repeatNumber if repeat is checked
newProfile.setRepeatNumber((repeat.isChecked()) ? Integer.parseInt(repeatNumber.getText().toString()) : 0);
dbHandler.addProfile(newProfile);
}
private void updateProfile()
{
// Updates profile object with user's settings
profile.setName(name.getText().toString().trim());
profile.setMinutes(Integer.parseInt(textTimeMinutes.getText().toString()));
profile.setSeconds(Integer.parseInt(textTimeSeconds.getText().toString()));
profile.setRepeat(repeat.isChecked());
// Only set user's repeatNumber if repeat is checked
profile.setRepeatNumber((repeat.isChecked()) ? Integer.parseInt(repeatNumber.getText().toString()) : 0);
dbHandler.saveEditedProfile(profile);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_profile, menu);
return true;
}
private void displayCancelDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Cancel");
// Set appropriate message depending on which operation is taking place
if (isEditingProfile)
{
builder.setMessage("Are you sure you want to discard your changes?");
}
else
{
builder.setMessage("Are you sure you want to discard this profile?");
}
// Adds the "Keep Editing" button
builder.setPositiveButton(R.string.keep_editing, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// Nothing here: alert dialog just closes
}
});
// Adds the "Discard" button
builder.setNegativeButton(R.string.discard, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// Closes this activity and directs users back to previous activity
finish();
}
});
// Displays the alert dialog
builder.create().show();
}
@Override
public void onFinishTimeSelectFragment(boolean isMinutes, int timeChosen)
{
// Removes time error if user has selected a non-zero value
if (timeChosen != 0)
{
timeError.setError(null);
}
// Determines whether minutes or seconds should be updated
if (isMinutes)
{
setTextTime(textTimeMinutes, timeChosen);
}
else
{
setTextTime(textTimeSeconds, timeChosen);
}
}
}
|
package com.samourai.wallet;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.TextView;
import android.widget.Toast;
import com.auth0.android.jwt.JWT;
import com.samourai.wallet.access.AccessFactory;
import com.samourai.wallet.api.APIFactory;
import com.samourai.wallet.crypto.AESUtil;
import com.samourai.wallet.home.BalanceActivity;
import com.samourai.wallet.payload.PayloadUtil;
import com.samourai.wallet.prng.PRNGFixes;
import com.samourai.wallet.service.BackgroundManager;
import com.samourai.wallet.service.WebSocketService;
import com.samourai.wallet.tor.TorManager;
import com.samourai.wallet.util.AppUtil;
import com.samourai.wallet.util.CharSequenceX;
import com.samourai.wallet.util.ConnectivityStatus;
import com.samourai.wallet.util.PrefsUtil;
import com.samourai.wallet.util.TimeOutUtil;
import org.apache.commons.codec.DecoderException;
import org.bitcoinj.crypto.MnemonicException;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.params.TestNet3Params;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
public class MainActivity2 extends Activity {
private ProgressDialog progress = null;
public static final String ACTION_RESTART = "com.samourai.wallet.MainActivity2.RESTART_SERVICE";
private AlertDialog.Builder dlg;
private boolean pinEntryActivityLaunched = false;
private TextView loaderTxView;
private CompositeDisposable compositeDisposables = new CompositeDisposable();
protected BroadcastReceiver receiver_restart = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (ACTION_RESTART.equals(intent.getAction())) {
// ReceiversUtil.getInstance(MainActivity2.this).initReceivers();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
if (AppUtil.getInstance(MainActivity2.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {
stopService(new Intent(MainActivity2.this.getApplicationContext(), WebSocketService.class));
}
startService(new Intent(MainActivity2.this.getApplicationContext(), WebSocketService.class));
}
}
}
};
protected BackgroundManager.Listener bgListener = new BackgroundManager.Listener() {
public void onBecameForeground() {
Intent intent = new Intent("com.samourai.wallet.BalanceFragment.REFRESH");
intent.putExtra("notifTx", false);
LocalBroadcastManager.getInstance(MainActivity2.this.getApplicationContext()).sendBroadcast(intent);
Intent _intent = new Intent("com.samourai.wallet.MainActivity2.RESTART_SERVICE");
LocalBroadcastManager.getInstance(MainActivity2.this.getApplicationContext()).sendBroadcast(_intent);
}
public void onBecameBackground() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (AppUtil.getInstance(MainActivity2.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {
stopService(new Intent(MainActivity2.this.getApplicationContext(), WebSocketService.class));
}
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
new Thread(new Runnable() {
@Override
public void run() {
try {
PayloadUtil.getInstance(MainActivity2.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(MainActivity2.this).getGUID() + AccessFactory.getInstance(MainActivity2.this).getPIN()));
} catch (Exception e) {
;
}
}
}).start();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
loaderTxView = findViewById(R.id.loader_text);
if (PrefsUtil.getInstance(MainActivity2.this).getValue(PrefsUtil.TESTNET, false) == true) {
SamouraiWallet.getInstance().setCurrentNetworkParams(TestNet3Params.get());
}
// if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
BackgroundManager.get(MainActivity2.this).addListener(bgListener);
// Apply PRNG fixes for Android 4.1
if (!AppUtil.getInstance(MainActivity2.this).isPRNG_FIXED()) {
PRNGFixes.apply();
AppUtil.getInstance(MainActivity2.this).setPRNG_FIXED(true);
}
if (PrefsUtil.getInstance(this).getValue(PrefsUtil.ENABLE_TOR, false) && !TorManager.getInstance(getApplicationContext()).isConnected() && ConnectivityStatus.hasConnectivity(getApplicationContext())) {
loaderTxView.setText("initializing Tor...");
((SamouraiApplication) getApplication()).startService();
Disposable disposable = TorManager.getInstance(this)
.torStatus
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(connection_states -> {
if (connection_states == TorManager.CONNECTION_STATES.CONNECTED) {
initAppOnCreate();
compositeDisposables.dispose();
}
});
compositeDisposables.add(disposable);
} else {
initAppOnCreate();
}
}
private void initAppOnCreate() {
if (AppUtil.getInstance(MainActivity2.this).isOfflineMode() &&
!(AccessFactory.getInstance(MainActivity2.this).getGUID().length() < 1 || !PayloadUtil.getInstance(MainActivity2.this).walletFileExists())) {
Toast.makeText(MainActivity2.this, R.string.in_offline_mode, Toast.LENGTH_SHORT).show();
doAppInit0(false, null, null);
} else {
// SSLVerifierThreadUtil.getInstance(MainActivity2.this).validateSSLThread();
// APIFactory.getInstance(MainActivity2.this).validateAPIThread();
String action = getIntent().getAction();
String scheme = getIntent().getScheme();
String strUri = null;
boolean isDial = false;
// String strUri = null;
String strPCode = null;
if (action != null && Intent.ACTION_VIEW.equals(action) && scheme.equals("bitcoin")) {
strUri = getIntent().getData().toString();
} else {
Bundle extras = getIntent().getExtras();
if (extras != null && extras.containsKey("dialed")) {
isDial = extras.getBoolean("dialed");
}
if (extras != null && extras.containsKey("uri")) {
strUri = extras.getString("uri");
}
if (extras != null && extras.containsKey("pcode")) {
strPCode = extras.getString("pcode");
}
}
doAppInit0(isDial, strUri, strPCode);
}
}
@Override
protected void onResume() {
if (PrefsUtil.getInstance(this).getValue(PrefsUtil.ENABLE_TOR, false) && !TorManager.getInstance(getApplicationContext()).isConnected()) {
((SamouraiApplication) getApplication()).startService();
Disposable disposable = TorManager.getInstance(getApplicationContext())
.torStatus
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(connection_states -> {
if (connection_states == TorManager.CONNECTION_STATES.CONNECTED) {
initAppOnResume();
compositeDisposables.dispose();
}
});
compositeDisposables.add(disposable);
} else {
initAppOnResume();
}
super.onResume();
}
private void initAppOnResume() {
AppUtil.getInstance(MainActivity2.this).setIsInForeground(true);
AppUtil.getInstance(MainActivity2.this).deleteQR();
AppUtil.getInstance(MainActivity2.this).deleteBackup();
IntentFilter filter_restart = new IntentFilter(ACTION_RESTART);
LocalBroadcastManager.getInstance(MainActivity2.this).registerReceiver(receiver_restart, filter_restart);
doAppInit0(false, null, null);
}
@Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(MainActivity2.this).unregisterReceiver(receiver_restart);
AppUtil.getInstance(MainActivity2.this).setIsInForeground(false);
}
@Override
protected void onDestroy() {
compositeDisposables.dispose();
AppUtil.getInstance(MainActivity2.this).deleteQR();
AppUtil.getInstance(MainActivity2.this).deleteBackup();
// if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
BackgroundManager.get(this).removeListener(bgListener);
super.onDestroy();
}
private void initDialog() {
Intent intent = new Intent(MainActivity2.this, LandingActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void validatePIN(String strUri) {
if (!pinEntryActivityLaunched) {
if (AccessFactory.getInstance(MainActivity2.this).isLoggedIn() && !TimeOutUtil.getInstance().isTimedOut()) {
return;
}
AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(false);
Intent intent = new Intent(MainActivity2.this, PinEntryActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
if (strUri != null) {
intent.putExtra("uri", strUri);
PrefsUtil.getInstance(MainActivity2.this).setValue("SCHEMED_URI", strUri);
}
startActivity(intent);
pinEntryActivityLaunched=true;
}
}
private void launchFromDialer(final String pin) {
if (progress != null && progress.isShowing()) {
progress.dismiss();
progress = null;
}
progress = new ProgressDialog(MainActivity2.this);
progress.setCancelable(false);
progress.setTitle(R.string.app_name);
progress.setMessage(getString(R.string.please_wait));
progress.show();
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
try {
PayloadUtil.getInstance(MainActivity2.this).restoreWalletfromJSON(new CharSequenceX(AccessFactory.getInstance(MainActivity2.this).getGUID() + pin));
if (progress != null && progress.isShowing()) {
progress.dismiss();
progress = null;
}
AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(true);
TimeOutUtil.getInstance().updatePin();
AppUtil.getInstance(MainActivity2.this).restartApp();
} catch (MnemonicException.MnemonicLengthException mle) {
mle.printStackTrace();
} catch (DecoderException de) {
de.printStackTrace();
} finally {
if (progress != null && progress.isShowing()) {
progress.dismiss();
progress = null;
}
}
Looper.loop();
}
}).start();
}
private void doAppInit0(final boolean isDial, final String strUri, final String strPCode) {
if(!SamouraiWallet.getInstance().isTestNet()) {
doAppInit1(isDial, strUri, strPCode);
return;
}
boolean needToken = false;
if (APIFactory.getInstance(MainActivity2.this).getAccessToken() == null) {
needToken = true;
} else {
JWT jwt = new JWT(APIFactory.getInstance(MainActivity2.this).getAccessToken());
if (jwt.isExpired(APIFactory.getInstance(MainActivity2.this).getAccessTokenRefresh())) {
needToken = true;
}
}
if (needToken && !AppUtil.getInstance(MainActivity2.this).isOfflineMode()) {
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
APIFactory.getInstance(MainActivity2.this).stayingAlive();
doAppInit1(isDial, strUri, strPCode);
Looper.loop();
}
}).start();
return;
} else {
doAppInit1(isDial, strUri, strPCode);
}
}
private void doAppInit1(boolean isDial, final String strUri, final String strPCode) {
if ((strUri != null || strPCode != null) && AccessFactory.getInstance(MainActivity2.this).isLoggedIn()) {
progress = new ProgressDialog(MainActivity2.this);
progress.setCancelable(false);
progress.setTitle(R.string.app_name);
progress.setMessage(getText(R.string.please_wait));
progress.show();
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
APIFactory.getInstance(MainActivity2.this).initWallet();
if (progress != null && progress.isShowing()) {
progress.dismiss();
progress = null;
}
Intent intent = new Intent(MainActivity2.this, SendActivity.class);
intent.putExtra("uri", strUri);
intent.putExtra("pcode", strPCode);
startActivity(intent);
Looper.loop();
}
}).start();
} else if (AccessFactory.getInstance(MainActivity2.this).getGUID().length() < 1 || !PayloadUtil.getInstance(MainActivity2.this).walletFileExists()) {
AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(false);
if (AppUtil.getInstance(MainActivity2.this).isSideLoaded()) {
doSelectNet();
} else {
initDialog();
}
} else if (isDial && AccessFactory.getInstance(MainActivity2.this).validateHash(PrefsUtil.getInstance(MainActivity2.this).getValue(PrefsUtil.ACCESS_HASH, ""), AccessFactory.getInstance(MainActivity2.this).getGUID(), new CharSequenceX(AccessFactory.getInstance(MainActivity2.this).getPIN()), AESUtil.DefaultPBKDF2Iterations)) {
TimeOutUtil.getInstance().updatePin();
launchFromDialer(AccessFactory.getInstance(MainActivity2.this).getPIN());
} else if (TimeOutUtil.getInstance().isTimedOut()) {
AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(false);
validatePIN(strUri == null ? null : strUri);
} else if (AccessFactory.getInstance(MainActivity2.this).isLoggedIn() && !TimeOutUtil.getInstance().isTimedOut()) {
TimeOutUtil.getInstance().updatePin();
Intent intent = new Intent(MainActivity2.this, BalanceActivity.class);
intent.putExtra("notifTx", true);
intent.putExtra("fetch", true);
startActivity(intent);
} else {
AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(false);
validatePIN(strUri == null ? null : strUri);
}
}
private void doSelectNet() {
if(dlg!=null){
return;
}
dlg = new AlertDialog.Builder(this)
.setTitle(R.string.app_name)
.setMessage(R.string.select_network)
.setCancelable(false)
.setPositiveButton(R.string.MainNet, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
PrefsUtil.getInstance(MainActivity2.this).removeValue(PrefsUtil.TESTNET);
SamouraiWallet.getInstance().setCurrentNetworkParams(MainNetParams.get());
initDialog();
}
})
.setNegativeButton(R.string.TestNet, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
PrefsUtil.getInstance(MainActivity2.this).setValue(PrefsUtil.TESTNET, true);
SamouraiWallet.getInstance().setCurrentNetworkParams(TestNet3Params.get());
initDialog();
}
});
if (!isFinishing()) {
dlg.show();
}
}
}
|
package com.samourai.wallet;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
//import android.widget.Toolbar;
//import android.util.Log;
import com.dm.zbar.android.scanner.ZBarConstants;
import com.dm.zbar.android.scanner.ZBarScannerActivity;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.crypto.BIP38PrivateKey;
import org.bitcoinj.crypto.MnemonicException;
import org.bitcoinj.params.MainNetParams;
import com.samourai.wallet.access.AccessFactory;
import com.samourai.wallet.api.APIFactory;
import com.samourai.wallet.crypto.AESUtil;
import com.samourai.wallet.hd.HD_Wallet;
import com.samourai.wallet.hd.HD_WalletFactory;
import com.samourai.wallet.pinning.SSLVerifierThreadUtil;
import com.samourai.wallet.prng.PRNGFixes;
import com.samourai.wallet.send.SendFactory;
import com.samourai.wallet.service.BroadcastReceiverService;
import com.samourai.wallet.service.WebSocketService;
import com.samourai.wallet.util.AppUtil;
import com.samourai.wallet.util.CharSequenceX;
import com.samourai.wallet.util.ConnectivityStatus;
import com.samourai.wallet.util.ExchangeRateFactory;
import com.samourai.wallet.util.MonetaryUtil;
import com.samourai.wallet.util.PrefsUtil;
import com.samourai.wallet.util.PrivateKeyFactory;
import com.samourai.wallet.util.TimeOutUtil;
import com.samourai.wallet.util.WebUtil;
import net.sourceforge.zbar.Symbol;
import org.apache.commons.codec.DecoderException;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.math.BigInteger;
public class MainActivity2 extends Activity {
private final static int SCAN_COLD_STORAGE = 2011;
private ProgressDialog progress = null;
private CharSequence mTitle;
private boolean isInForeground = false;
private static final String MIME_TEXT_PLAIN = "text/plain";
private static final int MESSAGE_SENT = 1;
/** An array of strings to populate dropdown list */
private static String[] account_selections = null;
private static ArrayAdapter<String> adapter = null;
private static boolean loadedBalanceFragment = false;
public static final String ACTION_RESTART = "com.samourai.wallet.MainActivity2.RESTART_SERVICE";
protected BroadcastReceiver receiver_restart = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(ACTION_RESTART.equals(intent.getAction())) {
if(AppUtil.getInstance(MainActivity2.this.getApplicationContext()).isServiceRunning(BroadcastReceiverService.class)) {
stopService(new Intent(MainActivity2.this.getApplicationContext(), BroadcastReceiverService.class));
}
startService(new Intent(MainActivity2.this.getApplicationContext(), BroadcastReceiverService.class));
if(AppUtil.getInstance(MainActivity2.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {
stopService(new Intent(MainActivity2.this.getApplicationContext(), WebSocketService.class));
}
startService(new Intent(MainActivity2.this.getApplicationContext(), WebSocketService.class));
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
loadedBalanceFragment = false;
// doAccountSelection();
getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
ActionBar.OnNavigationListener navigationListener = new ActionBar.OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
if(itemPosition == 2 && PrefsUtil.getInstance(MainActivity2.this).getValue(PrefsUtil.FIRST_USE_SHUFFLE, true) == true) {
new AlertDialog.Builder(MainActivity2.this)
.setTitle(R.string.app_name)
.setMessage(R.string.first_use_shuffle)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
PrefsUtil.getInstance(MainActivity2.this).setValue(PrefsUtil.FIRST_USE_SHUFFLE, false);
}
}).show();
}
SamouraiWallet.getInstance().setCurrentSelectedAccount(itemPosition);
if(account_selections.length > 1) {
SamouraiWallet.getInstance().setShowTotalBalance(true);
}
else {
SamouraiWallet.getInstance().setShowTotalBalance(false);
}
if(loadedBalanceFragment) {
BalanceFragment balanceFragment = BalanceFragment.newInstance(4);
Bundle args = new Bundle();
args.putBoolean("notifTx", false);
args.putBoolean("fetch", false);
balanceFragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, balanceFragment).commit();
}
return false;
}
};
getActionBar().setListNavigationCallbacks(adapter, navigationListener);
getActionBar().setSelectedNavigationItem(1);
mTitle = getTitle();
// Apply PRNG fixes for Android 4.1
if(!AppUtil.getInstance(MainActivity2.this).isPRNG_FIXED()) {
PRNGFixes.apply();
AppUtil.getInstance(MainActivity2.this).setPRNG_FIXED(true);
}
if(!ConnectivityStatus.hasConnectivity(MainActivity2.this)) {
new AlertDialog.Builder(MainActivity2.this)
.setTitle(R.string.app_name)
.setMessage(R.string.no_internet)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
AppUtil.getInstance(MainActivity2.this).restartApp();
}
}).show();
}
else {
SSLVerifierThreadUtil.getInstance(MainActivity2.this).validateSSLThread();
exchangeRateThread();
boolean isDial = false;
String strUri = null;
String strPCode = null;
Bundle extras = getIntent().getExtras();
if(extras != null && extras.containsKey("dialed")) {
isDial = extras.getBoolean("dialed");
}
if(extras != null && extras.containsKey("uri")) {
strUri = extras.getString("uri");
}
if(extras != null && extras.containsKey("pcode")) {
strPCode = extras.getString("pcode");
}
if(PrefsUtil.getInstance(MainActivity2.this).getValue("popup_" + getResources().getString(R.string.version_name), false) == true) {
doAppInit(isDial, strUri, strPCode);
}
else {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity2.this);
WebView wv = new WebView(MainActivity2.this);
wv.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
wv.loadUrl("http://samouraiwallet.com/changelog/alpha3.html");
alert.setView(wv);
alert.setNegativeButton("Close", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
PrefsUtil.getInstance(MainActivity2.this).setValue("popup_" + getResources().getString(R.string.version_name), true);
AppUtil.getInstance(MainActivity2.this).restartApp();
}
});
if(!isFinishing()) {
alert.show();
}
}
}
}
@Override
protected void onResume() {
super.onResume();
AppUtil.getInstance(MainActivity2.this).setIsInForeground(true);
AppUtil.getInstance(MainActivity2.this).deleteQR();
AppUtil.getInstance(MainActivity2.this).deleteBackup();
if(TimeOutUtil.getInstance().isTimedOut()) {
if(AccessFactory.getInstance(MainActivity2.this).getGUID().length() < 1 || !HD_WalletFactory.getInstance(MainActivity2.this).walletFileExists()) {
AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(false);
initDialog();
}
else {
AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(false);
validatePIN(null);
}
}
else {
TimeOutUtil.getInstance().updatePin();
SSLVerifierThreadUtil.getInstance(MainActivity2.this).validateSSLThread();
}
IntentFilter filter_restart = new IntentFilter(ACTION_RESTART);
LocalBroadcastManager.getInstance(MainActivity2.this).registerReceiver(receiver_restart, filter_restart);
doAccountSelection();
}
@Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(MainActivity2.this).unregisterReceiver(receiver_restart);
AppUtil.getInstance(MainActivity2.this).setIsInForeground(false);
}
@Override
protected void onDestroy() {
AppUtil.getInstance(MainActivity2.this).deleteQR();
AppUtil.getInstance(MainActivity2.this).deleteBackup();
super.onDestroy();
}
@Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
}
public void onSectionAttached(int number) {
mTitle = getString(R.string.app_name);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == Activity.RESULT_OK && requestCode == SCAN_COLD_STORAGE) {
if(data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) {
final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT);
String format = null;
try {
format = PrivateKeyFactory.getInstance().getFormat(strResult);
}
catch(Exception e) {
;
}
if(format != null) {
if(format.equals(PrivateKeyFactory.BIP38)) {
final EditText password38 = new EditText(MainActivity2.this);
AlertDialog.Builder dlg = new AlertDialog.Builder(MainActivity2.this)
.setTitle(R.string.app_name)
.setMessage(R.string.bip38_pw)
.setView(password38)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String password = password38.getText().toString();
progress = new ProgressDialog(MainActivity2.this);
progress.setCancelable(false);
progress.setTitle(R.string.app_name);
progress.setMessage(getString(R.string.decrypting_bip38));
progress.show();
bip38Thread(strResult, password);
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(MainActivity2.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show();
}
});
if(!isFinishing()) {
dlg.show();
}
}
else {
doSweep(strResult);
}
}
}
}
else if(resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_COLD_STORAGE) {
;
}
else {
;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
menu.getItem(0).setVisible(false);
menu.getItem(1).setVisible(false);
restoreActionBar();
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
// noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
doSettings();
}
else if (id == R.id.action_sweep) {
doSweep();
}
else if (id == R.id.action_backup) {
try {
if(HD_WalletFactory.getInstance(MainActivity2.this).get() != null && SamouraiWallet.getInstance().hasPassphrase(MainActivity2.this)) {
doBackup();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.passphrase_needed_for_backup).setCancelable(false);
AlertDialog alert = builder.create();
alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}});
if(!isFinishing()) {
alert.show();
}
}
}
catch(MnemonicException.MnemonicLengthException mle) {
;
}
catch(IOException ioe) {
;
}
}
else {
;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK) {
if(getFragmentManager().getBackStackEntryCount() == 0 && !loadedBalanceFragment) {
loadedBalanceFragment = true;
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, BalanceFragment.newInstance(4)).commit();
}
else if(getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.ask_you_sure_exit).setCancelable(false);
AlertDialog alert = builder.create();
alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(false);
TimeOutUtil.getInstance().reset();
dialog.dismiss();
moveTaskToBack(true);
}});
alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
if(!isFinishing()) {
alert.show();
}
}
return true;
}
else {
;
}
return false;
}
private void doSettings() {
TimeOutUtil.getInstance().updatePin();
Intent intent = new Intent(MainActivity2.this, SettingsActivity.class);
startActivity(intent);
}
private void initDialog() {
AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(false);
AlertDialog.Builder dlg = new AlertDialog.Builder(this)
.setTitle(R.string.app_name)
.setMessage(R.string.please_select)
.setCancelable(false)
.setPositiveButton(R.string.create_wallet, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final EditText passphrase = new EditText(MainActivity2.this);
passphrase.setSingleLine(true);
AlertDialog.Builder dlg = new AlertDialog.Builder(MainActivity2.this)
.setTitle(R.string.app_name)
.setMessage(R.string.bip39_safe)
.setView(passphrase)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final String passphrase39 = passphrase.getText().toString();
if (passphrase39 != null && passphrase39.length() > 0) {
Intent intent = new Intent(MainActivity2.this, PinEntryActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("create", true);
intent.putExtra("passphrase", passphrase39 == null ? "" : passphrase39);
startActivity(intent);
} else {
Toast.makeText(MainActivity2.this, R.string.bip39_must, Toast.LENGTH_SHORT).show();
AppUtil.getInstance(MainActivity2.this).restartApp();
}
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(MainActivity2.this, R.string.bip39_must, Toast.LENGTH_SHORT).show();
AppUtil.getInstance(MainActivity2.this).restartApp();
}
});
if(!isFinishing()) {
dlg.show();
}
}
})
.setNegativeButton(R.string.restore_wallet, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
AlertDialog.Builder dlg = new AlertDialog.Builder(MainActivity2.this)
.setTitle(R.string.app_name)
.setMessage(R.string.restore_wallet)
.setCancelable(false)
.setPositiveButton(R.string.import_backup, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final EditText passphrase = new EditText(MainActivity2.this);
passphrase.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
passphrase.setHint(R.string.passphrase);
AlertDialog.Builder dlg = new AlertDialog.Builder(MainActivity2.this)
.setTitle(R.string.app_name)
.setView(passphrase)
.setMessage(R.string.restore_wallet_from_backup)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final String pw = passphrase.getText().toString();
if (pw == null || pw.length() < 1) {
Toast.makeText(MainActivity2.this, R.string.invalid_passphrase, Toast.LENGTH_SHORT).show();
AppUtil.getInstance(MainActivity2.this).restartApp();
}
final EditText edBackup = new EditText(MainActivity2.this);
edBackup.setSingleLine(false);
edBackup.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
edBackup.setLines(10);
edBackup.setHint(R.string.encrypted_backup);
edBackup.setGravity(Gravity.START);
TextWatcher textWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
edBackup.setSelection(0);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
;
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
;
}
};
edBackup.addTextChangedListener(textWatcher);
AlertDialog.Builder dlg = new AlertDialog.Builder(MainActivity2.this)
.setTitle(R.string.app_name)
.setView(edBackup)
.setMessage(R.string.restore_wallet_from_backup)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String encrypted = edBackup.getText().toString();
if (encrypted == null || encrypted.length() < 1) {
Toast.makeText(MainActivity2.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
AppUtil.getInstance(MainActivity2.this).restartApp();
}
String decrypted = null;
try {
decrypted = AESUtil.decrypt(encrypted, new CharSequenceX(pw), AESUtil.DefaultPBKDF2Iterations);
} catch (Exception e) {
Toast.makeText(MainActivity2.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
} finally {
if (decrypted == null || decrypted.length() < 1) {
Toast.makeText(MainActivity2.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
AppUtil.getInstance(MainActivity2.this).restartApp();
}
}
final String decryptedPayload = decrypted;
if (progress != null && progress.isShowing()) {
progress.dismiss();
progress = null;
}
progress = new ProgressDialog(MainActivity2.this);
progress.setCancelable(false);
progress.setTitle(R.string.app_name);
progress.setMessage(getString(R.string.please_wait));
progress.show();
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
try {
JSONObject json = new JSONObject(decryptedPayload);
HD_Wallet hdw = HD_WalletFactory.getInstance(MainActivity2.this).restoreWalletfromJSON(json);
HD_WalletFactory.getInstance(MainActivity2.this).set(hdw);
String guid = AccessFactory.getInstance(MainActivity2.this).createGUID();
String hash = AccessFactory.getInstance(MainActivity2.this).getHash(guid, new CharSequenceX(AccessFactory.getInstance(MainActivity2.this).getPIN()), AESUtil.DefaultPBKDF2Iterations);
PrefsUtil.getInstance(MainActivity2.this).setValue(PrefsUtil.ACCESS_HASH, hash);
PrefsUtil.getInstance(MainActivity2.this).setValue(PrefsUtil.ACCESS_HASH2, hash);
HD_WalletFactory.getInstance(MainActivity2.this).saveWalletToJSON(new CharSequenceX(guid + AccessFactory.getInstance().getPIN()));
}
catch(MnemonicException.MnemonicLengthException mle) {
mle.printStackTrace();
Toast.makeText(MainActivity2.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
}
catch(DecoderException de) {
de.printStackTrace();
Toast.makeText(MainActivity2.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
}
catch(JSONException je) {
je.printStackTrace();
Toast.makeText(MainActivity2.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
}
catch(IOException ioe) {
ioe.printStackTrace();
Toast.makeText(MainActivity2.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
}
catch(java.lang.NullPointerException npe) {
npe.printStackTrace();
Toast.makeText(MainActivity2.this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
}
finally {
if (progress != null && progress.isShowing()) {
progress.dismiss();
progress = null;
}
AppUtil.getInstance(MainActivity2.this).restartApp();
}
Looper.loop();
}
}).start();
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
AppUtil.getInstance(MainActivity2.this).restartApp();
}
});
if(!isFinishing()) {
dlg.show();
}
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
AppUtil.getInstance(MainActivity2.this).restartApp();
}
});
if(!isFinishing()) {
dlg.show();
}
}
})
.setNegativeButton(R.string.import_mnemonic, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final EditText mnemonic = new EditText(MainActivity2.this);
mnemonic.setHint(R.string.mnemonic_hex);
final EditText passphrase = new EditText(MainActivity2.this);
passphrase.setHint(R.string.bip39_passphrase);
passphrase.setSingleLine(true);
LinearLayout restoreLayout = new LinearLayout(MainActivity2.this);
restoreLayout.setOrientation(LinearLayout.VERTICAL);
restoreLayout.addView(mnemonic);
restoreLayout.addView(passphrase);
AlertDialog.Builder dlg = new AlertDialog.Builder(MainActivity2.this)
.setTitle(R.string.app_name)
.setMessage(R.string.bip39_safe)
.setView(restoreLayout)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final String seed39 = mnemonic.getText().toString();
final String passphrase39 = passphrase.getText().toString();
if (seed39 != null && seed39.length() > 0) {
Intent intent = new Intent(MainActivity2.this, PinEntryActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("create", true);
intent.putExtra("seed", seed39);
intent.putExtra("passphrase", passphrase39 == null ? "" : passphrase39);
startActivity(intent);
} else {
AppUtil.getInstance(MainActivity2.this).restartApp();
}
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
AppUtil.getInstance(MainActivity2.this).restartApp();
}
});
if(!isFinishing()) {
dlg.show();
}
}
});
if(!isFinishing()) {
dlg.show();
}
}
});
if(!isFinishing()) {
dlg.show();
}
}
private void validatePIN(String strUri) {
if(AccessFactory.getInstance(MainActivity2.this).isLoggedIn() && !TimeOutUtil.getInstance().isTimedOut()) {
return;
}
AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(false);
Intent intent = new Intent(MainActivity2.this, PinEntryActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
if(strUri != null) {
intent.putExtra("uri", strUri);
PrefsUtil.getInstance(MainActivity2.this).setValue("SCHEMED_URI", strUri);
}
startActivity(intent);
}
private void launchFromDialer(final String pin) {
if (progress != null && progress.isShowing()) {
progress.dismiss();
progress = null;
}
progress = new ProgressDialog(MainActivity2.this);
progress.setCancelable(false);
progress.setTitle(R.string.app_name);
progress.setMessage(getString(R.string.please_wait));
progress.show();
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
try {
HD_WalletFactory.getInstance(MainActivity2.this).restoreWalletfromJSON(new CharSequenceX(AccessFactory.getInstance(MainActivity2.this).getGUID() + pin));
if (progress != null && progress.isShowing()) {
progress.dismiss();
progress = null;
}
AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(true);
TimeOutUtil.getInstance().updatePin();
AppUtil.getInstance(MainActivity2.this).restartApp();
}
catch (MnemonicException.MnemonicLengthException mle) {
mle.printStackTrace();
}
catch (DecoderException de) {
de.printStackTrace();
}
finally {
if (progress != null && progress.isShowing()) {
progress.dismiss();
progress = null;
}
}
Looper.loop();
}
}).start();
}
private void exchangeRateThread() {
final Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
String response = null;
try {
response = WebUtil.getInstance(null).getURL(WebUtil.LBC_EXCHANGE_URL);
ExchangeRateFactory.getInstance(MainActivity2.this).setDataLBC(response);
ExchangeRateFactory.getInstance(MainActivity2.this).parseLBC();
}
catch(Exception e) {
e.printStackTrace();
}
response = null;
try {
response = WebUtil.getInstance(null).getURL(WebUtil.BTCe_EXCHANGE_URL + "btc_usd");
ExchangeRateFactory.getInstance(MainActivity2.this).setDataBTCe(response);
ExchangeRateFactory.getInstance(MainActivity2.this).parseBTCe();
}
catch(Exception e) {
e.printStackTrace();
}
response = null;
try {
response = WebUtil.getInstance(null).getURL(WebUtil.BTCe_EXCHANGE_URL + "btc_eur");
ExchangeRateFactory.getInstance(MainActivity2.this).setDataBTCe(response);
ExchangeRateFactory.getInstance(MainActivity2.this).parseBTCe();
}
catch(Exception e) {
e.printStackTrace();
}
response = null;
try {
response = WebUtil.getInstance(null).getURL(WebUtil.BTCe_EXCHANGE_URL + "btc_rur");
ExchangeRateFactory.getInstance(MainActivity2.this).setDataBTCe(response);
ExchangeRateFactory.getInstance(MainActivity2.this).parseBTCe();
}
catch(Exception e) {
e.printStackTrace();
}
response = null;
try {
response = WebUtil.getInstance(null).getURL(WebUtil.BFX_EXCHANGE_URL);
ExchangeRateFactory.getInstance(MainActivity2.this).setDataBFX(response);
ExchangeRateFactory.getInstance(MainActivity2.this).parseBFX();
}
catch(Exception e) {
e.printStackTrace();
}
response = null;
try {
response = WebUtil.getInstance(null).getURL(WebUtil.AVG_EXCHANGE_URL);
ExchangeRateFactory.getInstance(MainActivity2.this).setDataAVG(response);
ExchangeRateFactory.getInstance(MainActivity2.this).parseAVG();
}
catch(Exception e) {
e.printStackTrace();
}
handler.post(new Runnable() {
@Override
public void run() {
;
}
});
Looper.loop();
}
}).start();
}
private void doAppInit(boolean isDial, final String strUri, final String strPCode) {
if((strUri != null || strPCode != null) && AccessFactory.getInstance(MainActivity2.this).isLoggedIn()) {
progress = new ProgressDialog(MainActivity2.this);
progress.setCancelable(false);
progress.setTitle(R.string.app_name);
progress.setMessage(getText(R.string.please_wait));
progress.show();
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
APIFactory.getInstance(MainActivity2.this).initWalletAmounts();
if (progress != null && progress.isShowing()) {
progress.dismiss();
progress = null;
}
TimeOutUtil.getInstance().updatePin();
FragmentManager fragmentManager = getFragmentManager();
Bundle bundle = new Bundle();
bundle.putString("uri", strUri);
bundle.putString("pcode", strPCode);
SendFragment sendFragment = SendFragment.newInstance(2);
sendFragment.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.container, sendFragment).commit();
Looper.loop();
}
}).start();
}
else if(AccessFactory.getInstance(MainActivity2.this).getGUID().length() < 1 || !HD_WalletFactory.getInstance(MainActivity2.this).walletFileExists()) {
AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(false);
initDialog();
}
else if(isDial && AccessFactory.getInstance(MainActivity2.this).validateHash(PrefsUtil.getInstance(MainActivity2.this).getValue(PrefsUtil.ACCESS_HASH, ""), AccessFactory.getInstance(MainActivity2.this).getGUID(), new CharSequenceX(AccessFactory.getInstance(MainActivity2.this).getPIN()), AESUtil.DefaultPBKDF2Iterations)) {
TimeOutUtil.getInstance().updatePin();
launchFromDialer(AccessFactory.getInstance(MainActivity2.this).getPIN());
}
else if(TimeOutUtil.getInstance().isTimedOut()) {
AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(false);
validatePIN(strUri == null ? null : strUri);
}
else if(AccessFactory.getInstance(MainActivity2.this).isLoggedIn() && !TimeOutUtil.getInstance().isTimedOut()) {
TimeOutUtil.getInstance().updatePin();
loadedBalanceFragment = true;
BalanceFragment balanceFragment = BalanceFragment.newInstance(4);
Bundle args = new Bundle();
args.putBoolean("notifTx", true);
args.putBoolean("fetch", true);
balanceFragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, balanceFragment).commit();
}
else {
AccessFactory.getInstance(MainActivity2.this).setIsLoggedIn(false);
validatePIN(strUri == null ? null : strUri);
}
}
private void doSweep() {
Intent intent = new Intent(MainActivity2.this, ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{ Symbol.QRCODE } );
startActivityForResult(intent, SCAN_COLD_STORAGE);
}
private void bip38Thread(final String data, final String password) {
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
try {
BIP38PrivateKey bip38 = new BIP38PrivateKey(MainNetParams.get(), data);
final ECKey ecKey = bip38.decrypt(password);
if(ecKey != null && ecKey.hasPrivKey()) {
doSweep(ecKey.getPrivateKeyEncoded(MainNetParams.get()).toString());
}
}
catch(Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity2.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show();
}
if (progress != null && progress.isShowing()) {
progress.dismiss();
progress = null;
}
Looper.loop();
}
}).start();
}
private void doSweep(String data) {
ECKey ecKey = null;
try {
String keyFormat = PrivateKeyFactory.getInstance().getFormat(data);
ecKey = PrivateKeyFactory.getInstance().getKey(keyFormat, data);
// Log.i("sweep", ecKey.toAddress(MainNetParams.get()).toString());
}
catch(Exception e) {
e.printStackTrace();
}
final ECKey _ecKey = ecKey;
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
final BigInteger bValue = SendFactory.getInstance(MainActivity2.this).sweep(_ecKey);
if(bValue.compareTo(BigInteger.valueOf((long)(0.0001 * 1e8))) == 1) {
AlertDialog.Builder dlg = new AlertDialog.Builder(MainActivity2.this)
.setTitle(R.string.app_name)
.setMessage(getString(R.string.sweep_address_for) + " " + MonetaryUtil.getInstance().getBTCFormat().format(bValue.doubleValue() / 1e8) + " BTC?")
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
SendFactory.getInstance(MainActivity2.this).sweep(_ecKey, bValue.subtract(BigInteger.valueOf((long)(0.0001 * 1e8))), BigInteger.valueOf((long)(0.0001 * 1e8)), new OpCallback() {
public void onSuccess() {
MainActivity2.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity2.this, R.string.sweep_ok, Toast.LENGTH_SHORT).show();
}
});
}
public void onFail() {
MainActivity2.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity2.this, R.string.sweep_ko, Toast.LENGTH_SHORT).show();
}
});
}
});
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
;
}
});
if(!isFinishing()) {
dlg.show();
}
}
Looper.loop();
}
}).start();
}
private void doBackup() {
try {
final String passphrase = HD_WalletFactory.getInstance(MainActivity2.this).get().getPassphrase();
final String[] export_methods = new String[2];
export_methods[0] = getString(R.string.export_to_clipboard);
export_methods[1] = getString(R.string.export_to_email);
new AlertDialog.Builder(MainActivity2.this)
.setTitle(R.string.options_export)
.setSingleChoiceItems(export_methods, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
HD_WalletFactory.getInstance(MainActivity2.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(MainActivity2.this).getGUID() + AccessFactory.getInstance(MainActivity2.this).getPIN()));
} catch (Exception e) {
;
}
String encrypted = null;
try {
encrypted = AESUtil.encrypt(HD_WalletFactory.getInstance(MainActivity2.this).get().toJSON(MainActivity2.this).toString(), new CharSequenceX(passphrase), AESUtil.DefaultPBKDF2Iterations);
if(isExternalStorageWritable() && PrefsUtil.getInstance(MainActivity2.this).getValue(PrefsUtil.AUTO_BACKUP, true)) {
serialize(encrypted);
}
} catch (Exception e) {
Toast.makeText(MainActivity2.this, e.getMessage(), Toast.LENGTH_SHORT).show();
} finally {
if (encrypted == null) {
Toast.makeText(MainActivity2.this, R.string.encryption_error, Toast.LENGTH_SHORT).show();
return;
}
}
if (which == 0) {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(android.content.Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = null;
clip = android.content.ClipData.newPlainText("Wallet backup", encrypted);
clipboard.setPrimaryClip(clip);
Toast.makeText(MainActivity2.this, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show();
} else {
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_SUBJECT, "Samourai Wallet backup");
email.putExtra(Intent.EXTRA_TEXT, encrypted);
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, MainActivity2.this.getText(R.string.choose_email_client)));
}
dialog.dismiss();
}
}
).show();
}
catch(IOException ioe) {
ioe.printStackTrace();
Toast.makeText(MainActivity2.this, "HD wallet error", Toast.LENGTH_SHORT).show();
}
catch(MnemonicException.MnemonicLengthException mle) {
mle.printStackTrace();
Toast.makeText(MainActivity2.this, "HD wallet error", Toast.LENGTH_SHORT).show();
}
}
public void doAccountSelection() {
if(!HD_WalletFactory.getInstance(MainActivity2.this).walletFileExists()) {
return;
}
/*
if(AddressFactory.getInstance(MainActivity2.this).getHighestTxReceiveIdx(SamouraiWallet.MIXING_ACCOUNT) < 1) {
account_selections = new String[] {
getString(R.string.account_samourai),
};
}
else {
account_selections = new String[] {
getString(R.string.total),
getString(R.string.account_samourai),
getString(R.string.account_shuffling),
};
}
*/
account_selections = new String[] {
getString(R.string.total),
getString(R.string.account_samourai),
getString(R.string.account_shuffling),
};
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_dropdown_item, account_selections);
}
else {
adapter = new ArrayAdapter<String>(getBaseContext(), R.layout.spinner_dropdown, account_selections);
}
if(account_selections.length > 1) {
SamouraiWallet.getInstance().setShowTotalBalance(true);
}
else {
SamouraiWallet.getInstance().setShowTotalBalance(false);
}
}
private boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
private synchronized void serialize(String data) throws IOException {
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File newfile = new File(dir, "samourai.txt");
newfile.setWritable(true, true);
newfile.setReadable(true, true);
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newfile), "UTF-8"));
try {
out.write(data);
} finally {
out.close();
}
}
}
|
package com.samuel.destructo;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.parse.ParseAnalytics;
import com.parse.ParseUser;
public class MainActivity extends ActionBarActivity {
public static final String TAG = MainActivity.class.getSimpleName();
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Parse.com analytics
ParseAnalytics.trackAppOpenedInBackground(getIntent());
//When a user is logged in, condition is stored in cache
ParseUser currentUser = ParseUser.getCurrentUser();
if(currentUser == null){
navigateToLogin();
}
else{
Log.i(TAG, currentUser.getUsername());
}
//Set up action bar
final ActionBar actionBar = getSupportActionBar();
mSectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
//Set up ViewPager with sections adapter
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
/*
The following method is a result of a user action, originally intended to happen after the user
has taken a picture or video, but in this case it will be after a contact is selected from
the contact fragment.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
//Media stuff
/*if(resultCode == RESULT_OK){
}else if(resultCode != RESULT_CANCELED){
Toast.makeText(this, R.string.general_error, Toast.LENGTH_LONG).show();
}*/
Intent recipientsIntent = new Intent(this, RecipientsActivity.class);
//recipientsIntent.setData(mMediaUri);
startActivity(recipientsIntent);
}
private void navigateToLogin() {
//Go to log in activity
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int itemId = item.getItemId();
//noinspection SimplifiableIfStatement
if (itemId == R.id.action_logout) {
//The user has tapped on the log out option
ParseUser.logOut();
//Push user back to the login screen
navigateToLogin();
return true;
}
else if(itemId == R.id.action_edit_friends){
Intent intent = new Intent(this, EditFriendsActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.