answer
stringlengths 17
10.2M
|
|---|
package seedu.jimi.ui;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.SplitPane;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import seedu.jimi.commons.core.LogsCenter;
import seedu.jimi.commons.events.ui.TaskPanelSelectionChangedEvent;
import seedu.jimi.model.task.ReadOnlyTask;
import java.util.logging.Logger;
/**
* Panel containing the list of persons.
*/
public class TaskListPanel extends UiPart {
private final Logger logger = LogsCenter.getLogger(TaskListPanel.class);
private static final String FXML = "TaskListPanel.fxml";
private VBox panel;
private AnchorPane placeHolderPane;
@FXML
private ListView<ReadOnlyTask> taskListView;
public TaskListPanel() {
super();
}
@Override
public void setNode(Node node) {
panel = (VBox) node;
}
@Override
public String getFxmlPath() {
return FXML;
}
@Override
public void setPlaceholder(AnchorPane pane) {
this.placeHolderPane = pane;
}
public static TaskListPanel load(Stage primaryStage, AnchorPane taskListPlaceholder,
ObservableList<ReadOnlyTask> taskList) {
TaskListPanel taskListPanel =
UiPartLoader.loadUiPart(primaryStage, taskListPlaceholder, new TaskListPanel());
taskListPanel.configure(taskList);
return taskListPanel;
}
private void configure(ObservableList<ReadOnlyTask> taskList) {
setConnections(taskList);
addToPlaceholder();
}
private void setConnections(ObservableList<ReadOnlyTask> taskList) {
taskListView.setItems(taskList);
taskListView.setCellFactory(listView -> new PersonListViewCell());
setEventHandlerForSelectionChangeEvent();
}
private void addToPlaceholder() {
SplitPane.setResizableWithParent(placeHolderPane, false);
placeHolderPane.getChildren().add(panel);
}
private void setEventHandlerForSelectionChangeEvent() {
taskListView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if (newValue != null) {
logger.fine("Selection in task list panel changed to : '" + newValue + "'");
raise(new TaskPanelSelectionChangedEvent(newValue));
}
});
}
public void scrollTo(int index) {
Platform.runLater(() -> {
taskListView.scrollTo(index);
taskListView.getSelectionModel().clearAndSelect(index);
});
}
class PersonListViewCell extends ListCell<ReadOnlyTask> {
public PersonListViewCell() {
}
@Override
protected void updateItem(ReadOnlyTask task, boolean empty) {
super.updateItem(task, empty);
if (empty || task == null) {
setGraphic(null);
setText(null);
} else {
setGraphic(TaskCard.load(task, getIndex() + 1).getLayout());
}
}
}
}
|
package stexfires.io;
import stexfires.core.Record;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.util.Objects;
/**
* @author Mathias Kalb
* @since 0.1
*/
public class BaseRecordFile<W extends Record, R extends W> implements ReadableRecordFile<R>, WritableRecordFile<W> {
protected final Path path;
public BaseRecordFile(final Path path) {
Objects.requireNonNull(path);
this.path = path;
}
@Override
public final Path getPath() {
return path;
}
@Override
public ReadableRecordProducer<R> openProducer() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public WritableRecordConsumer<W> openConsumer() throws IOException {
throw new UnsupportedOperationException();
}
protected BufferedWriter newBufferedWriter(CharsetEncoder charsetEncoder,
OpenOption... options) throws IOException {
return new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(path, options), charsetEncoder));
}
protected BufferedReader newBufferedReader(CharsetDecoder charsetDecoder,
OpenOption... options) throws IOException {
return new BufferedReader(new InputStreamReader(Files.newInputStream(path, options), charsetDecoder));
}
protected CharsetDecoder newCharsetDecoder(Charset charset) {
return newCharsetDecoder(charset, CodingErrorAction.REPORT, null);
}
protected CharsetDecoder newCharsetDecoder(Charset charset,
CodingErrorAction malformedInputAction) {
return newCharsetDecoder(charset, malformedInputAction, null);
}
protected CharsetDecoder newCharsetDecoder(Charset charset,
CodingErrorAction malformedInputAction,
String replacement) {
CharsetDecoder charsetDecoder = charset.newDecoder().onMalformedInput(malformedInputAction);
if (malformedInputAction == CodingErrorAction.REPLACE && replacement != null) {
charsetDecoder = charsetDecoder.replaceWith(replacement);
}
return charsetDecoder;
}
protected CharsetEncoder newCharsetEncoder(Charset charset) {
return newCharsetEncoder(charset, CodingErrorAction.REPORT, null);
}
protected CharsetEncoder newCharsetEncoder(Charset charset,
CodingErrorAction unmappableCharacterAction) {
return newCharsetEncoder(charset, unmappableCharacterAction, null);
}
protected CharsetEncoder newCharsetEncoder(Charset charset,
CodingErrorAction unmappableCharacterAction,
byte[] replacement) {
CharsetEncoder charsetEncoder = charset.newEncoder().onUnmappableCharacter(unmappableCharacterAction);
if (unmappableCharacterAction == CodingErrorAction.REPLACE && replacement != null) {
charsetEncoder = charsetEncoder.replaceWith(replacement);
}
return charsetEncoder;
}
}
|
package studentcapture.mail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Author C13evk
*/
@Repository
public class MailDAO {
@Autowired
protected JdbcTemplate jdbcTemplate;
public MailDAO(){
}
public List<String> getAssignmentID(){
return jdbcTemplate.queryForList(getAssignmentIDQuery(),String.class);
}
public String getStartDateFromAssignment(String assID){
return jdbcTemplate.queryForObject(getStartDateQuery(), new Object[]{assID}, String.class);
}
public String getCourseIDFromAssignment(String assID){
return jdbcTemplate.queryForObject(getCourseIDQuery(), new Object[]{assID}, String.class);
}
public List<String> getPraticipantsEmails(String courseID){
return jdbcTemplate.queryForList(getEmailsQuery(), new Object[]{courseID}, String.class);
}
private String getEmailsQuery() {
return "SELECT Users.email "+
"FROM Users JOIN Participant ON Users.userID = Participant.userID "+
"WHERE courseID = ?;";
}
private String getAssignmentIDQuery(){
return "SELECT assignmentID FROM assignment;";
}
private String getStartDateQuery(){
return "SELECT startdate FROM assignment WHERE assignmentID=?;";
}
private String getCourseIDQuery(){
return "SELECT courseID FROM assignment WHERE assignmentID=?;";
}
}
|
package alma.acs.logging.config;
import java.io.StringReader;
import java.util.Set;
import java.util.logging.Logger;
import junit.framework.TestCase;
import si.ijs.maci.LoggingConfigurable;
import alma.acs.logging.ACSCoreLevel;
import alma.acs.testsupport.TestLogger;
import alma.maci.loggingconfig.LoggingConfig;
import alma.maci.loggingconfig.UnnamedLogger;
/**
* Test for {@linkplain LogConfig}.
* Does not require a running ACS environment.
*
* @author hsommer
*/
public class LogConfigTest extends TestCase {
private LogConfig logConfig;
private Logger logger;
public LogConfigTest() {
super("LogConfigTest");
}
protected void setUp() throws Exception {
super.setUp();
logConfig = new LogConfig();
logger = TestLogger.getLogger("LogConfigTest");
logConfig.setInternalLogger(logger);
}
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Mock LogConfigSubscriber to trace notification.
*/
private static class CountingLogConfigSubscriber implements LogConfigSubscriber {
volatile int count = 0;
public void configureLogging(LogConfig logConfig) {
assertNotNull(logConfig);
count++;
}
}
/**
* Tests adding and removing of subscribers, and whether {@link LogConfig#initialize(boolean)}
* triggers correctly the notification of these subscribers.
*/
public void testSubscriberNotification() throws LogConfigException {
logger.info("============ Running testSubscriberNotification ============");
int numSubscribers = 10;
CountingLogConfigSubscriber[] configSubscribers = new CountingLogConfigSubscriber[numSubscribers];
for (int i = 0; i < numSubscribers; i++) {
configSubscribers[i] = new CountingLogConfigSubscriber();
logConfig.addSubscriber(configSubscribers[i]);
// as a stupid client we add some subscribers again but expect this to have no side effect
if (i%2 == 0) {
logConfig.addSubscriber(configSubscribers[i]);
}
}
logConfig.initialize(false); // should call "configureLogging" on all subscribers
for (int i = 0; i < numSubscribers; i++) {
assertEquals(1, configSubscribers[i].count);
}
// now remove a few subscribers and assert they don't get called again, and that the remaining ones get called again
int numRemainingSubscribers = 3;
assertTrue(numSubscribers > numRemainingSubscribers);
for (int i = 0; i < numSubscribers - numRemainingSubscribers; i++) {
logConfig.removeSubscriber(configSubscribers[i]);
}
logConfig.initialize(false);
for (int i = 0; i < numSubscribers - numRemainingSubscribers; i++) {
assertEquals(1, configSubscribers[i].count);
}
for (int i = numSubscribers - numRemainingSubscribers; i < numSubscribers; i++) {
assertEquals(2, configSubscribers[i].count);
}
}
/**
* Tests the config values returned from {@link LogConfig}
* with at most env vars for default levels being set (can be enforced by TAT!),
* but without CDB or other information being considered.
* <p>
* Also asserts that none of these calls return the original object,
* but instead a copy of it. This indirectly exercises the equals method.
*/
public void testDefaultValues() throws Exception {
logger.info("============ Running testDefaultValues ============");
assertEquals("Log", logConfig.getCentralizedLogger());
assertEquals(10, logConfig.getDispatchPacketSize());
LoggingConfig schemaDefaults = new LoggingConfig();
// We verify that the castor-generated class actually has the current schema defaults.
// These values must be adjusted when the schema is changed.
// In that case also the values in the simulated CDB's xml might have to be changed
// in order to still be different from the default values.
assertEquals(0, schemaDefaults.getCount()); // 0 named loggers
assertEquals(10, schemaDefaults.getDispatchPacketSize());
assertEquals(10, schemaDefaults.getFlushPeriodSeconds());
assertEquals(10, schemaDefaults.getImmediateDispatchLevel());
assertEquals(1000, schemaDefaults.getMaxLogQueueSize());
assertEquals(ACSCoreLevel.ACS_LEVEL_TRACE, schemaDefaults.getMinLogLevelLocal());
assertEquals(ACSCoreLevel.ACS_LEVEL_TRACE, schemaDefaults.getMinLogLevel());
assertEquals("Log", schemaDefaults.getCentralizedLogger());
int defaultMinLogLevelLocal = schemaDefaults.getMinLogLevelLocal();
// but if env vars are set, we may have different default levels
Integer PROP_ACS_LOG_STDOUT = Integer.getInteger(LogConfig.PROPERTYNAME_MIN_LOG_LEVEL_LOCAL);
if (PROP_ACS_LOG_STDOUT != null) {
defaultMinLogLevelLocal = PROP_ACS_LOG_STDOUT.intValue();
logger.info("Using default stdout level from env var: " + defaultMinLogLevelLocal);
}
else {
logger.info("No env var setting found for " + LogConfig.PROPERTYNAME_MIN_LOG_LEVEL_LOCAL);
}
int defaultMinLogLevel = schemaDefaults.getMinLogLevel();
Integer PROP_ACS_LOG_REMOTE = Integer.getInteger(LogConfig.PROPERTYNAME_MIN_LOG_LEVEL);
if (PROP_ACS_LOG_REMOTE != null) {
defaultMinLogLevel = PROP_ACS_LOG_REMOTE.intValue();
logger.info("Using default remote level from env var: " + defaultMinLogLevelLocal);
}
else {
logger.info("No env var setting found for " + LogConfig.PROPERTYNAME_MIN_LOG_LEVEL);
}
// our logConfig should give the correct default values, coming from schema or env var
assertEquals(defaultMinLogLevelLocal, logConfig.getDefaultMinLogLevelLocal());
assertEquals(defaultMinLogLevel, logConfig.getDefaultMinLogLevel());
// Check default data other than log levels
assertEquals(schemaDefaults.getCentralizedLogger(), logConfig.getCentralizedLogger());
assertEquals(schemaDefaults.getImmediateDispatchLevel(), logConfig.getImmediateDispatchLevel());
assertEquals(schemaDefaults.getDispatchPacketSize(), logConfig.getDispatchPacketSize());
assertEquals(schemaDefaults.getFlushPeriodSeconds(), logConfig.getFlushPeriodSeconds());
// Get log levels for not existing named loggers, which should result in the default log levels being used
UnnamedLogger namedLogConfig1 = logConfig.getNamedLoggerConfig(null);
assertEquals(defaultMinLogLevel, namedLogConfig1.getMinLogLevel());
assertEquals(defaultMinLogLevelLocal, namedLogConfig1.getMinLogLevelLocal());
UnnamedLogger namedLogConfig2 = logConfig.getNamedLoggerConfig("nonExistingLogger");
assertNotSame(namedLogConfig1, namedLogConfig2);
assertEquals(defaultMinLogLevel, namedLogConfig2.getMinLogLevel());
assertEquals(defaultMinLogLevelLocal, namedLogConfig2.getMinLogLevelLocal());
}
public void testGetLogConfigXml() throws Exception {
String separateConfigComponent1 = "testComp1";
String separateConfigComponent2 = "testComp2";
String componentsXml =
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> " +
"<Components xmlns=\"urn:schemas-cosylab-com:Components:1.0\" xmlns:xsi=\"http:
createComponentsCdbXml(separateConfigComponent1, "IDL_TYPE_1", "some.class1", "zampaione", true, 0, 8) +
createComponentsCdbXml(separateConfigComponent2, "IDL_TYPE_2", "some.class2", "zampaione", true, 5, 7) +
"</Components>";
logger.info("componentsXml = " + componentsXml);
String cdbComponentsPath = "MACI/Components";
TestCDB testCDB = new TestCDB();
logConfig.setCDB(testCDB);
testCDB.addCurlToXmlMapping(cdbComponentsPath, componentsXml);
logConfig.setCDBComponentPath(separateConfigComponent1, cdbComponentsPath);
logConfig.setCDBComponentPath(separateConfigComponent2, cdbComponentsPath);
String expr = "//_[@Name='" + separateConfigComponent2 + "']/ComponentLogger";
String xml = logConfig.getLogConfigXml("MACI/Components", expr);
assertNotNull(xml);
logger.info("Got component config xml: " + xml);
UnnamedLogger compLoggerConfig = UnnamedLogger.unmarshalUnnamedLogger(new StringReader(xml));
assertNotNull(compLoggerConfig);
}
/**
* Tests logging config from the CDB, for both cases
* (a) that env vars beat CDB settings e.g. for normal CDB readign,
* (b) that CDB beats env vars e.g. during a refresh from CDB triggered via LoggingConfigurable API.
*/
public void testCDBValues() throws Exception {
logger.info("============ Running testCDBValues ============");
// we simulate an ACS_LOG_STDOUT env var setting
String ACS_LOG_STDOUT_ORIGINAL = System.getProperty(LogConfig.PROPERTYNAME_MIN_LOG_LEVEL_LOCAL);
String ACS_LOG_REMOTE_ORIGINAL = System.getProperty(LogConfig.PROPERTYNAME_MIN_LOG_LEVEL);
String ACS_LOG_STDOUT = "" + ACSCoreLevel.ACS_LEVEL_EMERGENCY;
assertFalse("Fix this test to chose a different env var than the default", ACS_LOG_STDOUT.equals(ACS_LOG_STDOUT_ORIGINAL));
System.setProperty(LogConfig.PROPERTYNAME_MIN_LOG_LEVEL_LOCAL, ACS_LOG_STDOUT);
logger.info("Set property (env var) for local default level to " + ACS_LOG_STDOUT);
// and remove any possibly present property from env var ACS_LOG_CENTRAL
System.clearProperty(LogConfig.PROPERTYNAME_MIN_LOG_LEVEL);
logger.info("Removed property (env var) for remote default level");
// the schema defaults as reference
LoggingConfig schemaDefaults = new LoggingConfig();
int defaultMinLogLevel = schemaDefaults.getMinLogLevel();
int defaultMinLogLevelLocal = schemaDefaults.getMinLogLevelLocal();
// before we read the CDB, let's verify that the env var and default log levels are correct
logConfig.initialize(false);
assertEquals(defaultMinLogLevel, logConfig.getDefaultMinLogLevel());
assertEquals(ACSCoreLevel.ACS_LEVEL_EMERGENCY, logConfig.getDefaultMinLogLevelLocal());
// the simulated test CDB to configure our loggers from
String cdbContainerPath = "MACI/Containers/frodoContainer";
String frodoContainerXml =
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> " +
"<Container xmlns=\"urn:schemas-cosylab-com:Container:1.0\" xmlns:xsi=\"http:
"<LoggingConfig " +
" minLogLevel=\"4\" " +
" minLogLevelLocal=\"3\" " +
" centralizedLogger=\"LogForFrodo\" " +
" maxLogQueueSize=\"200\" " +
" immediateDispatchLevel=\"7\" " +
" dispatchPacketSize=\"33\" " +
" >" +
"<log:_ Name=\"MyMuteComponent\" minLogLevel=\"5\" minLogLevelLocal=\"6\" />" +
"</LoggingConfig>" +
"</Container>";
TestCDB testCDB = new TestCDB();
testCDB.addCurlToXmlMapping(cdbContainerPath, frodoContainerXml);
logConfig.setCDBLoggingConfigPath(cdbContainerPath);
logConfig.setCDB(testCDB);
// first the normal case where the env var default level beats the CDB default level
logConfig.initialize(false);
assertEquals("CDB must beat schema default", 4, logConfig.getDefaultMinLogLevel());
assertEquals("Env var must beat CDB", ACSCoreLevel.ACS_LEVEL_EMERGENCY, logConfig.getDefaultMinLogLevelLocal());
assertEquals("LogForFrodo", logConfig.getCentralizedLogger());
assertEquals(7, logConfig.getImmediateDispatchLevel());
assertEquals(33, logConfig.getDispatchPacketSize());
assertEquals(200, logConfig.getMaxLogQueueSize());
Set<String> loggerNames = logConfig.getLoggerNames();
assertEquals(1, loggerNames.size());
assertTrue(loggerNames.contains("MyMuteComponent"));
assertEquals(schemaDefaults.getFlushPeriodSeconds(), logConfig.getFlushPeriodSeconds()); // was not in CDB, thus default should be used
// next the special case of CDB refresh via dynamic API, where the CDB beats the env var default levels
logConfig.initialize(true);
assertEquals("CDB must beat schema default", 4, logConfig.getDefaultMinLogLevel());
assertEquals("CDB must beat env var", 3, logConfig.getDefaultMinLogLevelLocal());
assertEquals("LogForFrodo", logConfig.getCentralizedLogger());
assertEquals(7, logConfig.getImmediateDispatchLevel());
assertEquals(33, logConfig.getDispatchPacketSize());
assertEquals(200, logConfig.getMaxLogQueueSize());
loggerNames = logConfig.getLoggerNames();
assertEquals(1, loggerNames.size());
assertTrue(loggerNames.contains("MyMuteComponent"));
assertEquals(schemaDefaults.getFlushPeriodSeconds(), logConfig.getFlushPeriodSeconds()); // was not in CDB, thus default should be used
UnnamedLogger myMuteloggerConfig = logConfig.getNamedLoggerConfig("MyMuteComponent");
assertEquals(5, myMuteloggerConfig.getMinLogLevel());
assertEquals(6, myMuteloggerConfig.getMinLogLevelLocal());
// Test logger configuration given in the CDB separately for a component in the Components.xml file, not with the rest of LoggingConfig in the Container xml.
String separateConfigComponent1 = "testComp1";
String separateConfigComponent2 = "testComp2";
String componentsXml =
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> " +
"<Components xmlns=\"urn:schemas-cosylab-com:Components:1.0\" xmlns:xsi=\"http:
createComponentsCdbXml(separateConfigComponent1, "IDL_TYPE_1", "some.class1", "zampaione", true, 0, 8) +
createComponentsCdbXml(separateConfigComponent2, "IDL_TYPE_2", "some.class2", "zampaione", true, 5, 7) +
"</Components>";
logger.info("componentsXml = " + componentsXml);
String cdbComponentsPath = "MACI/Components";
testCDB.addCurlToXmlMapping(cdbComponentsPath, componentsXml);
logConfig.setCDBComponentPath(separateConfigComponent1, cdbComponentsPath);
logConfig.setCDBComponentPath(separateConfigComponent2, cdbComponentsPath);
logConfig.initialize(false);
loggerNames = logConfig.getLoggerNames();
// assertEquals(2, loggerNames.size());
assertTrue(loggerNames.contains("MyMuteComponent"));
// assertTrue(loggerNames.contains(separateConfigComponent1));
// assertTrue(loggerNames.contains(separateConfigComponent2));
UnnamedLogger separateConfig1 = logConfig.getNamedLoggerConfig(separateConfigComponent1);
assertEquals(0, separateConfig1.getMinLogLevel());
assertEquals(8, separateConfig1.getMinLogLevelLocal());
UnnamedLogger separateConfig2 = logConfig.getNamedLoggerConfig(separateConfigComponent2);
assertEquals(5, separateConfig2.getMinLogLevel());
assertEquals(7, separateConfig2.getMinLogLevelLocal());
// restore env vars (probably not necessary)
if (ACS_LOG_STDOUT_ORIGINAL != null) {
System.setProperty(LogConfig.PROPERTYNAME_MIN_LOG_LEVEL_LOCAL, ACS_LOG_STDOUT_ORIGINAL);
}
if (ACS_LOG_REMOTE_ORIGINAL != null) {
System.setProperty(LogConfig.PROPERTYNAME_MIN_LOG_LEVEL, ACS_LOG_REMOTE_ORIGINAL);
}
}
/**
* Checks the response to bad CDB data and CDB access problems.
*/
public void testInvalidCDB() throws Exception {
logger.info("============ Running testInvalidCDB ============");
String cdbContainerPath = "MACI/Containers/frodoContainer";
String frodoContainerXml =
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> " +
"<Container xmlns=\"urn:schemas-cosylab-com:Container:1.0\" xmlns:xsi=\"http:
"<LoggingConfig " +
" minLogLevel=\"NotANumber\" " + // should cause an error
" minLogLevelLocal=\"3\" " +
" centralizedLogger=\"LogForFrodo\" " +
" maxLogQueueSize=\"200\" " +
" immediateDispatchLevel=\"\" " + // empty attr should be ignored w/o message
" myMisfittingAttribute=\"ShouldNotMatterThough\" " + // again no err message expected for this
" dispatchPacketSize=\"33\" " +
" flushPeriodSeconds=\"5\" " +
" />" +
"</Container>";
TestCDB testCDB = new TestCDB();
testCDB.addCurlToXmlMapping(cdbContainerPath, frodoContainerXml);
logConfig.setCDBLoggingConfigPath(cdbContainerPath);
logConfig.setCDB(testCDB);
try {
logConfig.initialize(true);
fail("LogConfigException was expected.");
}
catch (LogConfigException ex) {
assertEquals("Log config initialization at least partially failed. Failed to parse XML for CDB node MACI/Containers/frodoContainer into binding classes " +
"(ex=org.exolab.castor.xml.MarshalException, msg='The following error occured while trying to unmarshal field _minLogLevel of class alma.maci.loggingconfig.LoggingConfig\n" +
"For input string: \"NotANumber\"'). ", ex.getMessage());
}
testCDB.setThrowException(true);
try {
logConfig.initialize(true);
fail("LogConfigException was expected.");
}
catch (LogConfigException ex) {
assertEquals("Log config initialization at least partially failed. Node MACI/Containers/frodoContainer does not exist in the CDB (msg='CDB record does not exist'). ", ex.getMessage());
}
}
/**
* Tests runtime changes as they could happen via the {@linkplain LoggingConfigurable} API.
*/
public void testDynamicChanges() throws Exception {
logger.info("============ Running testDynamicChanges ============");
// the default log levels from schema defaults and optional env var setting
int defaultMinLogLevel = logConfig.getDefaultMinLogLevel();
int defaultMinLogLevelLocal = logConfig.getDefaultMinLogLevelLocal();
// change the default log levels
logConfig.setDefaultMinLogLevel(defaultMinLogLevel + 1);
assertEquals(defaultMinLogLevel + 1, logConfig.getDefaultMinLogLevel());
assertEquals(defaultMinLogLevelLocal, logConfig.getDefaultMinLogLevelLocal());
logConfig.setDefaultMinLogLevel(defaultMinLogLevel + 2);
logConfig.setDefaultMinLogLevelLocal(defaultMinLogLevelLocal + 2);
assertEquals(defaultMinLogLevel + 2, logConfig.getDefaultMinLogLevel());
assertEquals(defaultMinLogLevelLocal + 2, logConfig.getDefaultMinLogLevelLocal());
logConfig.setDefaultMinLogLevel(defaultMinLogLevel); // restore initial values
logConfig.setDefaultMinLogLevelLocal(defaultMinLogLevelLocal);
// named logger levels
String knownLoggerName = "knownLogger";
UnnamedLogger knownLoggerConfig = logConfig.getNamedLoggerConfig(knownLoggerName); // now the logger is known, even though it has default values
assertEquals(defaultMinLogLevel, knownLoggerConfig.getMinLogLevel());
assertEquals(defaultMinLogLevelLocal, knownLoggerConfig.getMinLogLevelLocal());
Set<String> loggerNames = logConfig.getLoggerNames();
assertEquals(1, loggerNames.size());
assertTrue(loggerNames.contains(knownLoggerName));
String unknownLoggerName = "unknownLogger";
logConfig.setMinLogLevel(3, unknownLoggerName); // first encounter with this logger when setting its levels
loggerNames = logConfig.getLoggerNames();
assertEquals(2, loggerNames.size());
assertTrue(loggerNames.contains(knownLoggerName));
assertTrue(loggerNames.contains(unknownLoggerName));
// make sure that returned objects are not "live" for the logConfig data
knownLoggerConfig = logConfig.getNamedLoggerConfig(knownLoggerName);
UnnamedLogger knownLoggerConfig2 = logConfig.getNamedLoggerConfig(knownLoggerName);
assertNotSame(knownLoggerConfig, knownLoggerConfig2);
knownLoggerConfig.setMinLogLevel(defaultMinLogLevel + 3);
assertEquals(defaultMinLogLevel, logConfig.getDefaultMinLogLevel());
logConfig.setDefaultMinLogLevel(defaultMinLogLevel + 4);
assertEquals(defaultMinLogLevel, knownLoggerConfig2.getMinLogLevel());
}
public void testLockingRemoteLevel() throws Exception {
logger.info("============ Running testLockingLevels ============");
// the default log levels from schema defaults and optional env var setting
int defaultMinLogLevel = logConfig.getDefaultMinLogLevel();
int defaultMinLogLevelLocal = logConfig.getDefaultMinLogLevelLocal();
// named logger levels
String loggerName = "jacorb@archiveContainer";
int lockedLevel = Integer.MAX_VALUE;
logConfig.getNamedLoggerConfig(loggerName); // now the logger is known, even though it has default values
logConfig.setAndLockMinLogLevel(lockedLevel, loggerName);
// once a level is locked, it must not be changed any more:
assertEquals(lockedLevel, logConfig.getNamedLoggerConfig(loggerName).getMinLogLevel());
logConfig.setMinLogLevel(2, loggerName);
assertEquals(lockedLevel, logConfig.getNamedLoggerConfig(loggerName).getMinLogLevel());
logConfig.setAndLockMinLogLevel(2, loggerName);
assertEquals(lockedLevel, logConfig.getNamedLoggerConfig(loggerName).getMinLogLevel());
logConfig.clearNamedLoggerConfig(loggerName);
assertEquals(lockedLevel, logConfig.getNamedLoggerConfig(loggerName).getMinLogLevel());
logConfig.initialize(false);
logConfig.initialize(true);
String cdbContainerPath = "MACI/Containers/archiveContainer";
String archiveContainerXml =
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> " +
"<Container xmlns=\"urn:schemas-cosylab-com:Container:1.0\" xmlns:xsi=\"http:
"<LoggingConfig>" +
"<log:_ Name=\"" + loggerName + "\" minLogLevel=\"2\" minLogLevelLocal=\"2\" />" +
"<log:_ Name=\"unlockedLogger\" minLogLevel=\"6\" minLogLevelLocal=\"6\" />" +
"</LoggingConfig>" +
"</Container>";
TestCDB testCDB = new TestCDB();
testCDB.addCurlToXmlMapping(cdbContainerPath, archiveContainerXml);
logConfig.setCDBLoggingConfigPath(cdbContainerPath);
logConfig.setCDB(testCDB);
logConfig.initialize(true);
assertEquals(6, logConfig.getNamedLoggerConfig("unlockedLogger").getMinLogLevel()); // to make sure the CDB entry was considered
assertEquals(lockedLevel, logConfig.getNamedLoggerConfig(loggerName).getMinLogLevel());
assertTrue(logConfig.getNamedLoggerConfig(loggerName).isLocked());
}
// helper methods
private String createComponentsCdbXml(String compName, String type, String code, String container, boolean configureLogger, int minLogLevel, int minLogLevelLocal) {
String xml =
"<_ Name=\"" + compName + "\"" +
" Type=\"" + type + "\"" +
" Code=\"" + code + "\"" +
" Container=\"" + container + "\">";
if (configureLogger) {
xml +=
"<ComponentLogger minLogLevel=\"" + minLogLevel + "\" minLogLevelLocal=\"" + minLogLevelLocal + "\" />";
}
xml += "</_>";
return xml;
}
}
|
package alma.acs.logging.config;
import junit.framework.TestCase;
import alma.acs.logging.ACSCoreLevel;
import alma.acs.testsupport.TestLogger;
import alma.maci.loggingconfig.LoggingConfig;
import alma.maci.loggingconfig.UnnamedLogger;
public class LogConfigTest extends TestCase {
private LogConfig logConfig;
public LogConfigTest() {
super("LogConfigTest");
logConfig = new LogConfig();
logConfig.setInternalLogger(TestLogger.getLogger("LogConfigTest"));
}
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
private static class CountingLogConfigSubscriber implements LogConfigSubscriber {
volatile int count = 0;
public void configureLogging(LogConfig logConfig) {
assertNotNull(logConfig);
count++;
}
}
/**
* Tests adding and removing of subscribers, and whether {@link LogConfig#initialize(boolean)}
* triggers correctly the notification of these subscribers.
*/
public void testSubscriberNotification() throws LogConfigException {
int numSubscribers = 10;
CountingLogConfigSubscriber[] configSubscribers = new CountingLogConfigSubscriber[numSubscribers];
for (int i = 0; i < numSubscribers; i++) {
configSubscribers[i] = new CountingLogConfigSubscriber();
logConfig.addSubscriber(configSubscribers[i]);
// as a stupid client we add some subscribers again but expect this to have no side effect
if (i%2 == 0) {
logConfig.addSubscriber(configSubscribers[i]);
}
}
logConfig.initialize(false); // should call "configureLogging" on all subscribers
for (int i = 0; i < numSubscribers; i++) {
assertEquals(1, configSubscribers[i].count);
}
// now remove a few subscribers and assert they don't get called again, and that the remaining ones get called again
int numRemainingSubscribers = 3;
assertTrue(numSubscribers > numRemainingSubscribers);
for (int i = 0; i < numSubscribers - numRemainingSubscribers; i++) {
logConfig.removeSubscriber(configSubscribers[i]);
}
logConfig.initialize(false);
for (int i = 0; i < numSubscribers - numRemainingSubscribers; i++) {
assertEquals(1, configSubscribers[i].count);
}
for (int i = numSubscribers - numRemainingSubscribers; i < numSubscribers; i++) {
assertEquals(2, configSubscribers[i].count);
}
}
/**
* Tests the config values returned from {@link LogConfig#getLoggingConfig()}
* and {@link LogConfig#getNamedLoggerConfig(String)} in the pristine state of our LogConfig object,
* that is, without CDB or other property information being considered.
* <p>
* Also asserts that none of these calls return the original object,
* but instead a copy of it. This indirectly exercises the equals method.
*/
public void testDefaultValues() throws Exception {
LoggingConfig defaultLogConfig = logConfig.getLoggingConfig();
assertEquals("Log", defaultLogConfig.getCentralizedLogger());
assertEquals(10, defaultLogConfig.getDispatchPacketSize());
assertEquals(ACSCoreLevel.ACS_LEVEL_TRACE, defaultLogConfig.getMinLogLevel());
int expectedMinLogLevelLocal = ACSCoreLevel.ACS_LEVEL_TRACE;
// TAT defines ACS_LOG_STDOUT, so the test must take this into account
Integer ACS_LOG_STDOUT = Integer.getInteger(LogConfig.PROPERTYNAME_MIN_LOG_LEVEL_LOCAL);
if (ACS_LOG_STDOUT != null) {
expectedMinLogLevelLocal = ACS_LOG_STDOUT.intValue();
}
assertEquals(expectedMinLogLevelLocal, defaultLogConfig.getMinLogLevelLocal());
assertEquals(ACSCoreLevel.ACS_LEVEL_ALERT, defaultLogConfig.getImmediateDispatchLevel());
LoggingConfig defaultLogConfig2 = logConfig.getLoggingConfig();
// assertNotSame(defaultLogConfig, defaultLogConfig2); // commented out because currently we don't copy/hide the instance
assertEquals(defaultLogConfig, defaultLogConfig2);
UnnamedLogger namedLogConfig1 = logConfig.getNamedLoggerConfig(null); // name=null should yield default config
assertEquals(defaultLogConfig.getMinLogLevel(), namedLogConfig1.getMinLogLevel());
assertEquals(defaultLogConfig.getMinLogLevelLocal(), namedLogConfig1.getMinLogLevelLocal());
UnnamedLogger namedLogConfig2 = logConfig.getNamedLoggerConfig("nonExistingLogger");
assertNotSame(namedLogConfig1, namedLogConfig2);
assertEquals(namedLogConfig1.getMinLogLevel(), namedLogConfig2.getMinLogLevel());
assertEquals(namedLogConfig1.getMinLogLevelLocal(), namedLogConfig2.getMinLogLevelLocal());
}
public void testCDBValues() throws Exception {
String cdbContainerPath = "MACI/Containers/frodoContainer";
String frodoContainerXml =
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> " +
"<Container xmlns=\"urn:schemas-cosylab-com:Container:1.0\" xmlns:xsi=\"http:
"<LoggingConfig " +
" minLogLevel=\"2\" " +
" minLogLevelLocal=\"3\" " +
" centralizedLogger=\"LogForFrodo\" " +
" maxLogQueueSize=\"200\" " +
" immediateDispatchLevel=\"7\" " +
" dispatchPacketSize=\"33\" " +
" >" +
"<log:_ Name=\"MyMuteComponent\" minLogLevel=\"5\" minLogLevelLocal=\"6\" />" +
"</LoggingConfig>" +
"</Container>";
TestCDB testCDB = new TestCDB();
testCDB.addCurlToXmlMapping(cdbContainerPath, frodoContainerXml);
logConfig.setCDBLoggingConfigPath(cdbContainerPath);
logConfig.setCDB(testCDB);
logConfig.initialize(true);
LoggingConfig updatedConfig = logConfig.getLoggingConfig();
assertEquals("LogForFrodo", updatedConfig.getCentralizedLogger());
assertEquals(7, updatedConfig.getImmediateDispatchLevel());
assertEquals(33, updatedConfig.getDispatchPacketSize());
assertEquals(10, updatedConfig.getFlushPeriodSeconds()); // was not in CDB, thus default should be used
assertEquals(2, updatedConfig.getMinLogLevel());
assertEquals(3, updatedConfig.getMinLogLevelLocal());
UnnamedLogger myMuteloggerConfig = logConfig.getNamedLoggerConfig("MyMuteComponent");
assertEquals(5, myMuteloggerConfig.getMinLogLevel());
assertEquals(6, myMuteloggerConfig.getMinLogLevelLocal());
// TODO: test logConfig.setCDBComponentPath() with some real XML added to the test CDB, once this is implemented
// Problem currently is that <_> elements for each component can't be accessed.
String componentsXml =
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> " +
"<Components xmlns=\"urn:schemas-cosylab-com:Components:1.0\" xmlns:cdb=\"urn:schemas-cosylab-com:CDB:1.0\" xmlns:xsi=\"http:
createComponentsCdbXml("testComp1", "IDL_TYPE_1", "some.class", "zampaione", true, 0, 8) +
"</Components>";
// String cdbComponentsPath = "MACI/Components";
// logConfig.setCDBComponentPath(compLoggerName, cdbComponentsPath)
}
/**
* Checks the response to bad CDB data and CDB access problems.
*/
public void testInvalidCDB() throws Exception {
String cdbContainerPath = "MACI/Containers/frodoContainer";
String frodoContainerXml =
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> " +
"<Container xmlns=\"urn:schemas-cosylab-com:Container:1.0\" xmlns:xsi=\"http:
"<LoggingConfig " +
" minLogLevel=\"NotANumber\" " + // should cause an error
" minLogLevelLocal=\"3\" " +
" centralizedLogger=\"LogForFrodo\" " +
" maxLogQueueSize=\"200\" " +
" immediateDispatchLevel=\"\" " + // empty attr should be ignored w/o message
" myMisfittingAttribute=\"ShouldNotMatterThough\" " + // again no err message expected for this
" dispatchPacketSize=\"33\" " +
" flushPeriodSeconds=\"5\" " +
" />" +
"</Container>";
TestCDB testCDB = new TestCDB();
testCDB.addCurlToXmlMapping(cdbContainerPath, frodoContainerXml);
logConfig.setCDBLoggingConfigPath(cdbContainerPath);
logConfig.setCDB(testCDB);
try {
logConfig.initialize(true);
fail("LogConfigException was expected.");
}
catch (LogConfigException ex) {
assertEquals("Log config initialization at least partially failed. Failed to parse XML for CDB node MACI/Containers/frodoContainer into binding classes " +
"(ex=org.exolab.castor.xml.MarshalException, msg='The following error occured while trying to unmarshal field _minLogLevel of class alma.maci.loggingconfig.LoggingConfig\n" +
"For input string: \"NotANumber\"'). ", ex.getMessage());
}
testCDB.setThrowException(true);
try {
logConfig.initialize(true);
fail("LogConfigException was expected.");
}
catch (LogConfigException ex) {
assertEquals("Log config initialization at least partially failed. Node MACI/Containers/frodoContainer does not exist in the CDB (msg='CDB record does not exist'). ", ex.getMessage());
}
}
// helper methods
private String createComponentsCdbXml(String compName, String type, String code, String container, boolean configureLogger, int minLogLevel, int minLogLevelLocal) {
String xml =
"<_ Name=\"" + compName + "\"" +
" Type=\"" + type + "\"" +
" Code=\"" + code + "\"" +
" Container=\"" + container + "\">";
if (configureLogger) {
xml +=
"<ComponentLogger minLogLevel=\"" + minLogLevel + "\" minLogLevelLocal=\"" + minLogLevelLocal + "\" />";
}
xml += "</_>";
return xml;
}
}
|
import javax.swing.*;
import java.awt.event.*;
import java.util.Arrays;
import java.util.Calendar;
import java.util.TimeZone;
public class TimezoneMenu {
//Menu Components
private JMenuBar menuBar;
private JMenu menu, submenu;
private JMenuItem menuItem;
private JRadioButtonMenuItem standardTimezone, allTimezone, africaTimezone, americaTimezone, asiaTimezone, australiaTimezone, europeTimezone, pacificTimezone, usTimezone;
//Item Listeners
private ItemListener standardListener;
private ItemListener allListener;
private ItemListener africaListener;
private ItemListener americaListener;
private ItemListener asiaListener;
private ItemListener australiaListener;
private ItemListener europeListener;
private ItemListener pacificListener;
private ItemListener usListener;
//Time Info
String currentTZ = Calendar.getInstance().getTimeZone().getID();
String[] allTimezoneList = TimeZone.getAvailableIDs();
String[] standardTimezoneList = {"Africa/Algiers", "Africa/Cairo", "Africa/Casablanca", "Africa/Harare", "Africa/Nairobi", "Africa/Windhoek", "America/Bogota", "America/Buenos_Aires", "America/Caracas", "America/Chihuahua", "America/Guatemala", "America/Mexico_City", "America/Montevideo", "America/Santiago", "America/Tijuana", "Asia/Amman", "Asia/Baghdad", "Asia/Baku", "Asia/Bangkok", "Asia/Beirut", "Asia/Calcutta", "Asia/Colombo", "Asia/Dhaka", "Asia/Hong_Kong", "Asia/Irkutsk", "Asia/Jerusalem", "Asia/Kabul", "Asia/Karachi", "Asia/Katmandu", "Asia/Krasnoyarsk", "Asia/Kuala_Lumpur", "Asia/Kuwait", "Asia/Magadan", "Asia/Muscat", "Asia/Novosibirsk", "Asia/Rangoon", "Asia/Seoul", "Asia/Shanghai","Asia/Taipei", "Asia/Tbilisi", "Asia/Tehran", "Asia/Tokyo", "Asia/Vladivostok", "Asia/Yakutsk", "Asia/Yekaterinburg", "Asia/Yerevan", "Atlantic/Azores", "Atlantic/Cape_Verde", "Australia/Adelaide", "Australia/Brisbane", "Australia/Darwin", "Australia/Hobart", "Australia/Perth", "Australia/Sydney", "Brazil/East", "Canada/Eastern", "Canada/Newfoundland", "Canada/Saskatchewan", "Europe/Athens", "Europe/Belgrade", "Europe/Berlin", "Europe/Brussels", "Europe/Helsinki", "Europe/London", "Europe/Minsk", "Europe/Moscow", "Europe/Paris", "Europe/Warsaw", "Pacific/Auckland", "Pacific/Fiji", "Pacific/Guam", "Pacific/Midway", "US/Alaska", "US/Arizona", "US/Central", "US/East-Indiana", "US/Eastern", "US/Hawaii", "US/Mountain", "US/Pacific", "UTC"} ;
String[] africaTimezoneList = {"Africa/Abidjan", "Africa/Accra", "Africa/Addis_Ababa", "Africa/Algiers", "Africa/Asmera", "Africa/Bamako", "Africa/Bangui", "Africa/Banjul", "Africa/Bissau", "Africa/Blantyre", "Africa/Brazzaville", "Africa/Bujumbura", "Africa/Cairo", "Africa/Casablanca", "Africa/Ceuta", "Africa/Conakry", "Africa/Dakar", "Africa/Dar_es_Salaam", "Africa/Djibouti", "Africa/Douala", "Africa/El_Aaiun", "Africa/Freetown", "Africa/Gaborone", "Africa/Harare", "Africa/Johannesburg", "Africa/Kampala", "Africa/Khartoum", "Africa/Kigali", "Africa/Kinshasa", "Africa/Lagos", "Africa/Libreville", "Africa/Lome", "Africa/Luanda", "Africa/Lubumbashi", "Africa/Lusaka", "Africa/Malabo", "Africa/Maputo", "Africa/Maseru", "Africa/Mbabane", "Africa/Mogadishu", "Africa/Monrovia", "Africa/Nairobi", "Africa/Ndjamena", "Africa/Niamey", "Africa/Nouakchott", "Africa/Ouagadougou", "Africa/Porto-Novo", "Africa/Sao_Tome", "Africa/Timbuktu", "Africa/Tripoli", "Africa/Tunis", "Africa/Windhoek"};
String[] americaTimezoneList = {"America/Belize", "America/Boa_Vista", "America/Bogota", "America/Boise", "America/Buenos_Aires", "America/Cambridge_Bay", "America/Campo_Grande", "America/Cancun", "America/Caracas", "America/Catamarca", "America/Cayenne", "America/Cayman", "America/Chicago", "America/Chihuahua", "America/Cordoba", "America/Costa_Rica", "America/Cuiaba", "America/Curacao", "America/Danmarkshavn", "America/Dawson", "America/Dawson_Creek", "America/Denver", "America/Detroit", "America/Dominica", "America/Edmonton", "America/Eirunepe", "America/El_Salvador", "America/Ensenada", "America/Fort_Wayne", "America/Fortaleza", "America/Glace_Bay", "America/Godthab", "America/Goose_Bay", "America/Grand_Turk", "America/Grenada", "America/Guadeloupe", "America/Guatemala", "America/Guayaquil", "America/Guyana", "America/Halifax", "America/Havana", "America/Hermosillo", "America/Indiana/Indianapolis", "America/Indiana/Knox", "America/Indiana/Marengo", "America/Indiana/Vevay", "America/Indianapolis", "America/Inuvik", "America/Iqaluit", "America/Jamaica", "America/Jujuy", "America/Juneau", "America/Kentucky/Louisville", "America/Kentucky/Monticello", "America/Knox_IN", "America/La_Paz", "America/Lima", "America/Los_Angeles", "America/Louisville", "America/Maceio", "America/Managua", "America/Manaus", "America/Martinique", "America/Mazatlan", "America/Mendoza", "America/Menominee", "America/Merida", "America/Mexico_City", "America/Miquelon", "America/Monterrey", "America/Montevideo", "America/Montreal", "America/Montserrat", "America/Nassau", "America/New_York", "America/Nipigon", "America/Nome", "America/Noronha", "America/North_Dakota/Center", "America/Panama", "America/Pangnirtung", "America/Paramaribo", "America/Phoenix", "America/Port_of_Spain", "America/Port-au-Prince", "America/Porto_Acre", "America/Porto_Velho", "America/Puerto_Rico", "America/Rainy_River", "America/Rankin_Inlet", "America/Recife", "America/Regina", "America/Rio_Branco", "America/Rosario", "America/Santiago", "America/Santo_Domingo", "America/Sao_Paulo", "America/Scoresbysund", "America/Shiprock", "America/St_Johns", "America/St_Kitts", "America/St_Lucia", "America/St_Thomas", "America/St_Vincent", "America/Swift_Current", "America/Tegucigalpa", "America/Thule", "America/Thunder_Bay", "America/Tijuana", "America/Toronto", "America/Tortola", "America/Vancouver", "America/Virgin", "America/Whitehorse", "America/Winnipeg", "America/Yakutat", "America/Yellowknife"};
String[] asiaTimezoneList = {"Asia/Aden", "Asia/Almaty", "Asia/Amman", "Asia/Anadyr", "Asia/Aqtau", "Asia/Aqtobe", "Asia/Ashgabat", "Asia/Ashkhabad", "Asia/Baghdad", "Asia/Bahrain", "Asia/Baku", "Asia/Bangkok", "Asia/Beirut", "Asia/Bishkek", "Asia/Brunei", "Asia/Calcutta", "Asia/Choibalsan", "Asia/Chongqing", "Asia/Chungking", "Asia/Colombo", "Asia/Dacca", "Asia/Damascus", "Asia/Dhaka", "Asia/Dili", "Asia/Dubai", "Asia/Dushanbe", "Asia/Gaza", "Asia/Harbin", "Asia/Hong_Kong", "Asia/Hovd", "Asia/Irkutsk", "Asia/Istanbul", "Asia/Jakarta", "Asia/Jayapura", "Asia/Jerusalem", "Asia/Kabul", "Asia/Kamchatka", "Asia/Karachi", "Asia/Kashgar", "Asia/Katmandu", "Asia/Krasnoyarsk", "Asia/Kuala_Lumpur", "Asia/Kuching", "Asia/Kuwait", "Asia/Macao", "Asia/Macau", "Asia/Magadan", "Asia/Makassar", "Asia/Manila", "Asia/Muscat", "Asia/Nicosia", "Asia/Novosibirsk", "Asia/Omsk", "Asia/Oral", "Asia/Phnom_Penh", "Asia/Pontianak", "Asia/Pyongyang", "Asia/Qatar", "Asia/Qyzylorda", "Asia/Rangoon", "Asia/Riyadh", "Asia/Riyadh87", "Asia/Riyadh88", "Asia/Riyadh89", "Asia/Saigon", "Asia/Sakhalin", "Asia/Samarkand", "Asia/Seoul", "Asia/Shanghai", "Asia/Singapore", "Asia/Taipei", "Asia/Tashkent", "Asia/Tbilisi", "Asia/Tehran", "Asia/Tel_Aviv", "Asia/Thimbu", "Asia/Thimphu", "Asia/Tokyo", "Asia/Ujung_Pandang", "Asia/Ulaanbaatar", "Asia/Ulan_Bator", "Asia/Urumqi", "Asia/Vientiane", "Asia/Vladivostok", "Asia/Yakutsk", "Asia/Yekaterinburg", "Asia/Yerevan"};
String[] australiaTimezoneList = {"Australia/ACT", "Australia/Adelaide", "Australia/Brisbane", "Australia/Broken_Hill", "Australia/Canberra", "Australia/Darwin", "Australia/Hobart", "Australia/LHI", "Australia/Lindeman", "Australia/Lord_Howe", "Australia/Melbourne", "Australia/North", "Australia/NSW", "Australia/Perth", "Australia/Queensland", "Australia/South", "Australia/Sydney", "Australia/Tasmania", "Australia/Victoria", "Australia/West", "Australia/Yancowinna"};
String[] europeTimezoneList = {"Europe/Amsterdam", "Europe/Andorra", "Europe/Athens", "Europe/Belfast", "Europe/Belgrade", "Europe/Berlin", "Europe/Bratislava", "Europe/Brussels", "Europe/Bucharest", "Europe/Budapest", "Europe/Chisinau", "Europe/Copenhagen", "Europe/Dublin", "Europe/Gibraltar", "Europe/Helsinki", "Europe/Istanbul", "Europe/Kaliningrad", "Europe/Kiev", "Europe/Lisbon", "Europe/Ljubljana", "Europe/London", "Europe/Luxembourg", "Europe/Madrid", "Europe/Malta", "Europe/Minsk", "Europe/Monaco", "Europe/Moscow", "Europe/Nicosia", "Europe/Oslo", "Europe/Paris", "Europe/Prague", "Europe/Riga", "Europe/Rome", "Europe/Samara", "Europe/San_Marino", "Europe/Sarajevo", "Europe/Simferopol", "Europe/Skopje", "Europe/Sofia", "Europe/Stockholm", "Europe/Tallinn", "Europe/Tirane", "Europe/Tiraspol", "Europe/Uzhgorod", "Europe/Vaduz", "Europe/Vatican", "Europe/Vienna", "Europe/Vilnius", "Europe/Warsaw", "Europe/Zagreb", "Europe/Zaporozhye", "Europe/Zurich"};
String[] pacificTimezoneList = {"Pacific/Apia", "Pacific/Auckland", "Pacific/Chatham", "Pacific/Easter", "Pacific/Efate", "Pacific/Enderbury", "Pacific/Fakaofo", "Pacific/Fiji", "Pacific/Funafuti", "Pacific/Galapagos", "Pacific/Gambier", "Pacific/Guadalcanal", "Pacific/Guam", "Pacific/Honolulu", "Pacific/Johnston", "Pacific/Kiritimati ", "Pacific/Kosrae", "Pacific/Kwajalein", "Pacific/Majuro", "Pacific/Marquesas", "Pacific/Midway", "Pacific/Nauru", "Pacific/Niue", "Pacific/Norfolk", "Pacific/Noumea", "Pacific/Pago_Pago", "Pacific/Palau", "Pacific/Pitcairn", "Pacific/Ponape", "Pacific/Port_Moresby", "Pacific/Rarotonga", "Pacific/Saipan", "Pacific/Samoa", "Pacific/Tahiti", "Pacific/Tarawa", "Pacific/Tongatapu", "Pacific/Truk", "Pacific/Wake", "Pacific/Wallis", "Pacific/Yap"};
String[] usTimezoneList = {"US/Alaska", "US/Aleutian", "US/Arizona", "US/Central", "US/East-Indiana", "US/Eastern", "US/Hawaii", "US/Indiana-Starke", "US/Michigan", "US/Mountain", "US/Pacific", "US/Pacific-New", "US/Samoa"};
//JCombo boxes for Timezone
final JComboBox baseTimezoneBox;
final JComboBox newTimezoneBox;
public TimezoneMenu(JComboBox baseTimezoneBox, JComboBox newTimezoneBox){
this.baseTimezoneBox = baseTimezoneBox;
this.newTimezoneBox = newTimezoneBox;
createMenuBar();
}
public void createMenuBar() {
menu = new JMenu("Menu");
menuBar = new JMenuBar();
standardListener = new standardListener();
allListener = new allListener();
africaListener = new africaListener();
americaListener = new americaListener();
asiaListener = new asiaListener();
australiaListener = new australiaListener();
europeListener = new europeListener();
pacificListener = new pacificListener();
usListener = new usListener();
//a group of check box menu items
standardTimezone = new JRadioButtonMenuItem("Regular Timezone");
standardTimezone.setMnemonic(KeyEvent.VK_S);
standardTimezone.addItemListener(standardListener);
menu.add(standardTimezone);
allTimezone = new JRadioButtonMenuItem("All Timezone");
allTimezone.setMnemonic(KeyEvent.VK_A);
allTimezone.addItemListener(allListener);
menu.add(allTimezone);
//Sub Menu Bar
submenu = new JMenu("Region");
submenu.setMnemonic(KeyEvent.VK_R);
africaTimezone = new JRadioButtonMenuItem("Africa");
africaTimezone.addItemListener(africaListener);
submenu.add(africaTimezone);
americaTimezone = new JRadioButtonMenuItem("America");
americaTimezone.addItemListener(americaListener);
submenu.add(americaTimezone);
asiaTimezone = new JRadioButtonMenuItem("Asia");
asiaTimezone.addItemListener(asiaListener);
submenu.add(asiaTimezone);
australiaTimezone = new JRadioButtonMenuItem("Australia");
australiaTimezone.addItemListener(australiaListener);
submenu.add(australiaTimezone);
europeTimezone = new JRadioButtonMenuItem("Europe");
europeTimezone.addItemListener(europeListener);
submenu.add(europeTimezone);
pacificTimezone = new JRadioButtonMenuItem("Pacific");
pacificTimezone.addItemListener(pacificListener);
submenu.add(pacificTimezone);
usTimezone = new JRadioButtonMenuItem("US");
usTimezone.addItemListener(usListener);
submenu.add(usTimezone);
menu.add(submenu);
//Final Quit Menu
menuItem = new JMenuItem("Quit", KeyEvent.VK_Q);
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
menuItem.addActionListener(new quitListener());
menu.addSeparator();
menu.add(menuItem);
standardTimezone.setSelected(true);
menuBar.add(menu);
}
public void setTimezoneList(String[] timezoneList){
Arrays.sort(timezoneList);
baseTimezoneBox.removeAllItems();
newTimezoneBox.removeAllItems();
for (String tz : timezoneList){
baseTimezoneBox.addItem(tz);
newTimezoneBox.addItem(tz);
}
baseTimezoneBox.setSelectedItem(currentTZ);
newTimezoneBox.setSelectedItem("UTC");
}
public JMenuBar getMenuBar(){
return menuBar;
}
public String[] getStandardTimezoneList(){
return standardTimezoneList;
}
public void deselectItems(){
standardTimezone.setSelected(false);
allTimezone.setSelected(false);
africaTimezone.setSelected(false);
americaTimezone.setSelected(false);
asiaTimezone.setSelected(false);
australiaTimezone.setSelected(false);
europeTimezone.setSelected(false);
pacificTimezone.setSelected(false);
usTimezone.setSelected(false);
}
public class quitListener implements ActionListener {
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
public class allListener implements ItemListener {
public void itemStateChanged(ItemEvent e){
removeListeners();
deselectItems();
allTimezone.setSelected(true);
setTimezoneList(allTimezoneList);
addListeners();
}
}
public class standardListener implements ItemListener{
public void itemStateChanged(ItemEvent e){
removeListeners();
deselectItems();
standardTimezone.setSelected(true);
setTimezoneList(standardTimezoneList);
addListeners();
}
}
public class africaListener implements ItemListener {
public void itemStateChanged(ItemEvent e){
removeListeners();
deselectItems();
africaTimezone.setSelected(true);
setTimezoneList(africaTimezoneList);
addListeners();
}
}
public class americaListener implements ItemListener {
public void itemStateChanged(ItemEvent e){
removeListeners();
deselectItems();
americaTimezone.setSelected(true);
setTimezoneList(americaTimezoneList);
addListeners();
}
}
public class asiaListener implements ItemListener {
public void itemStateChanged(ItemEvent e){
removeListeners();
deselectItems();
asiaTimezone.setSelected(true);
setTimezoneList(asiaTimezoneList);
addListeners();
}
}
public class australiaListener implements ItemListener {
public void itemStateChanged(ItemEvent e){
removeListeners();
deselectItems();
australiaTimezone.setSelected(true);
setTimezoneList(australiaTimezoneList);
addListeners();
}
}
public class europeListener implements ItemListener {
public void itemStateChanged(ItemEvent e){
removeListeners();
deselectItems();
europeTimezone.setSelected(true);
setTimezoneList(europeTimezoneList);
addListeners();
}
}
public class pacificListener implements ItemListener {
public void itemStateChanged(ItemEvent e){
removeListeners();
deselectItems();
pacificTimezone.setSelected(true);
setTimezoneList(pacificTimezoneList);
addListeners();
}
}
public class usListener implements ItemListener {
public void itemStateChanged(ItemEvent e){
removeListeners();
deselectItems();
usTimezone.setSelected(true);
setTimezoneList(usTimezoneList);
addListeners();
}
}
public void removeListeners(){
standardTimezone.removeItemListener(standardListener);
allTimezone.removeItemListener(allListener);
africaTimezone.removeItemListener(africaListener);
americaTimezone.removeItemListener(americaListener);
asiaTimezone.removeItemListener(asiaListener);
australiaTimezone.removeItemListener(australiaListener);
europeTimezone.removeItemListener(europeListener);
pacificTimezone.removeItemListener(pacificListener);
usTimezone.removeItemListener(usListener);
}
public void addListeners(){
standardTimezone.addItemListener(standardListener);
allTimezone.addItemListener(allListener);
africaTimezone.addItemListener(africaListener);
americaTimezone.addItemListener(americaListener);
asiaTimezone.addItemListener(asiaListener);
australiaTimezone.addItemListener(australiaListener);
europeTimezone.addItemListener(europeListener);
pacificTimezone.addItemListener(pacificListener);
usTimezone.addItemListener(usListener);
}
}
|
package uk.ac.ucl.excites.sapelli.collector;
import uk.ac.ucl.excites.sapelli.collector.db.ProjectStore;
import uk.ac.ucl.excites.sapelli.collector.model.Form;
import uk.ac.ucl.excites.sapelli.collector.model.Project;
import uk.ac.ucl.excites.sapelli.storage.model.Record;
import uk.ac.ucl.excites.sapelli.storage.model.Schema;
import uk.ac.ucl.excites.sapelli.storage.util.UnknownModelException;
import uk.ac.ucl.excites.sapelli.transmission.EncryptionSettings;
import uk.ac.ucl.excites.sapelli.transmission.Payload;
import uk.ac.ucl.excites.sapelli.transmission.TransmissionClient;
/**
* @author mstevens
*
*/
public class SapelliCollectorClient implements TransmissionClient
{
/**
* @param project
* @return
*/
static public long GetModelID(Project project)
{
return GetModelID(project.getID(), project.hashCode());
}
/**
* @param projectID unsigned(!) 24 bit integer
* @param projectHash signed 32 bit integer
* @return unsigned 56 bit integer
*/
static public long GetModelID(int projectID, int projectHash)
{
return ((((long) projectHash) & 0xffffffffL) << Project.PROJECT_ID_SIZE) + // Project hash takes up first 32 bits
projectID; // Project id takes up next 24 bits
}
static public int GetProjectID(long modelID)
{
return (int) (modelID % (1 << Project.PROJECT_ID_SIZE));
}
static public int GetProjectHash(long modelID)
{
return (int) (modelID >> Project.PROJECT_ID_SIZE);
}
static public short GetModelSchemaNo(Form form)
{
return form.getPosition();
}
private ProjectStore projectStore;
public SapelliCollectorClient(ProjectStore projectStore)
{
this.projectStore = projectStore;
}
/* (non-Javadoc)
* @see uk.ac.ucl.excites.sapelli.storage.StorageClient#getSchema(long, short)
*/
@Override
public Schema getSchema(long modelID, short modelSchemaNo) throws UnknownModelException
{
Project project = projectStore.retrieveProject(GetProjectID(modelID), GetProjectHash(modelID));
if(project != null)
return project.getForm(modelSchemaNo).getSchema();
else
throw new UnknownModelException(modelID, modelSchemaNo);
}
/* (non-Javadoc)
* @see uk.ac.ucl.excites.sapelli.storage.StorageClient#getNumberOfSchemataInModel(long)
*/
@Override
public short getNumberOfSchemataInModel(long modelID) throws UnknownModelException
{
Project project = projectStore.retrieveProject(GetProjectID(modelID), GetProjectHash(modelID));
if(project != null)
return (short) project.getForms().size();
else
throw new UnknownModelException(modelID);
}
/* (non-Javadoc)
* @see uk.ac.ucl.excites.sapelli.storage.StorageClient#getSchemaV1(int, int)
*/
@Override
public Schema getSchemaV1(int schemaID, int schemaVersion) throws UnknownModelException
{
Project project = projectStore.retrieveV1Project(schemaID, schemaVersion);
if(project != null)
return project.getForm(0).getSchema(); // return schema of the first (and assumed only) form
else
throw new UnknownModelException(schemaID, schemaVersion);
}
@Override
public void recordInserted(Record record)
{
// TODO Auto-generated method stub
}
@Override
public void recordUpdated(Record record)
{
// TODO Auto-generated method stub
}
@Override
public void recordDeleted(Record record)
{
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see uk.ac.ucl.excites.sapelli.transmission.TransmissionClient#getEncryptionSettingsFor(long)
*/
@Override
public EncryptionSettings getEncryptionSettingsFor(long modelID)
{
/*TODO FIX THIS
* This is buggy/hacky! Because schema's can be shared by multiple forms (and no schema ID/version duplicates are allowed)
* we cannot safely determine transmission settings based on the schema id/version.
*/
// List<Form> forms = dao.retrieveForms(schema.getID(), schema.getVersion());
// if(!forms.isEmpty())
// if(forms.get(0)/*HACK!*/.getProject() != null)
// return forms.get(0).getProject().getTransmissionSettings();
// else
// return null;
// else
// return null;
return null;
}
public Form getForm(Schema schema) throws IllegalArgumentException
{
long modelID = schema.getModelID();
Project project = projectStore.retrieveProject(GetProjectID(modelID), GetProjectHash(modelID));
if(project != null)
return project.getForm(schema.getModelSchemaNo());
else
throw new IllegalArgumentException("No matching form found!");
}
@Override
public Payload newPayload(int nonBuiltinType)
{
return null; // for now there are no Sapelli Collector-specific transmission payloads
}
}
|
import webcam.*;
import topcodes.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Dimension;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.util.Queue;
public class WebCamSample extends JPanel
implements ActionListener, WindowListener {
private static final long serialVersionUID = 1L;
/** The main app window */
protected JFrame frame;
/** Camera Manager dialog */
protected WebCam webcam;
/** TopCode scanner */
protected Scanner scanner;
/** Animates display */
protected Timer animator;
/** Panel */
JPanel pnlButton = new JPanel();
/** Button */
JButton btnSetOrientation = new JButton("Set Orientation");
public WebCamSample() {
super(true);
this.frame = new JFrame("TopCodes Webcam Sample");
this.webcam = new WebCam();
this.scanner = new Scanner();
this.animator = new Timer(100, this); // 10 frames / second
// Set up the application frame
setOpaque(true);
setPreferredSize(new Dimension(640, 480)); //Dimension of player: 640 x 480
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setContentPane(this);
frame.addWindowListener(this);
frame.pack();
frame.setVisible(true);
btnSetOrientation.setBounds(60, 400, 220, 30);
pnlButton.setBounds(800, 800, 200, 100);
pnlButton.add(btnSetOrientation);
add(pnlButton);
btnSetOrientation.setBorderPainted(false);
btnSetOrientation.setOpaque(false);
frame.setTitle("TOPCode Viewer");
/**This code segment will open an infinite amount of java applications running video
Do not uncomment out these lines.*/
// WebCamSample WinSize = new WebCamSample();
// WinSize.setSize(700, 520);
// frame.getContentPane().add(WinSize);
// frame.pack();
// frame.setVisible(true);
// Connect to the webcam (this might fail if the
// camera isn't connected yet).
try {
this.webcam.initialize();
// This can be set to other resolutions like
// (320x240) or (1600x1200) depending on what
// your camera supports
this.webcam.openCamera(640, 480); //Dimension of webcam
} catch (Exception x) {
x.printStackTrace();
}
requestFocusInWindow();
animator.start();
}
protected void paintComponent(Graphics graphics) {
Graphics2D g = (Graphics2D)graphics;
List<TopCode> codes = null;
//ArrayList<TopCode> filter = new ArrayList<TopCode>(3);
//filter.add(top.getCode());
// Capture a frame from the video stream and scan it for
// TopCodes.
try {
if (webcam.isCameraOpen()) {
webcam.captureFrame();
codes = scanner.scan(
webcam.getFrameData(),
webcam.getFrameWidth(),
webcam.getFrameHeight());
}
} catch (WebCamException wcx) {
System.err.println(wcx);
}
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON
);
BufferedImage image = scanner.getImage();
if (image != null) {
g.drawImage(image, 0, 0, null);
}
if (codes != null) {
for (TopCode top : codes) {
// Draw the topcode in place
top.draw(g);
int id = top.getCode();
float orientation = top.getOrientation();
float x = top.getCenterX();
float y = top.getCenterY();
System.out.println("id: " + id + " orientation: " + orientation + " pos: " + x + ", " + y);
}
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == animator) repaint();
}
/* WINDOW EVENTS */
public void windowClosing(WindowEvent e) {
this.webcam.closeCamera();
this.webcam.uninitialize();
frame.setVisible(false);
frame.dispose();
System.exit(0);
}
public void windowActivated(WindowEvent e) { }
public void windowClosed(WindowEvent e) { }
public void windowDeactivated(WindowEvent e) { }
public void windowDeiconified(WindowEvent e) { }
public void windowIconified(WindowEvent e) { }
public void windowOpened(WindowEvent e) { }
public void setCode() {}
public static void main(String[] args) {
// Fix cursor flicker problem (sort of :( )
System.setProperty("sun.java2d.noddraw", "true");
// Use standard Windows look and feel
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception x) { ; }
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new WebCamSample();
}
});
}
}
|
package latexstudio.editor;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import latexstudio.editor.remote.DbxState;
import latexstudio.editor.util.ApplicationUtils;
import org.apache.commons.io.IOUtils;
import org.fife.ui.autocomplete.AutoCompletion;
import org.fife.ui.autocomplete.BasicCompletion;
import org.fife.ui.autocomplete.CompletionProvider;
import org.fife.ui.autocomplete.DefaultCompletionProvider;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle.Messages;
import org.openide.util.NbPreferences;
import org.openide.windows.TopComponent;
/**
* Top component which displays the editor window.
*/
@ConvertAsProperties(
dtd = "-//latexstudio.editor//Editor//EN",
autostore = false
)
@TopComponent.Description(
preferredID = "EditorTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE",
persistenceType = TopComponent.PERSISTENCE_ALWAYS
)
@TopComponent.Registration(mode = "editor", openAtStartup = true)
@ActionID(category = "Window", id = "latexstudio.editor.EditorTopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
displayName = "#CTL_EditorAction",
preferredID = "EditorTopComponent"
)
@Messages({
"CTL_EditorAction=Editor",
"CTL_EditorTopComponent=Editor Window",
"HINT_EditorTopComponent=This is a Editor window"
})
public final class EditorTopComponent extends TopComponent {
private boolean dirty = false;
private File currentFile;
private DbxState dbxState;
private String latexPath;
private static final int AUTO_COMPLETE_DELAY = 700;
public EditorTopComponent() {
initComponents();
setName(Bundle.CTL_EditorTopComponent());
setDisplayName("welcome.tex");
setToolTipText(Bundle.HINT_EditorTopComponent());
putClientProperty(TopComponent.PROP_CLOSING_DISABLED, Boolean.TRUE);
putClientProperty(TopComponent.PROP_UNDOCKING_DISABLED, Boolean.TRUE);
Preferences pref = NbPreferences.forModule(LaTeXSettingsPanel.class);
String path = pref.get("latexPath", "");
pref.addPreferenceChangeListener(new PreferenceChangeListener() {
public void preferenceChange(PreferenceChangeEvent evt) {
if (evt.getKey().equals("latexPath")) {
latexPath = evt.getNewValue();
}
}
});
latexPath = path;
}
/**
* 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() {
jScrollPane1 = new javax.swing.JScrollPane();
rSyntaxTextArea = new org.fife.ui.rsyntaxtextarea.RSyntaxTextArea();
rSyntaxTextArea.setColumns(20);
rSyntaxTextArea.setRows(5);
rSyntaxTextArea.setSyntaxEditingStyle(org.openide.util.NbBundle.getMessage(EditorTopComponent.class, "EditorTopComponent.rSyntaxTextArea.syntaxEditingStyle")); // NOI18N
rSyntaxTextArea.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
rSyntaxTextAreaKeyReleased(evt);
}
});
jScrollPane1.setViewportView(rSyntaxTextArea);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void rSyntaxTextAreaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_rSyntaxTextAreaKeyReleased
dirty = true;
}//GEN-LAST:event_rSyntaxTextAreaKeyReleased
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JScrollPane jScrollPane1;
private org.fife.ui.rsyntaxtextarea.RSyntaxTextArea rSyntaxTextArea;
// End of variables declaration//GEN-END:variables
@Override
public void componentOpened() {
ApplicationUtils.deleteTempFiles();
CompletionProvider provider = createCompletionProvider();
AutoCompletion ac = new AutoCompletion(provider);
ac.setAutoActivationDelay(AUTO_COMPLETE_DELAY);
ac.setAutoActivationEnabled(true);
ac.setAutoCompleteEnabled(true);
ac.install(rSyntaxTextArea);
InputStream is = null;
try {
is = getClass().getResource("/latexstudio/editor/resources/welcome.tex").openStream();
String welcomeMessage = IOUtils.toString(is);
rSyntaxTextArea.setText(welcomeMessage);
setDirty(true);
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
} finally {
IOUtils.closeQuietly(is);
}
}
@Override
public void componentClosed() {
}
public String getEditorContent() {
return rSyntaxTextArea.getText();
}
public void setEditorContent(String text) {
rSyntaxTextArea.setText(text);
dirty = true;
}
public boolean isDirty() {
return dirty;
}
public void setDirty(boolean dirty) {
this.dirty = dirty;
}
public void undoAction() {
rSyntaxTextArea.undoLastAction();
}
public void redoAction() {
rSyntaxTextArea.redoLastAction();
}
public File getCurrentFile() {
return currentFile;
}
public void setCurrentFile(File currentFile) {
this.currentFile = currentFile;
setDisplayName(currentFile.getName());
}
public DbxState getDbxState() {
return dbxState;
}
public void setDbxState(DbxState dbxState) {
this.dbxState = dbxState;
}
public String getLatexPath() {
return latexPath;
}
private String findStartSymbol() {
String highlightedTextArea2 = null;
boolean toggle = true;
int carretCoordinates;
while (toggle) {
carretCoordinates = rSyntaxTextArea.getSelectionStart();
if (rSyntaxTextArea.getSelectedText().startsWith("\n") || rSyntaxTextArea.getSelectionStart() == 0) {
toggle = false;
if (rSyntaxTextArea.getSelectionStart() != 0) {
rSyntaxTextArea.select(carretCoordinates + 1, rSyntaxTextArea.getSelectionEnd());
highlightedTextArea2 = rSyntaxTextArea.getSelectedText();
return highlightedTextArea2;
} else {
rSyntaxTextArea.select(carretCoordinates, rSyntaxTextArea.getSelectionEnd());
highlightedTextArea2 = rSyntaxTextArea.getSelectedText();
return highlightedTextArea2;
}
} else {
carretCoordinates
rSyntaxTextArea.select(carretCoordinates, rSyntaxTextArea.getSelectionEnd());
}
}
highlightedTextArea2 = rSyntaxTextArea.getSelectedText();
return highlightedTextArea2;
}
public void commentOutText() {
String highlightedTextArea = rSyntaxTextArea.getSelectedText();
if (highlightedTextArea != null) {
highlightedTextArea = findStartSymbol();
if (highlightedTextArea.startsWith("%")) {
rSyntaxTextArea.replaceSelection(highlightedTextArea.replace("%", ""));
} else {
String[] array = highlightedTextArea.split("\n");
String tempStr = "";
for (int i = 0; i < array.length; i++) {
if (i != array.length - 1) {
array[i] = "%" + array[i] + "\n";
tempStr = tempStr + array[i];
} else {
array[i] = "%" + array[i];
tempStr = tempStr + array[i];
}
}
rSyntaxTextArea.replaceSelection(tempStr);
}
} else {
try {
int currentOffsetFromLineStart = rSyntaxTextArea.getCaretOffsetFromLineStart();
int currentCaretPosition = 0;
int lineStartPosition = 0;
currentCaretPosition = rSyntaxTextArea.getCaretPosition();
lineStartPosition = currentCaretPosition - currentOffsetFromLineStart;
String firstChar = rSyntaxTextArea.getText(lineStartPosition, lineStartPosition + 1);
if (firstChar.startsWith("%")) {
rSyntaxTextArea.replaceRange("", lineStartPosition, lineStartPosition + 1);
} else {
rSyntaxTextArea.replaceRange("%", lineStartPosition, lineStartPosition);
}
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
}
}
}
void writeProperties(java.util.Properties p) {
// better to version settings since initial version as advocated at
p.setProperty("version", "1.0");
// TODO store your settings
}
void readProperties(java.util.Properties p) {
String version = p.getProperty("version");
// TODO read your settings according to their version
}
private CompletionProvider createCompletionProvider() {
DefaultCompletionProvider provider = new DefaultCompletionProvider();
provider.setAutoActivationRules(true, "");
URL[] urls = new URL[3];
urls[0] = getClass().getResource("/latexstudio/editor/resources/tex.cwl");
urls[1] = getClass().getResource("/latexstudio/editor/resources/latex-document.cwl");
urls[2] = getClass().getResource("/latexstudio/editor/resources/latex-mathsymbols.cwl");
for (URL url : urls) {
InputStream is = null;
try {
is = url.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
if (!line.startsWith("
provider.addCompletion(new BasicCompletion(provider, line.substring(1)));
}
}
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
} finally {
IOUtils.closeQuietly(is);
}
}
return provider;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.epics.pvmanager.jca;
import gov.aps.jca.CAException;
import gov.aps.jca.CAStatus;
import gov.aps.jca.Channel;
import gov.aps.jca.Channel.ConnectionState;
import gov.aps.jca.Context;
import gov.aps.jca.Monitor;
import gov.aps.jca.dbr.*;
import gov.aps.jca.event.*;
import java.util.Date;
import org.epics.pvmanager.ValueCache;
import org.epics.pvmanager.data.AlarmSeverity;
import org.epics.pvmanager.data.AlarmStatus;
import org.epics.pvmanager.data.VDouble;
import org.epics.util.time.Timestamp;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
/**
*
* @author carcassi
*/
public class JCAVTypeAdapterSetTest {
public JCAVTypeAdapterSetTest() {
}
public static Channel mockChannel(final DBRType dbrType, final int count, final ConnectionState connState) {
return new Channel() {
@Override
public Context getContext() throws IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void destroy() throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ConnectionListener[] getConnectionListeners() throws IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void addConnectionListener(ConnectionListener l) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void removeConnectionListener(ConnectionListener l) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public AccessRightsListener[] getAccessRightsListeners() throws IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void addAccessRightsListener(AccessRightsListener l) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void removeAccessRightsListener(AccessRightsListener l) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getName() throws IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public DBRType getFieldType() throws IllegalStateException {
return dbrType;
}
@Override
public int getElementCount() throws IllegalStateException {
return count;
}
@Override
public ConnectionState getConnectionState() throws IllegalStateException {
return connState;
}
@Override
public String getHostName() throws IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean getReadAccess() throws IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean getWriteAccess() throws IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void put(byte[] value) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void put(byte[] value, PutListener l) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void put(short[] value) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void put(short[] value, PutListener l) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void put(int[] value) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void put(int[] value, PutListener l) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void put(float[] value) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void put(float[] value, PutListener l) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void put(double[] value) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void put(double[] value, PutListener l) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void put(String[] value) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void put(String[] value, PutListener l) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void putACKT(boolean value) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void putACKT(boolean value, PutListener l) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void putACKS(Severity severity) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void putACKS(Severity severity, PutListener l) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public DBR get(DBRType type, int count) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void get(DBRType type, int count, GetListener l) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Monitor addMonitor(DBRType type, int count, int mask, MonitorListener l) throws CAException, IllegalStateException {
throw new UnsupportedOperationException("Not supported yet.");
}
};
}
@Test
public void DBRFloatToVDouble1() {
ValueCache<Object> cache = new ValueCache<Object>(Object.class);
JCATypeAdapter adapter = JCAVTypeAdapterSet.DBRFloatToVDouble;
assertThat(adapter.match(cache, mockChannel(DBR_Float.TYPE, 1, ConnectionState.CONNECTED)), equalTo(1));
assertThat(adapter.match(cache, mockChannel(DBR_Float.TYPE, 5, ConnectionState.CONNECTED)), equalTo(0));
assertThat(adapter.match(cache, mockChannel(DBR_Double.TYPE, 1, ConnectionState.CONNECTED)), equalTo(0));
}
@Test
public void DBRFloatToVDouble2() {
ValueCache<VDouble> cache = new ValueCache<VDouble>(VDouble.class);
JCATypeAdapter adapter = JCAVTypeAdapterSet.DBRFloatToVDouble;
assertThat(adapter.match(cache, mockChannel(DBR_Float.TYPE, 1, ConnectionState.CONNECTED)), equalTo(1));
assertThat(adapter.match(cache, mockChannel(DBR_Float.TYPE, 5, ConnectionState.CONNECTED)), equalTo(0));
assertThat(adapter.match(cache, mockChannel(DBR_Double.TYPE, 1, ConnectionState.CONNECTED)), equalTo(0));
}
@Test
public void DBRFloatToVDouble3() {
ValueCache<String> cache = new ValueCache<String>(String.class);
JCATypeAdapter adapter = JCAVTypeAdapterSet.DBRFloatToVDouble;
assertThat(adapter.match(cache, mockChannel(DBR_Float.TYPE, 1, ConnectionState.CONNECTED)), equalTo(0));
assertThat(adapter.match(cache, mockChannel(DBR_Float.TYPE, 5, ConnectionState.CONNECTED)), equalTo(0));
assertThat(adapter.match(cache, mockChannel(DBR_Double.TYPE, 1, ConnectionState.CONNECTED)), equalTo(0));
}
@Test
public void DBRFloatToVDouble4() {
ValueCache<Object> cache = new ValueCache<Object>(Object.class);
JCATypeAdapter adapter = JCAVTypeAdapterSet.DBRFloatToVDouble;
Channel channel = mockChannel(DBR_Float.TYPE, 1, ConnectionState.CONNECTED);
Timestamp timestamp = Timestamp.of(1234567,1234);
DBR_TIME_Float value = createDBRTimeFloat(3.25F, Severity.MINOR_ALARM, Status.HIGH_ALARM, timestamp);
DBR_CTRL_Double meta = createMetadata();
MonitorEvent event = new MonitorEvent(channel, value, CAStatus.NORMAL);
adapter.updateCache(cache, channel, new JCAMessagePayload(meta, event));
assertThat(cache.getValue(), instanceOf(VDouble.class));
VDouble converted = (VDouble) cache.getValue();
assertThat(converted.getValue(), equalTo(3.25));
assertThat(converted.getAlarmSeverity(), equalTo(AlarmSeverity.MINOR));
assertThat(converted.getAlarmStatus(), equalTo(AlarmStatus.RECORD));
assertThat(converted.getTimestamp(), equalTo(timestamp));
assertThat(converted.getUpperDisplayLimit(), equalTo(10.0));
assertThat(converted.getUpperCtrlLimit(), equalTo(8.0));
assertThat(converted.getUpperAlarmLimit(), equalTo(6.0));
assertThat(converted.getUpperWarningLimit(), equalTo(4.0));
assertThat(converted.getLowerWarningLimit(), equalTo(-4.0));
assertThat(converted.getLowerAlarmLimit(), equalTo(-6.0));
assertThat(converted.getLowerCtrlLimit(), equalTo(-8.0));
assertThat(converted.getLowerDisplayLimit(), equalTo(-10.0));
}
@Test
public void DBRFloatToVDouble5() {
ValueCache<Object> cache = new ValueCache<Object>(Object.class);
JCATypeAdapter adapter = JCAVTypeAdapterSet.DBRFloatToVDouble;
Channel channel = mockChannel(DBR_Float.TYPE, 1, ConnectionState.DISCONNECTED);
Timestamp timestamp = Timestamp.of(1234567,1234);
DBR_TIME_Float value = createDBRTimeFloat(3.25F, Severity.MINOR_ALARM, Status.HIGH_ALARM, timestamp);
DBR_CTRL_Double meta = createMetadata();
MonitorEvent event = new MonitorEvent(channel, value, CAStatus.NORMAL);
adapter.updateCache(cache, channel, new JCAMessagePayload(meta, event));
assertThat(cache.getValue(), instanceOf(VDouble.class));
VDouble converted = (VDouble) cache.getValue();
assertThat(converted.getValue(), equalTo(3.25));
assertThat(converted.getAlarmSeverity(), equalTo(AlarmSeverity.UNDEFINED));
assertThat(converted.getAlarmStatus(), equalTo(AlarmStatus.CLIENT));
assertThat(converted.getTimestamp(), equalTo(timestamp));
assertThat(converted.getUpperDisplayLimit(), equalTo(10.0));
assertThat(converted.getUpperCtrlLimit(), equalTo(8.0));
assertThat(converted.getUpperAlarmLimit(), equalTo(6.0));
assertThat(converted.getUpperWarningLimit(), equalTo(4.0));
assertThat(converted.getLowerWarningLimit(), equalTo(-4.0));
assertThat(converted.getLowerAlarmLimit(), equalTo(-6.0));
assertThat(converted.getLowerCtrlLimit(), equalTo(-8.0));
assertThat(converted.getLowerDisplayLimit(), equalTo(-10.0));
}
private DBR_CTRL_Double createMetadata() {
DBR_CTRL_Double meta = new DBR_CTRL_Double();
meta.setUpperDispLimit(10);
meta.setUpperCtrlLimit(8);
meta.setUpperAlarmLimit(6);
meta.setUpperWarningLimit(4);
meta.setLowerWarningLimit(-4);
meta.setLowerAlarmLimit(-6);
meta.setLowerCtrlLimit(-8);
meta.setLowerDispLimit(-10);
return meta;
}
private DBR_TIME_Float createDBRTimeFloat(float number, gov.aps.jca.dbr.Severity severity, gov.aps.jca.dbr.Status status, org.epics.util.time.Timestamp timestamp) {
DBR_TIME_Float value = new DBR_TIME_Float(new float[]{number});
value.setSeverity(severity);
value.setStatus(status);
value.setTimeStamp(new TimeStamp(timestamp.getSec() - DataUtils.TS_EPOCH_SEC_PAST_1970, timestamp.getNanoSec()));
return value;
}
}
|
package eco.game;
public class Country {
/**
*
* This class represents and simulates another country
*
* @author phil, nate
*/
// Main Variables //
public Farmer farmer = new Farmer();
public Warrior warrior = new Warrior();
public Economy economy = new Economy();
public Wheat wheat = new Wheat();
public Land land = new Land();
// Country Variables //
public String name;
// Simulation Settings //
public Score score = new Score();
public boolean favorFarmers = true;
public boolean displacedEat = true;
public float desiredWarriorRatio = 0.15f;
public float desiredFarmerRatio = 0.85f;
public float fBirthRate = 0.03f;
public float fDeathRate = 0.02f;
public float fDefaultDeathRate = 0.02f;
public float wBirthRate = 0.008f;
public float wDeathRate = 0.002f;
public float wDefaultDeathRate = 0.002f;
public float farmerDeathRatio = 0.75f;
public float warriorDeathRatio = 0.75f;
public static float wheatRot = PlayerCountry.wheatRot;
public int landsize;
public boolean dead = false;
public AggressionScore aggression = new AggressionScore();
// Other Variables //
public int maxpop = 10000;
public int displaced = 0;
public Country(boolean favorFarmers, boolean displacedEat,
float desiredWarriorRatio, float desiredFarmerRatio) {
name = NameGen.generateRandom();
fBirthRate = Util.randFloat(0.01f, 0.07f);
fDeathRate = 0.02f;
fDefaultDeathRate = 0.02f;
wBirthRate = Util.randFloat(0.001f, 0.01f);
wDeathRate = 0.002f;
wDefaultDeathRate = 0.002f;
farmerDeathRatio = Util.randFloat(0.00f, 1f);
warriorDeathRatio = Util.randFloat(0.00f, 1f);
landsize = World.random.nextInt(4000) + 100;
maxpop = World.random.nextInt(4000) + 100;
}
public void tick() {
// Population growth //
if (farmer.getfPop() + warrior.getwPop() > maxpop) {
int overflow = farmer.getfPop() + warrior.getwPop() - maxpop;
int kfarmer = (int) (overflow * desiredFarmerRatio);
int kwarrior = (int) (overflow * desiredWarriorRatio);
farmer.addPop(-kfarmer);
warrior.addPop(-kwarrior);
displaced += overflow;
}
// Conscription //
float newPopulation = farmer.fPop(fBirthRate, fDeathRate) + warrior.wPop(wBirthRate, wDeathRate);
float newWarriors = newPopulation * desiredWarriorRatio;
newPopulation -= newWarriors;
farmer.addPop(newPopulation);
warrior.addPop(newWarriors);
warrior.setOldWPop(warrior.getwPop());
farmer.setOldFPop(farmer.getfPop());
// Hunger Calculations //
wheat.tWheat(farmer.getfPop(), farmer);
farmer.setTotalHunger(farmer.fHunger() * farmer.getfPop());
warrior.setTotalHunger(warrior.wHunger() * warrior.getwPop());
int warriorWheat = warrior.getTotalHunger();
int farmerWheat = farmer.getTotalHunger();
if (favorFarmers) {
farmerWheat = wheat.eatWheat(farmerWheat, economy);
warriorWheat = wheat.eatWheat(warriorWheat, economy);
} else {
warriorWheat = wheat.eatWheat(warriorWheat, economy);
farmerWheat = wheat.eatWheat(farmerWheat, economy);
}
if (farmerWheat != 0) {
int fDeath = (int) Math.round(((float) farmerWheat / (float) farmer
.getfHunger()) * farmerDeathRatio);
farmer.addPop(fDeath);
fDeathRate = Math.min(1f, fDeathRate + 0.001f);
}
else{
fDeathRate = Math.max(0f, fDeathRate - 0.001f);
}
if (warriorWheat != 0) {
int wDeath = (int) Math
.round(((float) warriorWheat / (float) warrior.getwHunger())
* warriorDeathRatio);
warrior.addPop(-wDeath);
wDeathRate = Math.min(1f, wDeathRate + 0.001f);
}
else{
wDeathRate = Math.max(0f, wDeathRate - 0.001f);
}
if (displacedEat) {
int displacedHungerConst = farmer.getfHunger() / 2;
int displacedHunger = displaced * displacedHungerConst;
displacedHunger = wheat.eatWheat(displacedHunger, economy);
if (displacedHunger != 0) {
int displacedDeath = (int) Math.round(((float) displacedHunger
/ (float) farmer.getfHunger() / 2f) * 1f);
displaced -= displacedDeath;
}
} else {
int displacedHungerConst = farmer.getfHunger() / 2;
int displacedHunger = displaced * displacedHungerConst;
if (displacedHunger != 0) {
int displacedDeath = (int) Math.round(((float) displacedHunger
/ (float) farmer.getfHunger() / 2f) * 1f);
displaced -= displacedDeath;
}
}
if (farmer.getfPop() <= 0 && warrior.getwPop() <= 0){
dead = true;
farmer.setfPop(0);
warrior.setwPop(0);
wheat.settWheat(0);
economy.setTreasury(0);
} else if (landsize <= 0){
dead = true;
farmer.setfPop(0);
warrior.setwPop(0);
wheat.settWheat(0);
economy.setTreasury(0);
}
// Economic Updates //
wheat.update(economy);
wheat.rot(wheatRot);
// Score //
int tick = PlayerCountry.year;
score.calculateTickScore(tick, farmer.getfPop(), warrior.getwPop(), wheat.gettWheat(), economy.getTreasury());
score.calculateAvgScore(tick);
score.calculateTickGrowth(tick);
score.calculateAvgGrowth(tick);
score.calculatePeakScore(tick);
score.calculateTotalScore(tick);
aggression.calculateAggressionScore(warrior.getwPop());
// War //
int diff = (Math.abs(aggression.aggressionScore - PlayerCountry.aggression.aggressionScore)) + 1;
int warMul = 100;
if (PlayerCountry.year < 250){
warMul = 1000;
}
if (World.random.nextInt(diff * warMul) == 0){
War.attackPlayer(this);
}
}
public int getScore(){
try{
return score.scoreAt(PlayerCountry.year - 1);
}
catch(Exception e){
return 0;
}
}
public void takeLand(int toTake){
if (toTake >= land.getLand()){
toTake -= land.getLand();
land.setLand(0);
landsize -= toTake;
} else{
land.setLand(land.getLand() - toTake);
}
}
}
|
package eco.game;
import static org.lwjgl.opengl.GL11.GL_QUADS;
import static org.lwjgl.opengl.GL11.glBegin;
import static org.lwjgl.opengl.GL11.glColor3f;
import static org.lwjgl.opengl.GL11.glEnd;
import static org.lwjgl.opengl.GL11.glTexCoord2f;
import static org.lwjgl.opengl.GL11.glVertex2f;
import java.util.ArrayList;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
public class MenuBar {
/**
*
* This class manages the rendering and logic for the menu bar
*
* @author phil, connor
*
*/
// Pane Variables //
private static int pane = 0;
private static ToggleButton statsPane = new ToggleButton(0,
10 + (6f * Main.height / 8f), 32, 6, 2, 7, 2, true);
private static ToggleButton econPane = new ToggleButton(0,
10 + (6f * Main.height / 8f) + 32, 32, 6, 2, 7, 2, false);
private static ToggleButton warPane = new ToggleButton(0,
10 + (6f * Main.height / 8f) + 64, 32, 6, 2, 7, 2, false);
private static ToggleButton logPane = new ToggleButton(0,
10 + (6f * Main.height / 8f) + 96, 32, 6, 2, 7, 2, false);
private static ToggleButton graphsPane = new ToggleButton(0,
10 + (6f * Main.height / 8f) + 128, 32, 6, 2, 7, 2, false);
private static ArrayList<Button> buttons = new ArrayList<Button>();
private static TextureAtlas atlas = Render.atlas;
// Control Pane //
private static ArrayList<Button> pane0Buttons = new ArrayList<Button>();
// War Pane //
private static Button warUp = new Button(40, 575, 48, 0, 2, 1, 2);
private static Button warDown = new Button(40, 645, 48, 2, 2, 3, 2);
private static TextButton warOne = new TextButton(100,
(Main.height / 8f * 6f) + 16, 176, 20, 6, 2, 7, 2, "Declare War");
private static TextButton warTwo = new TextButton(100,
(Main.height / 8f * 6f) + 16 + (20 * 1), 176, 20, 6, 2, 7, 2,
"Declare War");
private static TextButton warThree = new TextButton(100,
(Main.height / 8f * 6f) + 16 + (20 * 2), 176, 20, 6, 2, 7, 2,
"Declare War");
private static TextButton warFour = new TextButton(100,
(Main.height / 8f * 6f) + 16 + (20 * 3), 176, 20, 6, 2, 7, 2,
"Declare War");
private static TextButton warFive = new TextButton(100,
(Main.height / 8f * 6f) + 16 + (20 * 4), 176, 20, 6, 2, 7, 2,
"Declare War");
private static TextButton warSix = new TextButton(100,
(Main.height / 8f * 6f) + 16 + (20 * 5), 176, 20, 6, 2, 7, 2,
"Declare War");
private static TextButton warSeven = new TextButton(100,
(Main.height / 8f * 6f) + 16 + (20 * 6), 176, 20, 6, 2, 7, 2,
"Declare War");
private static TextButton warEight = new TextButton(100,
(Main.height / 8f * 6f) + 16 + (20 * 7), 176, 20, 6, 2, 7, 2,
"Declare War");
private static ArrayList<Button> pane1Buttons = new ArrayList<Button>();
private static int warOff = 0;
private static int warPos;
private static int warState = 2;
private static String warName = "";
private static int gold;
private static int land;
private static int wheat;
// Logging Pane //
private static Button logUp = new Button(40, 575, 48, 0, 2, 1, 2);
private static Button logDown = new Button(40, 645, 48, 2, 2, 3, 2);
private static ArrayList<Button> pane2Buttons = new ArrayList<Button>();
private static int logOff = 0;
private static int logPos;
// Graphs //
private static Graph popGraph = new Graph(75, 710, "Population",
new Treble<>(0f, 153f / 255f, 204f / 255f));
private static Graph globalWheatGraph = new Graph(75 + (150 * 1) + 75, 710,
"World Wheat", new Treble<>(208f / 255f, 194f / 255f, 109f / 255f));
private static Graph moneyGraph = new Graph(75 + (150 * 2) + (75 * 2), 710,
"Treasury", new Treble<>(100f / 255f, 191f / 255f, 115f / 255f));
private static Graph scoreGraph = new Graph(75 + (150 * 3) + (75 * 3), 710,
"Score", new Treble<>(167 / 255f, 76 / 255f, 76 / 255f));
private static Graph scoreGraphOther = new Graph(75 + (150 * 3) + (75 * 3),
710, "Score (Other)",
new Treble<>(129 / 255f, 87 / 255f, 87 / 255f));
private static ArrayList<Graph> graphs = new ArrayList<Graph>();
// Economy Pane //
private static ToggleButton toggleFeedDisplaced = new ToggleButton(900,
657, 25, 4, 2, 5, 2, true);
private static ToggleButton toggleFavorWarrior = new ToggleButton(900, 627,
25, 4, 2, 5, 2, false);
private static Button increaseWarriorRatio = new Button(525, 642, 20, 0, 2,
1, 2);
private static Button decreaseWarriorRatio = new Button(525, 672, 20, 2, 2,
3, 2);
private static ToggleButton toggleCutTrees = new ToggleButton(900, 597, 25,
4, 2, 5, 2, true);
private static ToggleButton toggleForceConscription = new ToggleButton(900,
567, 25, 4, 2, 5, 2, true);
private static ToggleButton toggleVeryFast = new ToggleButton(35, 595, 25, 8, 5, 9, 5,
false);
private static ToggleButton toggleFast = new ToggleButton(70, 595, 25, 8, 5, 9, 5,
false);
private static ToggleButton toggleNormal = new ToggleButton(105, 595, 25, 8, 6, 9, 6,
true);
private static ToggleButton toggleSlow = new ToggleButton(140, 595, 25, 8, 6, 9, 6,
false);
private static ToggleButton togglePaused = new ToggleButton(175, 595, 25, 8, 4, 9, 4,
false);
private static ArrayList<Button> pane4Buttons = new ArrayList<Button>();
static {
buttons.add(statsPane);
buttons.add(warPane);
buttons.add(graphsPane);
buttons.add(logPane);
buttons.add(econPane);
pane4Buttons.add(toggleFeedDisplaced);
pane4Buttons.add(toggleFavorWarrior);
pane4Buttons.add(increaseWarriorRatio);
pane4Buttons.add(decreaseWarriorRatio);
pane4Buttons.add(toggleFast);
pane4Buttons.add(toggleSlow);
pane4Buttons.add(toggleNormal);
pane4Buttons.add(toggleVeryFast);
pane4Buttons.add(togglePaused);
pane4Buttons.add(toggleCutTrees);
pane4Buttons.add(toggleForceConscription);
pane1Buttons.add(warUp);
pane1Buttons.add(warDown);
pane1Buttons.add(warOne);
pane1Buttons.add(warTwo);
pane1Buttons.add(warThree);
pane1Buttons.add(warFour);
pane1Buttons.add(warFive);
pane1Buttons.add(warSix);
pane1Buttons.add(warSeven);
pane1Buttons.add(warEight);
pane2Buttons.add(logUp);
pane2Buttons.add(logDown);
graphs.add(popGraph);
graphs.add(globalWheatGraph);
graphs.add(moneyGraph);
graphs.add(scoreGraph);
graphs.add(scoreGraphOther);
scoreGraphOther.hideStats();
statsPane.addOverlay(0, 1, 24);
warPane.addOverlay(1, 1, 24);
logPane.addOverlay(1, 5, 24);
graphsPane.addOverlay(0, 5, 24);
econPane.addOverlay(8, 0, 24);
}
public static void update() {
if (statsPane.checkForClick()) {
warPane.setToggle(false);
graphsPane.setToggle(false);
logPane.setToggle(false);
statsPane.setToggle(true);
econPane.setToggle(false);
pane = 0;
}
if (warPane.checkForClick()) {
statsPane.setToggle(false);
graphsPane.setToggle(false);
logPane.setToggle(false);
warPane.setToggle(true);
econPane.setToggle(false);
pane = 1;
}
if (logPane.checkForClick()) {
statsPane.setToggle(false);
graphsPane.setToggle(false);
warPane.setToggle(false);
logPane.setToggle(true);
econPane.setToggle(false);
pane = 2;
}
if (graphsPane.checkForClick()) {
statsPane.setToggle(false);
logPane.setToggle(false);
warPane.setToggle(false);
graphsPane.setToggle(true);
econPane.setToggle(false);
pane = 3;
}
if (econPane.checkForClick()) {
statsPane.setToggle(false);
logPane.setToggle(false);
warPane.setToggle(false);
graphsPane.setToggle(false);
econPane.setToggle(true);
pane = 4;
}
if (pane == 4) {
if (toggleFeedDisplaced.checkForClick()) {
PlayerCountry.displacedEat ^= true;
}
if (toggleFavorWarrior.checkForClick()) {
PlayerCountry.favorFarmers ^= true;
}
if (toggleCutTrees.checkForClick()) {
World.cutForests ^= true;
}
if (toggleForceConscription.checkForClick()) {
PlayerCountry.forceConscription ^= true;
}
if (increaseWarriorRatio.checkForClick()) {
if (PlayerCountry.desiredWarriorRatio < 1.0f) {
PlayerCountry.desiredWarriorRatio += 0.01f;
}
}
if (decreaseWarriorRatio.checkForClick()) {
if (PlayerCountry.desiredWarriorRatio > 0.0f) {
PlayerCountry.desiredWarriorRatio -= 0.01f;
} else {
PlayerCountry.desiredWarriorRatio = 0.0f;
}
}
if (toggleFast.checkForClick()) {
Main.framesPerTick = 9;
toggleFast.setToggle(true);
toggleSlow.setToggle(false);
toggleNormal.setToggle(false);
togglePaused.setToggle(false);
toggleVeryFast.setToggle(false);
}
if (toggleSlow.checkForClick()) {
Main.framesPerTick = 36;
toggleFast.setToggle(false);
toggleSlow.setToggle(true);
toggleNormal.setToggle(false);
togglePaused.setToggle(false);
toggleVeryFast.setToggle(false);
}
if (toggleNormal.checkForClick()) {
Main.framesPerTick = 18;
toggleFast.setToggle(false);
toggleSlow.setToggle(false);
toggleNormal.setToggle(true);
togglePaused.setToggle(false);
toggleVeryFast.setToggle(false);
}
if (toggleVeryFast.checkForClick()) {
Main.framesPerTick = 3;
toggleFast.setToggle(false);
toggleSlow.setToggle(false);
toggleNormal.setToggle(false);
togglePaused.setToggle(false);
toggleVeryFast.setToggle(true);
}
if (togglePaused.checkForClick()) {
Main.framesPerTick = 0x2000000;
toggleFast.setToggle(false);
toggleSlow.setToggle(false);
toggleNormal.setToggle(false);
togglePaused.setToggle(true);
toggleVeryFast.setToggle(false);
}
}
if (pane == 1) {
if (warDown.checkForClick()) {
warOff++;
warOff = Math.min(warOff, PlayerCountry.countries.size());
}
if (warUp.checkForClick()) {
warOff
if (warOff < 0) {
warOff = 0;
}
}
if (warOff != 0 && warPos == 0) {
warPos = PlayerCountry.countries.size();
} else if (warOff == 0) {
warPos = 0;
}
try {
if (warOne.checkForClick()) {
Country c = PlayerCountry.countries
.get(PlayerCountry.countries.size() - warOff - 1);
if (c != null && !c.dead) {
War.warWith(c);
warName = "The " + PlayerCountry.name + "-" + c.name
+ " war";
updateWar(warName);
}
}
if (warTwo.checkForClick()) {
Country c = PlayerCountry.countries
.get(PlayerCountry.countries.size() - warOff - 2);
if (c != null && !c.dead) {
War.warWith(c);
warName = "The " + PlayerCountry.name + "-" + c.name
+ " war";
updateWar(warName);
}
}
if (warThree.checkForClick()) {
Country c = PlayerCountry.countries
.get(PlayerCountry.countries.size() - warOff - 3);
if (c != null && !c.dead) {
War.warWith(c);
warName = "The " + PlayerCountry.name + "-" + c.name
+ " war";
updateWar(warName);
}
}
if (warFour.checkForClick()) {
Country c = PlayerCountry.countries
.get(PlayerCountry.countries.size() - warOff - 4);
if (c != null && !c.dead) {
War.warWith(c);
warName = "The " + PlayerCountry.name + "-" + c.name
+ " war";
updateWar(warName);
}
}
if (warFive.checkForClick()) {
Country c = PlayerCountry.countries
.get(PlayerCountry.countries.size() - warOff - 5);
if (c != null && !c.dead) {
War.warWith(c);
warName = "The " + PlayerCountry.name + "-" + c.name
+ " war";
updateWar(warName);
}
}
if (warSix.checkForClick()) {
Country c = PlayerCountry.countries
.get(PlayerCountry.countries.size() - warOff - 6);
if (c != null && !c.dead) {
War.warWith(c);
warName = "The " + PlayerCountry.name + "-" + c.name
+ " war";
updateWar(warName);
}
}
if (warSeven.checkForClick()) {
Country c = PlayerCountry.countries
.get(PlayerCountry.countries.size() - warOff - 7);
if (c != null && !c.dead) {
War.warWith(c);
warName = "The " + PlayerCountry.name + "-" + c.name
+ " war";
updateWar(warName);
}
}
if (warEight.checkForClick()) {
Country c = PlayerCountry.countries
.get(PlayerCountry.countries.size() - warOff - 8);
if (c != null && !c.dead) {
War.warWith(c);
warName = "The " + PlayerCountry.name + "-" + c.name
+ " war";
updateWar(warName);
}
}
} catch (Exception e) {
}
}
if (pane == 2) {
if (logDown.checkForClick()) {
logOff++;
logOff = Math.min(logOff, Log.getAll().size());
}
if (logUp.checkForClick()) {
logOff
if (logOff < 0) {
logOff = 0;
}
}
if (logOff != 0 && logPos == 0) {
logPos = Log.getAll().size();
} else if (logOff == 0) {
logPos = 0;
}
}
popGraph.tick(PlayerCountry.farmer.getfPop()
+ PlayerCountry.warrior.getwPop());
globalWheatGraph.tick(PlayerCountry.wheat.gettWheat());
moneyGraph.tick(PlayerCountry.economy.getTreasury());
scoreGraph.tick(PlayerCountry.score.scoreAt(Math.max(0,
PlayerCountry.year - 1)));
scoreGraphOther.tick(Util.calcAverageCountryScore());
}
public static void click(float x, float y) {
for (Button b : buttons) {
b.click(x, y);
}
if (pane == 0) {
for (Button b : pane0Buttons) {
b.click(x, y);
}
}
if (pane == 1) {
for (Button b : pane1Buttons) {
b.click(x, y);
}
}
if (pane == 2) {
for (Button b : pane2Buttons) {
b.click(x, y);
}
}
if (pane == 4) {
for (Button b : pane4Buttons) {
b.click(x, y);
}
}
}
public static void render(float x, float y) {
atlas.getTexture().bind();
for (Button b : buttons) {
b.render(x, y);
}
if (pane == 0) {
renderStats();
} else if (pane == 1) {
renderWar();
} else if (pane == 2) {
renderLog();
} else if (pane == 3) {
renderGraphs();
} else if (pane == 4){
renderEcon();
}
}
public static void render2(float x, float y) {
Render.initOrtho();
for (Button b : buttons) {
b.render2();
}
if (pane == 3) {
renderGraphs2();
}
}
public static void renderEcon(){
for (Button b : pane4Buttons){
b.render(Mouse.getX(), Main.height - Mouse.getY());
}
renderEcon2();
}
public static void renderEcon2(){
for (Button b : pane4Buttons){
b.render2();
}
Render.drawString("Conscription Rate: "
+ ((int) (100 * PlayerCountry.desiredWarriorRatio)) + "%", 285,
657);
if(toggleFast.getToggle() == true) {
Render.drawString("Game Speed: Fast", 35, 567);
} else if(toggleSlow.getToggle() == true) {
Render.drawString("Game Speed: Slow", 35, 567);
} else if(toggleNormal.getToggle() == true) {
Render.drawString("Game Speed: Normal", 35, 567);
} else if(toggleVeryFast.getToggle() == true) {
Render.drawString("Game Speed: Very Fast", 35, 567);
} else if(togglePaused.getToggle() == true) {
Render.drawString("Game Speed: Paused", 35, 567);
}
Render.drawString(
"Feed Displaced: " + String.valueOf(PlayerCountry.displacedEat),
585, 657);
Render.drawString(
"Favor Warrior Rations: "
+ String.valueOf(!PlayerCountry.favorFarmers), 585, 627);
Render.drawString("Cut Forests: " + String.valueOf(World.cutForests),
585, 597);
Render.drawString(
"Force Conscription: "
+ String.valueOf(PlayerCountry.forceConscription), 585,
567);
}
public static void renderWar() {
for (int i = 0; i < pane1Buttons.size(); i++) {
if (i < 2) {
pane1Buttons.get(i).render(Mouse.getX(),
Main.height - Mouse.getY());
continue;
}
try {
Country c = PlayerCountry.countries.get(PlayerCountry.countries
.size() - warOff - (i - 2) - 1);
if (c == null) {
continue;
}
} catch (Exception e) {
continue;
}
pane1Buttons.get(i)
.render(Mouse.getX(), Main.height - Mouse.getY());
}
if (warState != 0 && warState != 2) {
/* Draw wheat icon */
glBegin(GL_QUADS);
glTexCoord2f(atlas.getCoord(0, false), atlas.getCoord(3, false));
glVertex2f(750, 575);
glTexCoord2f(atlas.getCoord(0, true), atlas.getCoord(3, false));
glVertex2f(775, 575);
glTexCoord2f(atlas.getCoord(0, true), atlas.getCoord(3, true));
glVertex2f(775, 600);
glTexCoord2f(atlas.getCoord(0, false), atlas.getCoord(3, true));
glVertex2f(750, 600);
glEnd();
glColor3f(1.0f, 1.0f, 1.0f);
/* Draw wheat icon */
glBegin(GL_QUADS);
glTexCoord2f(atlas.getCoord(0, false), atlas.getCoord(3, false));
glVertex2f(750, 610);
glTexCoord2f(atlas.getCoord(0, true), atlas.getCoord(3, false));
glVertex2f(775, 610);
glTexCoord2f(atlas.getCoord(0, true), atlas.getCoord(3, true));
glVertex2f(775, 635);
glTexCoord2f(atlas.getCoord(0, false), atlas.getCoord(3, true));
glVertex2f(750, 635);
glEnd();
glColor3f(1.0f, 1.0f, 1.0f);
/* Draw wheat icon */
glBegin(GL_QUADS);
glTexCoord2f(atlas.getCoord(0, false), atlas.getCoord(3, false));
glVertex2f(750, 645);
glTexCoord2f(atlas.getCoord(0, true), atlas.getCoord(3, false));
glVertex2f(775, 645);
glTexCoord2f(atlas.getCoord(0, true), atlas.getCoord(3, true));
glVertex2f(775, 670);
glTexCoord2f(atlas.getCoord(0, false), atlas.getCoord(3, true));
glVertex2f(750, 670);
glEnd();
glColor3f(1.0f, 1.0f, 1.0f);
}
renderWar2();
}
public static void renderGraphs() {
for (Graph g : graphs) {
g.render();
}
}
public static void renderGraphs2() {
for (Graph g : graphs) {
g.render2();
}
}
public static void renderLog() {
for (Button b : pane2Buttons) {
b.render(Mouse.getX(), Main.height - Mouse.getY());
}
ArrayList<String> log = Log.getAll();
String str;
int offx = 100;
int offy = Main.height / 8 * 6;
offy += 20;
int logstart = logOff;
for (int i = logstart; i < 8 + logstart; i++) {
try {
if (logOff == 0) {
str = log.get(log.size() - 1 - i);
} else {
str = log.get(logPos - 1 - i);
}
Render.font.drawString(offx, offy, str);
offy += 20;
} catch (Exception e) {
break;
}
}
}
public static void renderWar2() {
for (int i = 0; i < pane1Buttons.size(); i++) {
if (i < 2) {
pane1Buttons.get(i).render2();
continue;
}
try {
Country c = PlayerCountry.countries.get(PlayerCountry.countries
.size() - warOff - (i - 2) - 1);
if (c == null) {
continue;
}
} catch (Exception e) {
continue;
}
pane1Buttons.get(i).render2();
}
int offx = 300;
int offy = Main.height / 8 * 6;
offy += 20;
int logstart = warOff;
for (int i = logstart; i < 8 + logstart; i++) {
try {
String name = "";
Country country = null;
if (warOff == 0) {
name = PlayerCountry.countries.get(PlayerCountry.countries
.size() - 1 - i).name;
country = PlayerCountry.countries
.get(PlayerCountry.countries.size() - 1 - i);
} else {
name = PlayerCountry.countries.get(warPos - 1 - i).name;
country = PlayerCountry.countries.get(warPos - 1 - i);
}
if (!country.dead) {
Render.font.drawString(offx, offy, name);
Render.font.drawString(offx + Render.font.getWidth(name)
+ 10, offy,
"[" + Integer.toString(country.aggression.aggressionScore)
+ "]", new Color(
(country.aggression.aggressionScore * 2) / 255f,
1 - (country.aggression.aggressionScore * 2 / 255f),
20 / 255f));
int tempoff = offx
+ Render.font.getWidth(name)
+ 20
+ Render.font.getWidth("["
+ Integer
.toString(country.aggression.aggressionScore)
+ "]");
Render.font.drawString(tempoff, offy,
"[" + Integer.toString(country.getScore()) + "]",
new Color(102, 186, 233));
offy += 20;
} else {
Render.font.drawString(offx, offy, name);
Render.font.drawString(offx + Render.font.getWidth(name)
+ 10, offy,
"[" + Integer.toString(country.aggression.aggressionScore)
+ "]", new Color(
(country.aggression.aggressionScore * 2) / 255f,
1 - (country.aggression.aggressionScore * 2 / 255f),
20 / 255f));
int tempoff = offx
+ Render.font.getWidth(name)
+ 20
+ Render.font.getWidth("["
+ Integer
.toString(country.aggression.aggressionScore)
+ "]");
Render.font.drawString(tempoff, offy, "[In Exile]",
new Color(195, 65, 65));
offy += 20;
}
} catch (Exception e) {
break;
}
}
if (warState == 0) {
Render.font.drawString(800, (Main.height / 8 * 6) + 12, warName);
int off = Render.font.getWidth(warName) + 10;
Render.font.drawString(800 + off, (Main.height / 8 * 6) + 12,
"- Stalemate!", new Color(0.75f, 0.75f, 0.25f));
} else if (warState == 1) {
Render.font.drawString(800, (Main.height / 8 * 6) + 12, warName);
int off = Render.font.getWidth(warName) + 10;
Render.font.drawString(800 + off, (Main.height / 8 * 6) + 12,
"- Victory!", new Color(0.25f, 0.75f, 0.25f));
Render.font.drawString(800, (Main.height / 8 * 6) + 37, "Wheat: "
+ wheat, new Color(0.25f, 0.75f, 0.25f));
Render.font.drawString(800, (Main.height / 8 * 6) + 77, "Money: "
+ gold, new Color(0.25f, 0.75f, 0.25f));
Render.font.drawString(800, (Main.height / 8 * 6) + 117, "Land: "
+ land, new Color(0.25f, 0.75f, 0.25f));
} else if (warState == -1) {
Render.font.drawString(800, (Main.height / 8 * 6) + 12, warName);
int off = Render.font.getWidth(warName) + 10;
Render.font.drawString(800 + off, (Main.height / 8 * 6) + 12,
"- Defeat!", new Color(0.75f, 0.25f, 0.25f));
Render.font.drawString(800, (Main.height / 8 * 6) + 37, "Wheat: "
+ wheat, new Color(0.75f, 0.25f, 0.25f));
Render.font.drawString(800, (Main.height / 8 * 6) + 77, "Money: "
+ gold, new Color(0.75f, 0.25f, 0.25f));
Render.font.drawString(800, (Main.height / 8 * 6) + 117, "Land: "
+ land, new Color(0.75f, 0.25f, 0.25f));
} else if (warState == 2) {
Render.font.drawString(800, (Main.height / 8 * 6) + 12,
"No Recent Wars");
}
}
public static void renderStats() {
for (Button b : pane0Buttons) {
b.render(Mouse.getX(), Main.height - Mouse.getY());
}
/* Draw wheat icon */
glBegin(GL_QUADS);
glTexCoord2f(atlas.getCoord(0, false), atlas.getCoord(3, false));
glVertex2f(50, 575);
glTexCoord2f(atlas.getCoord(0, true), atlas.getCoord(3, false));
glVertex2f(75, 575);
glTexCoord2f(atlas.getCoord(0, true), atlas.getCoord(3, true));
glVertex2f(75, 600);
glTexCoord2f(atlas.getCoord(0, false), atlas.getCoord(3, true));
glVertex2f(50, 600);
glEnd();
glColor3f(1.0f, 1.0f, 1.0f);
/* Draw house icon */
glBegin(GL_QUADS);
glTexCoord2f(atlas.getCoord(0, false), atlas.getCoord(1, false));
glVertex2f(50, 610);
glTexCoord2f(atlas.getCoord(0, true), atlas.getCoord(1, false));
glVertex2f(75, 610);
glTexCoord2f(atlas.getCoord(0, true), atlas.getCoord(1, true));
glVertex2f(75, 635);
glTexCoord2f(atlas.getCoord(0, false), atlas.getCoord(1, true));
glVertex2f(50, 635);
glEnd();
glColor3f(1.0f, 1.0f, 1.0f);
/* Draw castle icon */
glBegin(GL_QUADS);
glTexCoord2f(atlas.getCoord(1, false), atlas.getCoord(1, false));
glVertex2f(50, 645);
glTexCoord2f(atlas.getCoord(1, true), atlas.getCoord(1, false));
glVertex2f(75, 645);
glTexCoord2f(atlas.getCoord(1, true), atlas.getCoord(1, true));
glVertex2f(75, 670);
glTexCoord2f(atlas.getCoord(1, false), atlas.getCoord(1, true));
glVertex2f(50, 670);
glEnd();
glColor3f(1.0f, 1.0f, 1.0f);
/* Draw log icon */
glBegin(GL_QUADS);
glTexCoord2f(atlas.getCoord(7, false), atlas.getCoord(4, false));
glVertex2f(950, 593);
glTexCoord2f(atlas.getCoord(7, true), atlas.getCoord(4, false));
glVertex2f(975, 593);
glTexCoord2f(atlas.getCoord(7, true), atlas.getCoord(4, true));
glVertex2f(975, 617);
glTexCoord2f(atlas.getCoord(7, false), atlas.getCoord(4, true));
glVertex2f(950, 617);
glEnd();
glColor3f(1.0f, 1.0f, 1.0f);
/* Draw sword icon */
glBegin(GL_QUADS);
glTexCoord2f(atlas.getCoord(8, false), atlas.getCoord(3, false));
glVertex2f(950, 563);
glTexCoord2f(atlas.getCoord(8, true), atlas.getCoord(3, false));
glVertex2f(975, 563);
glTexCoord2f(atlas.getCoord(8, true), atlas.getCoord(3, true));
glVertex2f(975, 587);
glTexCoord2f(atlas.getCoord(8, false), atlas.getCoord(3, true));
glVertex2f(950, 587);
glEnd();
glColor3f(1.0f, 1.0f, 1.0f);
/* Draw coin icon */
glBegin(GL_QUADS);
glTexCoord2f(atlas.getCoord(8, false), atlas.getCoord(0, false));
glVertex2f(950, 653);
glTexCoord2f(atlas.getCoord(8, true), atlas.getCoord(0, false));
glVertex2f(975, 653);
glTexCoord2f(atlas.getCoord(8, true), atlas.getCoord(0, true));
glVertex2f(975, 677);
glTexCoord2f(atlas.getCoord(8, false), atlas.getCoord(0, true));
glVertex2f(950, 677);
glEnd();
glColor3f(1.0f, 1.0f, 1.0f);
/* Draw land icon */
glBegin(GL_QUADS);
glTexCoord2f(atlas.getCoord(8, false), atlas.getCoord(1, false));
glVertex2f(950, 623);
glTexCoord2f(atlas.getCoord(8, true), atlas.getCoord(1, false));
glVertex2f(975, 623);
glTexCoord2f(atlas.getCoord(8, true), atlas.getCoord(1, true));
glVertex2f(975, 647);
glTexCoord2f(atlas.getCoord(8, false), atlas.getCoord(1, true));
glVertex2f(950, 647);
glEnd();
glColor3f(1.0f, 1.0f, 1.0f);
/* Draw stone icon */
glBegin(GL_QUADS);
glTexCoord2f(atlas.getCoord(8, false), atlas.getCoord(2, false));
glVertex2f(950, 683);
glTexCoord2f(atlas.getCoord(8, true), atlas.getCoord(2, false));
glVertex2f(975, 683);
glTexCoord2f(atlas.getCoord(8, true), atlas.getCoord(2, true));
glVertex2f(975, 707);
glTexCoord2f(atlas.getCoord(8, false), atlas.getCoord(2, true));
glVertex2f(950, 707);
glEnd();
glColor3f(1.0f, 1.0f, 1.0f);
renderStats2();
}
public static void renderStats2() {
Render.drawString(String.valueOf(PlayerCountry.warrior.getwPop())
+ " Warriors", 85, 657);
Render.drawString(String.valueOf(PlayerCountry.farmer.getfPop())
+ " Farmers", 85, 627);
Render.drawString(String.valueOf(PlayerCountry.wheat.gettWheat()), 85,
587);
if (Util.getWheatRate() > 0) {
Render.font.drawString(85 + Render.font.getWidth(String
.valueOf(PlayerCountry.wheat.gettWheat() + " ")), 587, " ("
+ Util.getWheatRateForDisplay() + ")", Color.green);
} else {
Render.font.drawString(85 + Render.font.getWidth(String
.valueOf(PlayerCountry.wheat.gettWheat() + " ")), 587, " ("
+ Util.getWheatRateForDisplay() + ")", Color.red);
}
Render.drawString(
"Occupied Territories: "
+ String.valueOf(PlayerCountry.land.getLand()), 985,
627);
Render.drawString(
"Money: " + String.valueOf(PlayerCountry.economy.getTreasury()),
985, 657);
Render.drawString(
"Wood: " + String.valueOf(PlayerCountry.wood.getWood()), 985,
597);
Render.drawString("Aggression: ", 985, 567);
int value = PlayerCountry.aggression.aggressionScore;
Render.font.drawString(985 + 15 + Render.font.getWidth("Aggression"),
567, String.valueOf(PlayerCountry.aggression.aggressionScore), new Color(
(value * 2) / 255f, 1 - (value * 2 / 255f), 20 / 255f));
Render.drawString(
"Stone: " + String.valueOf(PlayerCountry.stone.getStone()),
985, 687);
}
public static boolean shouldRenderGraphs() {
return pane == 3;
}
public static void reset() {
warState = 2;
wheat = 0;
gold = 0;
land = 0;
for (Graph g : graphs) {
g.reset();
}
}
public static void setPane(int newPane){
pane = newPane;
}
public static void updateWar(String name){
warState = War.winLose;
warName = name;
wheat = War.wheatLoss;
gold = War.moneyLoss;
land = War.landLoss;
}
}
|
package FrontEnd;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame marco = new JFrame("SuperSoft v0.0 proto");
marco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
marco.setBounds(10, 100, 400, 300);
marco.setVisible(true);
marco.setContentPane(new PantallaBienvenida(marco));
marco.validate();
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
marco.setContentPane(new Inicio(marco));
marco.validate();
}
}
|
package org.postgresql.jdbc1;
// IMPORTANT NOTE: This file implements the JDBC 1 version of the driver.
// If you make any modifications to this file, you must make sure that the
// changes are also made (if relevent) to the related JDBC 2 class in the
// org.postgresql.jdbc2 package.
import java.sql.*;
import java.util.*;
import org.postgresql.Field;
/**
* This class provides information about the database as a whole.
*
* <p>Many of the methods here return lists of information in ResultSets. You
* can use the normal ResultSet methods such as getString and getInt to
* retrieve the data from these ResultSets. If a given form of metadata is
* not available, these methods should throw a SQLException.
*
* <p>Some of these methods take arguments that are String patterns. These
* arguments all have names such as fooPattern. Within a pattern String,
* "%" means match any substring of 0 or more characters, and "_" means
* match any one character. Only metadata entries matching the search
* pattern are returned. if a search pattern argument is set to a null
* ref, it means that argument's criteria should be dropped from the
* search.
*
* <p>A SQLException will be throws if a driver does not support a meta
* data method. In the case of methods that return a ResultSet, either
* a ResultSet (which may be empty) is returned or a SQLException is
* thrown.
*
* @see java.sql.DatabaseMetaData
*/
public class DatabaseMetaData implements java.sql.DatabaseMetaData
{
Connection connection; // The connection association
// These define various OID's. Hopefully they will stay constant.
static final int iVarcharOid = 1043; // OID for varchar
static final int iBoolOid = 16; // OID for bool
static final int iInt2Oid = 21; // OID for int2
static final int iInt4Oid = 23; // OID for int4
static final int VARHDRSZ = 4; // length for int4
// This is a default value for remarks
private static final byte defaultRemarks[]="no remarks".getBytes();
public DatabaseMetaData(Connection conn)
{
this.connection = conn;
}
/**
* Can all the procedures returned by getProcedures be called
* by the current user?
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean allProceduresAreCallable() throws SQLException
{
return true; // For now...
}
/**
* Can all the tables returned by getTable be SELECTed by
* the current user?
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean allTablesAreSelectable() throws SQLException
{
return true; // For now...
}
/**
* What is the URL for this database?
*
* @return the url or null if it cannott be generated
* @exception SQLException if a database access error occurs
*/
public String getURL() throws SQLException
{
return connection.getURL();
}
/**
* What is our user name as known to the database?
*
* @return our database user name
* @exception SQLException if a database access error occurs
*/
public String getUserName() throws SQLException
{
return connection.getUserName();
}
/**
* Is the database in read-only mode?
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean isReadOnly() throws SQLException
{
return connection.isReadOnly();
}
/**
* Are NULL values sorted high?
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean nullsAreSortedHigh() throws SQLException
{
return false;
}
/**
* Are NULL values sorted low?
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean nullsAreSortedLow() throws SQLException
{
return false;
}
/**
* Are NULL values sorted at the start regardless of sort order?
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean nullsAreSortedAtStart() throws SQLException
{
return false;
}
/**
* Are NULL values sorted at the end regardless of sort order?
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean nullsAreSortedAtEnd() throws SQLException
{
return true;
}
/**
* What is the name of this database product - we hope that it is
* PostgreSQL, so we return that explicitly.
*
* @return the database product name
* @exception SQLException if a database access error occurs
*/
public String getDatabaseProductName() throws SQLException
{
return "PostgreSQL";
}
/**
* What is the version of this database product.
*
* @return the database version
* @exception SQLException if a database access error occurs
*/
public String getDatabaseProductVersion() throws SQLException
{
java.sql.ResultSet resultSet = connection.ExecSQL("select version()");
resultSet.next();
StringTokenizer versionParts = new StringTokenizer(resultSet.getString(1));
versionParts.nextToken(); /* "PostgreSQL" */
String versionNumber = versionParts.nextToken(); /* "X.Y.Z" */
return versionNumber;
}
/**
* What is the name of this JDBC driver? If we don't know this
* we are doing something wrong!
*
* @return the JDBC driver name
* @exception SQLException why?
*/
public String getDriverName() throws SQLException
{
return "PostgreSQL Native Driver";
}
/**
* What is the version string of this JDBC driver? Again, this is
* static.
*
* @return the JDBC driver name.
* @exception SQLException why?
*/
public String getDriverVersion() throws SQLException
{
return connection.this_driver.getVersion();
}
/**
* What is this JDBC driver's major version number?
*
* @return the JDBC driver major version
*/
public int getDriverMajorVersion()
{
return connection.this_driver.getMajorVersion();
}
/**
* What is this JDBC driver's minor version number?
*
* @return the JDBC driver minor version
*/
public int getDriverMinorVersion()
{
return connection.this_driver.getMinorVersion();
}
/**
* Does the database store tables in a local file? No - it
* stores them in a file on the server.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean usesLocalFiles() throws SQLException
{
return false;
}
/**
* Does the database use a file for each table? Well, not really,
* since it doesnt use local files.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean usesLocalFilePerTable() throws SQLException
{
return false;
}
/**
* Does the database treat mixed case unquoted SQL identifiers
* as case sensitive and as a result store them in mixed case?
* A JDBC-Compliant driver will always return false.
*
* <p>Predicament - what do they mean by "SQL identifiers" - if it
* means the names of the tables and columns, then the answers
* given below are correct - otherwise I don't know.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsMixedCaseIdentifiers() throws SQLException
{
return false;
}
/**
* Does the database treat mixed case unquoted SQL identifiers as
* case insensitive and store them in upper case?
*
* @return true if so
*/
public boolean storesUpperCaseIdentifiers() throws SQLException
{
return false;
}
/**
* Does the database treat mixed case unquoted SQL identifiers as
* case insensitive and store them in lower case?
*
* @return true if so
*/
public boolean storesLowerCaseIdentifiers() throws SQLException
{
return true;
}
/**
* Does the database treat mixed case unquoted SQL identifiers as
* case insensitive and store them in mixed case?
*
* @return true if so
*/
public boolean storesMixedCaseIdentifiers() throws SQLException
{
return false;
}
/**
* Does the database treat mixed case quoted SQL identifiers as
* case sensitive and as a result store them in mixed case? A
* JDBC compliant driver will always return true.
*
* <p>Predicament - what do they mean by "SQL identifiers" - if it
* means the names of the tables and columns, then the answers
* given below are correct - otherwise I don't know.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException
{
return true;
}
/**
* Does the database treat mixed case quoted SQL identifiers as
* case insensitive and store them in upper case?
*
* @return true if so
*/
public boolean storesUpperCaseQuotedIdentifiers() throws SQLException
{
return false;
}
/**
* Does the database treat mixed case quoted SQL identifiers as case
* insensitive and store them in lower case?
*
* @return true if so
*/
public boolean storesLowerCaseQuotedIdentifiers() throws SQLException
{
return false;
}
/**
* Does the database treat mixed case quoted SQL identifiers as case
* insensitive and store them in mixed case?
*
* @return true if so
*/
public boolean storesMixedCaseQuotedIdentifiers() throws SQLException
{
return false;
}
/**
* What is the string used to quote SQL identifiers? This returns
* a space if identifier quoting isn't supported. A JDBC Compliant
* driver will always use a double quote character.
*
* <p>If an SQL identifier is a table name, column name, etc. then
* we do not support it.
*
* @return the quoting string
* @exception SQLException if a database access error occurs
*/
public String getIdentifierQuoteString() throws SQLException
{
return "\"";
}
public String getSQLKeywords() throws SQLException
{
return "abort,acl,add,aggregate,append,archive,arch_store,backward,binary,change,cluster,copy,database,delimiters,do,extend,explain,forward,heavy,index,inherits,isnull,light,listen,load,merge,nothing,notify,notnull,oids,purge,rename,replace,retrieve,returns,rule,recipe,setof,stdin,stdout,store,vacuum,verbose,version";
}
public String getNumericFunctions() throws SQLException
{
// XXX-Not Implemented
return "";
}
public String getStringFunctions() throws SQLException
{
// XXX-Not Implemented
return "";
}
public String getSystemFunctions() throws SQLException
{
// XXX-Not Implemented
return "";
}
public String getTimeDateFunctions() throws SQLException
{
// XXX-Not Implemented
return "";
}
/**
* This is the string that can be used to escape '_' and '%' in
* a search string pattern style catalog search parameters
*
* @return the string used to escape wildcard characters
* @exception SQLException if a database access error occurs
*/
public String getSearchStringEscape() throws SQLException
{
return "\\";
}
/**
* Get all the "extra" characters that can bew used in unquoted
* identifier names (those beyond a-zA-Z0-9 and _)
*
* <p>From the file src/backend/parser/scan.l, an identifier is
* {letter}{letter_or_digit} which makes it just those listed
* above.
*
* @return a string containing the extra characters
* @exception SQLException if a database access error occurs
*/
public String getExtraNameCharacters() throws SQLException
{
return "";
}
/**
* Is "ALTER TABLE" with an add column supported?
* Yes for PostgreSQL 6.1
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsAlterTableWithAddColumn() throws SQLException
{
return true;
}
/**
* Is "ALTER TABLE" with a drop column supported?
* Peter 10/10/2000 This was set to true, but 7.1devel doesn't support it!
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsAlterTableWithDropColumn() throws SQLException
{
return false;
}
public boolean supportsColumnAliasing() throws SQLException
{
return true;
}
/**
* Are concatenations between NULL and non-NULL values NULL? A
* JDBC Compliant driver always returns true
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean nullPlusNonNullIsNull() throws SQLException
{
return true;
}
public boolean supportsConvert() throws SQLException
{
// XXX-Not Implemented
return false;
}
public boolean supportsConvert(int fromType, int toType) throws SQLException
{
// XXX-Not Implemented
return false;
}
public boolean supportsTableCorrelationNames() throws SQLException
{
// XXX-Not Implemented
return false;
}
public boolean supportsDifferentTableCorrelationNames() throws SQLException
{
// XXX-Not Implemented
return false;
}
/**
* Are expressions in "ORCER BY" lists supported?
*
* <br>e.g. select * from t order by a + b;
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsExpressionsInOrderBy() throws SQLException
{
return true;
}
/**
* Can an "ORDER BY" clause use columns not in the SELECT?
* I checked it, and you can't.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsOrderByUnrelated() throws SQLException
{
return false;
}
/**
* Is some form of "GROUP BY" clause supported?
* I checked it, and yes it is.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsGroupBy() throws SQLException
{
return true;
}
/**
* Can a "GROUP BY" clause use columns not in the SELECT?
* I checked it - it seems to allow it
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsGroupByUnrelated() throws SQLException
{
return true;
}
/**
* Can a "GROUP BY" clause add columns not in the SELECT provided
* it specifies all the columns in the SELECT? Does anyone actually
* understand what they mean here?
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsGroupByBeyondSelect() throws SQLException
{
return true; // For now...
}
/**
* Is the escape character in "LIKE" clauses supported? A
* JDBC compliant driver always returns true.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsLikeEscapeClause() throws SQLException
{
return true;
}
/**
* Are multiple ResultSets from a single execute supported?
* Well, I implemented it, but I dont think this is possible from
* the back ends point of view.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsMultipleResultSets() throws SQLException
{
return false;
}
/**
* Can we have multiple transactions open at once (on different
* connections?)
* I guess we can have, since Im relying on it.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsMultipleTransactions() throws SQLException
{
return true;
}
/**
* Can columns be defined as non-nullable. A JDBC Compliant driver
* always returns true.
*
* <p>This changed from false to true in v6.2 of the driver, as this
* support was added to the backend.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsNonNullableColumns() throws SQLException
{
return true;
}
public boolean supportsMinimumSQLGrammar() throws SQLException
{
return true;
}
/**
* Does this driver support the Core ODBC SQL grammar. We need
* SQL-92 conformance for this.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsCoreSQLGrammar() throws SQLException
{
return false;
}
/**
* Does this driver support the Extended (Level 2) ODBC SQL
* grammar. We don't conform to the Core (Level 1), so we can't
* conform to the Extended SQL Grammar.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsExtendedSQLGrammar() throws SQLException
{
return false;
}
/**
* Does this driver support the ANSI-92 entry level SQL grammar?
* All JDBC Compliant drivers must return true. I think we have
* to support outer joins for this to be true.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsANSI92EntryLevelSQL() throws SQLException
{
return false;
}
/**
* Does this driver support the ANSI-92 intermediate level SQL
* grammar? Anyone who does not support Entry level cannot support
* Intermediate level.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsANSI92IntermediateSQL() throws SQLException
{
return false;
}
/**
* Does this driver support the ANSI-92 full SQL grammar?
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsANSI92FullSQL() throws SQLException
{
return false;
}
/**
* Is the SQL Integrity Enhancement Facility supported?
* I haven't seen this mentioned anywhere, so I guess not
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsIntegrityEnhancementFacility() throws SQLException
{
return false;
}
/**
* Is some form of outer join supported? From my knowledge, nope.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsOuterJoins() throws SQLException
{
return false;
}
/**
* Are full nexted outer joins supported? Well, we dont support any
* form of outer join, so this is no as well
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsFullOuterJoins() throws SQLException
{
return false;
}
/**
* Is there limited support for outer joins? (This will be true if
* supportFullOuterJoins is true)
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsLimitedOuterJoins() throws SQLException
{
return false;
}
/**
* What is the database vendor's preferred term for "schema" - well,
* we do not provide support for schemas, so lets just use that
* term.
*
* @return the vendor term
* @exception SQLException if a database access error occurs
*/
public String getSchemaTerm() throws SQLException
{
return "Schema";
}
/**
* What is the database vendor's preferred term for "procedure" -
* I kind of like "Procedure" myself.
*
* @return the vendor term
* @exception SQLException if a database access error occurs
*/
public String getProcedureTerm() throws SQLException
{
return "Procedure";
}
/**
* What is the database vendor's preferred term for "catalog"? -
* we dont have a preferred term, so just use Catalog
*
* @return the vendor term
* @exception SQLException if a database access error occurs
*/
public String getCatalogTerm() throws SQLException
{
return "Catalog";
}
/**
* Does a catalog appear at the start of a qualified table name?
* (Otherwise it appears at the end).
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean isCatalogAtStart() throws SQLException
{
return false;
}
/**
* What is the Catalog separator. Hmmm....well, I kind of like
* a period (so we get catalog.table definitions). - I don't think
* PostgreSQL supports catalogs anyhow, so it makes no difference.
*
* @return the catalog separator string
* @exception SQLException if a database access error occurs
*/
public String getCatalogSeparator() throws SQLException
{
// PM Sep 29 97 - changed from "." as we don't support catalogs.
return "";
}
/**
* Can a schema name be used in a data manipulation statement? Nope.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsSchemasInDataManipulation() throws SQLException
{
return false;
}
/**
* Can a schema name be used in a procedure call statement? Nope.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsSchemasInProcedureCalls() throws SQLException
{
return false;
}
/**
* Can a schema be used in a table definition statement? Nope.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsSchemasInTableDefinitions() throws SQLException
{
return false;
}
/**
* Can a schema name be used in an index definition statement?
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsSchemasInIndexDefinitions() throws SQLException
{
return false;
}
/**
* Can a schema name be used in a privilege definition statement?
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsSchemasInPrivilegeDefinitions() throws SQLException
{
return false;
}
/**
* Can a catalog name be used in a data manipulation statement?
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsCatalogsInDataManipulation() throws SQLException
{
return false;
}
/**
* Can a catalog name be used in a procedure call statement?
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsCatalogsInProcedureCalls() throws SQLException
{
return false;
}
/**
* Can a catalog name be used in a table definition statement?
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsCatalogsInTableDefinitions() throws SQLException
{
return false;
}
/**
* Can a catalog name be used in an index definition?
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsCatalogsInIndexDefinitions() throws SQLException
{
return false;
}
/**
* Can a catalog name be used in a privilege definition statement?
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException
{
return false;
}
/**
* We support cursors for gets only it seems. I dont see a method
* to get a positioned delete.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsPositionedDelete() throws SQLException
{
return false; // For now...
}
/**
* Is positioned UPDATE supported?
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsPositionedUpdate() throws SQLException
{
return false; // For now...
}
public boolean supportsSelectForUpdate() throws SQLException
{
// XXX-Not Implemented
return false;
}
public boolean supportsStoredProcedures() throws SQLException
{
// XXX-Not Implemented
return false;
}
public boolean supportsSubqueriesInComparisons() throws SQLException
{
// XXX-Not Implemented
return false;
}
public boolean supportsSubqueriesInExists() throws SQLException
{
// XXX-Not Implemented
return false;
}
public boolean supportsSubqueriesInIns() throws SQLException
{
// XXX-Not Implemented
return false;
}
public boolean supportsSubqueriesInQuantifieds() throws SQLException
{
// XXX-Not Implemented
return false;
}
public boolean supportsCorrelatedSubqueries() throws SQLException
{
// XXX-Not Implemented
return false;
}
/**
* Is SQL UNION supported? Nope.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsUnion() throws SQLException
{
return false;
}
/**
* Is SQL UNION ALL supported? Nope.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsUnionAll() throws SQLException
{
return false;
}
/**
* In PostgreSQL, Cursors are only open within transactions.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsOpenCursorsAcrossCommit() throws SQLException
{
return false;
}
/**
* Do we support open cursors across multiple transactions?
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsOpenCursorsAcrossRollback() throws SQLException
{
return false;
}
/**
* Can statements remain open across commits? They may, but
* this driver cannot guarentee that. In further reflection.
* we are talking a Statement object jere, so the answer is
* yes, since the Statement is only a vehicle to ExecSQL()
*
* @return true if they always remain open; false otherwise
* @exception SQLException if a database access error occurs
*/
public boolean supportsOpenStatementsAcrossCommit() throws SQLException
{
return true;
}
/**
* Can statements remain open across rollbacks? They may, but
* this driver cannot guarentee that. In further contemplation,
* we are talking a Statement object here, so the answer is yes,
* since the Statement is only a vehicle to ExecSQL() in Connection
*
* @return true if they always remain open; false otherwise
* @exception SQLException if a database access error occurs
*/
public boolean supportsOpenStatementsAcrossRollback() throws SQLException
{
return true;
}
/**
* How many hex characters can you have in an inline binary literal
*
* @return the max literal length
* @exception SQLException if a database access error occurs
*/
public int getMaxBinaryLiteralLength() throws SQLException
{
return 0; // For now...
}
/**
* What is the maximum length for a character literal
* I suppose it is 8190 (8192 - 2 for the quotes)
*
* @return the max literal length
* @exception SQLException if a database access error occurs
*/
public int getMaxCharLiteralLength() throws SQLException
{
return 65535;
}
/**
* Whats the limit on column name length. The description of
* pg_class would say '32' (length of pg_class.relname) - we
* should probably do a query for this....but....
*
* @return the maximum column name length
* @exception SQLException if a database access error occurs
*/
public int getMaxColumnNameLength() throws SQLException
{
return 32;
}
/**
* What is the maximum number of columns in a "GROUP BY" clause?
*
* @return the max number of columns
* @exception SQLException if a database access error occurs
*/
public int getMaxColumnsInGroupBy() throws SQLException
{
return getMaxColumnsInTable();
}
/**
* What's the maximum number of columns allowed in an index?
* 6.0 only allowed one column, but 6.1 introduced multi-column
* indices, so, theoretically, its all of them.
*
* @return max number of columns
* @exception SQLException if a database access error occurs
*/
public int getMaxColumnsInIndex() throws SQLException
{
return getMaxColumnsInTable();
}
/**
* What's the maximum number of columns in an "ORDER BY clause?
* Theoretically, all of them!
*
* @return the max columns
* @exception SQLException if a database access error occurs
*/
public int getMaxColumnsInOrderBy() throws SQLException
{
return getMaxColumnsInTable();
}
/**
* What is the maximum number of columns in a "SELECT" list?
* Theoretically, all of them!
*
* @return the max columns
* @exception SQLException if a database access error occurs
*/
public int getMaxColumnsInSelect() throws SQLException
{
return getMaxColumnsInTable();
}
/**
* What is the maximum number of columns in a table? From the
* create_table(l) manual page...
*
* <p>"The new class is created as a heap with no initial data. A
* class can have no more than 1600 attributes (realistically,
* this is limited by the fact that tuple sizes must be less than
* 8192 bytes)..."
*
* @return the max columns
* @exception SQLException if a database access error occurs
*/
public int getMaxColumnsInTable() throws SQLException
{
return 1600;
}
/**
* How many active connection can we have at a time to this
* database? Well, since it depends on postmaster, which just
* does a listen() followed by an accept() and fork(), its
* basically very high. Unless the system runs out of processes,
* it can be 65535 (the number of aux. ports on a TCP/IP system).
* I will return 8192 since that is what even the largest system
* can realistically handle,
*
* @return the maximum number of connections
* @exception SQLException if a database access error occurs
*/
public int getMaxConnections() throws SQLException
{
return 8192;
}
public int getMaxCursorNameLength() throws SQLException
{
return 32;
}
/**
* What is the maximum length of an index (in bytes)? Now, does
* the spec. mean name of an index (in which case its 32, the
* same as a table) or does it mean length of an index element
* (in which case its 8192, the size of a row) or does it mean
* the number of rows it can access (in which case it 2^32 -
* a 4 byte OID number)? I think its the length of an index
* element, personally, so Im setting it to 65535.
*
* @return max index length in bytes
* @exception SQLException if a database access error occurs
*/
public int getMaxIndexLength() throws SQLException
{
return 65535;
}
public int getMaxSchemaNameLength() throws SQLException
{
// XXX-Not Implemented
return 0;
}
/**
* What is the maximum length of a procedure name?
* (length of pg_proc.proname used) - again, I really
* should do a query here to get it.
*
* @return the max name length in bytes
* @exception SQLException if a database access error occurs
*/
public int getMaxProcedureNameLength() throws SQLException
{
return 32;
}
public int getMaxCatalogNameLength() throws SQLException
{
// XXX-Not Implemented
return 0;
}
/**
* What is the maximum length of a single row? (not including
* blobs). 65535 is defined in PostgreSQL.
*
* @return max row size in bytes
* @exception SQLException if a database access error occurs
*/
public int getMaxRowSize() throws SQLException
{
return 65535;
}
/**
* Did getMaxRowSize() include LONGVARCHAR and LONGVARBINARY
* blobs? We don't handle blobs yet
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean doesMaxRowSizeIncludeBlobs() throws SQLException
{
return false;
}
/**
* What is the maximum length of a SQL statement?
*
* @return max length in bytes
* @exception SQLException if a database access error occurs
*/
public int getMaxStatementLength() throws SQLException
{
return 65535;
}
/**
* How many active statements can we have open at one time to
* this database? Basically, since each Statement downloads
* the results as the query is executed, we can have many. However,
* we can only really have one statement per connection going
* at once (since they are executed serially) - so we return
* one.
*
* @return the maximum
* @exception SQLException if a database access error occurs
*/
public int getMaxStatements() throws SQLException
{
return 1;
}
/**
* What is the maximum length of a table name? This was found
* from pg_class.relname length
*
* @return max name length in bytes
* @exception SQLException if a database access error occurs
*/
public int getMaxTableNameLength() throws SQLException
{
return 32;
}
/**
* What is the maximum number of tables that can be specified
* in a SELECT? Theoretically, this is the same number as the
* number of tables allowable. In practice tho, it is much smaller
* since the number of tables is limited by the statement, we
* return 1024 here - this is just a number I came up with (being
* the number of tables roughly of three characters each that you
* can fit inside a 65535 character buffer with comma separators).
*
* @return the maximum
* @exception SQLException if a database access error occurs
*/
public int getMaxTablesInSelect() throws SQLException
{
return 1024;
}
/**
* What is the maximum length of a user name? Well, we generally
* use UNIX like user names in PostgreSQL, so I think this would
* be 8. However, showing the schema for pg_user shows a length
* for username of 32.
*
* @return the max name length in bytes
* @exception SQLException if a database access error occurs
*/
public int getMaxUserNameLength() throws SQLException
{
return 32;
}
/**
* What is the database's default transaction isolation level? We
* do not support this, so all transactions are SERIALIZABLE.
*
* @return the default isolation level
* @exception SQLException if a database access error occurs
* @see Connection
*/
public int getDefaultTransactionIsolation() throws SQLException
{
return Connection.TRANSACTION_READ_COMMITTED;
}
/**
* Are transactions supported? If not, commit and rollback are noops
* and the isolation level is TRANSACTION_NONE. We do support
* transactions.
*
* @return true if transactions are supported
* @exception SQLException if a database access error occurs
*/
public boolean supportsTransactions() throws SQLException
{
return true;
}
/**
* Does the database support the given transaction isolation level?
* We only support TRANSACTION_SERIALIZABLE and TRANSACTION_READ_COMMITTED
*
* @param level the values are defined in java.sql.Connection
* @return true if so
* @exception SQLException if a database access error occurs
* @see Connection
*/
public boolean supportsTransactionIsolationLevel(int level) throws SQLException
{
if (level == Connection.TRANSACTION_SERIALIZABLE ||
level == Connection.TRANSACTION_READ_COMMITTED)
return true;
else
return false;
}
/**
* Are both data definition and data manipulation transactions
* supported? I checked it, and could not do a CREATE TABLE
* within a transaction, so I am assuming that we don't
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException
{
return false;
}
/**
* Are only data manipulation statements withing a transaction
* supported?
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsDataManipulationTransactionsOnly() throws SQLException
{
return true;
}
/**
* Does a data definition statement within a transaction force
* the transaction to commit? I think this means something like:
*
* <p><pre>
* CREATE TABLE T (A INT);
* INSERT INTO T (A) VALUES (2);
* BEGIN;
* UPDATE T SET A = A + 1;
* CREATE TABLE X (A INT);
* SELECT A FROM T INTO X;
* COMMIT;
* </pre><p>
*
* does the CREATE TABLE call cause a commit? The answer is no.
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean dataDefinitionCausesTransactionCommit() throws SQLException
{
return false;
}
/**
* Is a data definition statement within a transaction ignored?
* It seems to be (from experiment in previous method)
*
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean dataDefinitionIgnoredInTransactions() throws SQLException
{
return true;
}
/**
* Get a description of stored procedures available in a catalog
*
* <p>Only procedure descriptions matching the schema and procedure
* name criteria are returned. They are ordered by PROCEDURE_SCHEM
* and PROCEDURE_NAME
*
* <p>Each procedure description has the following columns:
* <ol>
* <li><b>PROCEDURE_CAT</b> String => procedure catalog (may be null)
* <li><b>PROCEDURE_SCHEM</b> String => procedure schema (may be null)
* <li><b>PROCEDURE_NAME</b> String => procedure name
* <li><b>Field 4</b> reserved (make it null)
* <li><b>Field 5</b> reserved (make it null)
* <li><b>Field 6</b> reserved (make it null)
* <li><b>REMARKS</b> String => explanatory comment on the procedure
* <li><b>PROCEDURE_TYPE</b> short => kind of procedure
* <ul>
* <li> procedureResultUnknown - May return a result
* <li> procedureNoResult - Does not return a result
* <li> procedureReturnsResult - Returns a result
* </ul>
* </ol>
*
* @param catalog - a catalog name; "" retrieves those without a
* catalog; null means drop catalog name from criteria
* @param schemaParrern - a schema name pattern; "" retrieves those
* without a schema - we ignore this parameter
* @param procedureNamePattern - a procedure name pattern
* @return ResultSet - each row is a procedure description
* @exception SQLException if a database access error occurs
*/
public java.sql.ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern) throws SQLException
{
// the field descriptors for the new ResultSet
Field f[] = new Field[8];
java.sql.ResultSet r; // ResultSet for the SQL query that we need to do
Vector v = new Vector(); // The new ResultSet tuple stuff
byte remarks[] = defaultRemarks;
f[0] = new Field(connection, "PROCEDURE_CAT", iVarcharOid, 32);
f[1] = new Field(connection, "PROCEDURE_SCHEM", iVarcharOid, 32);
f[2] = new Field(connection, "PROCEDURE_NAME", iVarcharOid, 32);
f[3] = f[4] = f[5] = null; // reserved, must be null for now
f[6] = new Field(connection, "REMARKS", iVarcharOid, 8192);
f[7] = new Field(connection, "PROCEDURE_TYPE", iInt2Oid, 2);
// If the pattern is null, then set it to the default
if(procedureNamePattern==null)
procedureNamePattern="%";
r = connection.ExecSQL("select proname, proretset from pg_proc where proname like '"+procedureNamePattern.toLowerCase()+"' order by proname");
while (r.next())
{
byte[][] tuple = new byte[8][0];
tuple[0] = null; // Catalog name
tuple[1] = null; // Schema name
tuple[2] = r.getBytes(1); // Procedure name
tuple[3] = tuple[4] = tuple[5] = null; // Reserved
tuple[6] = remarks; // Remarks
if (r.getBoolean(2))
tuple[7] = Integer.toString(java.sql.DatabaseMetaData.procedureReturnsResult).getBytes();
else
tuple[7] = Integer.toString(java.sql.DatabaseMetaData.procedureNoResult).getBytes();
v.addElement(tuple);
}
return new ResultSet(connection, f, v, "OK", 1);
}
/**
* Get a description of a catalog's stored procedure parameters
* and result columns.
*
* <p>Only descriptions matching the schema, procedure and parameter
* name criteria are returned. They are ordered by PROCEDURE_SCHEM
* and PROCEDURE_NAME. Within this, the return value, if any, is
* first. Next are the parameter descriptions in call order. The
* column descriptions follow in column number order.
*
* <p>Each row in the ResultSet is a parameter description or column
* description with the following fields:
* <ol>
* <li><b>PROCEDURE_CAT</b> String => procedure catalog (may be null)
* <li><b>PROCEDURE_SCHE</b>M String => procedure schema (may be null)
* <li><b>PROCEDURE_NAME</b> String => procedure name
* <li><b>COLUMN_NAME</b> String => column/parameter name
* <li><b>COLUMN_TYPE</b> Short => kind of column/parameter:
* <ul><li>procedureColumnUnknown - nobody knows
* <li>procedureColumnIn - IN parameter
* <li>procedureColumnInOut - INOUT parameter
* <li>procedureColumnOut - OUT parameter
* <li>procedureColumnReturn - procedure return value
* <li>procedureColumnResult - result column in ResultSet
* </ul>
* <li><b>DATA_TYPE</b> short => SQL type from java.sql.Types
* <li><b>TYPE_NAME</b> String => SQL type name
* <li><b>PRECISION</b> int => precision
* <li><b>LENGTH</b> int => length in bytes of data
* <li><b>SCALE</b> short => scale
* <li><b>RADIX</b> short => radix
* <li><b>NULLABLE</b> short => can it contain NULL?
* <ul><li>procedureNoNulls - does not allow NULL values
* <li>procedureNullable - allows NULL values
* <li>procedureNullableUnknown - nullability unknown
* <li><b>REMARKS</b> String => comment describing parameter/column
* </ol>
* @param catalog This is ignored in org.postgresql, advise this is set to null
* @param schemaPattern This is ignored in org.postgresql, advise this is set to null
* @param procedureNamePattern a procedure name pattern
* @param columnNamePattern a column name pattern
* @return each row is a stored procedure parameter or column description
* @exception SQLException if a database-access error occurs
* @see #getSearchStringEscape
*/
// Implementation note: This is required for Borland's JBuilder to work
public java.sql.ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException
{
if(procedureNamePattern==null)
procedureNamePattern="%";
if(columnNamePattern==null)
columnNamePattern="%";
// for now, this returns an empty result set.
Field f[] = new Field[13];
ResultSet r; // ResultSet for the SQL query that we need to do
Vector v = new Vector(); // The new ResultSet tuple stuff
f[0] = new Field(connection, "PROCEDURE_CAT", iVarcharOid, 32);
f[1] = new Field(connection, "PROCEDURE_SCHEM", iVarcharOid, 32);
f[2] = new Field(connection, "PROCEDURE_NAME", iVarcharOid, 32);
f[3] = new Field(connection, "COLUMN_NAME", iVarcharOid, 32);
f[4] = new Field(connection, "COLUMN_TYPE", iInt2Oid, 2);
f[5] = new Field(connection, "DATA_TYPE", iInt2Oid, 2);
f[6] = new Field(connection, "TYPE_NAME", iVarcharOid, 32);
f[7] = new Field(connection, "PRECISION", iInt4Oid, 4);
f[8] = new Field(connection, "LENGTH", iInt4Oid, 4);
f[9] = new Field(connection, "SCALE", iInt2Oid, 2);
f[10] = new Field(connection, "RADIX", iInt2Oid, 2);
f[11] = new Field(connection, "NULLABLE", iInt2Oid, 2);
f[12] = new Field(connection, "REMARKS", iVarcharOid, 32);
// add query loop here
return new ResultSet(connection, f, v, "OK", 1);
}
/**
* Get a description of tables available in a catalog.
*
* <p>Only table descriptions matching the catalog, schema, table
* name and type criteria are returned. They are ordered by
* TABLE_TYPE, TABLE_SCHEM and TABLE_NAME.
*
* <p>Each table description has the following columns:
*
* <ol>
* <li><b>TABLE_CAT</b> String => table catalog (may be null)
* <li><b>TABLE_SCHEM</b> String => table schema (may be null)
* <li><b>TABLE_NAME</b> String => table name
* <li><b>TABLE_TYPE</b> String => table type. Typical types are "TABLE",
* "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL
* TEMPORARY", "ALIAS", "SYNONYM".
* <li><b>REMARKS</b> String => explanatory comment on the table
* </ol>
*
* <p>The valid values for the types parameter are:
* "TABLE", "INDEX", "SEQUENCE", "SYSTEM TABLE" and "SYSTEM INDEX"
*
* @param catalog a catalog name; For org.postgresql, this is ignored, and
* should be set to null
* @param schemaPattern a schema name pattern; For org.postgresql, this is ignored, and
* should be set to null
* @param tableNamePattern a table name pattern. For all tables this should be "%"
* @param types a list of table types to include; null returns
* all types
* @return each row is a table description
* @exception SQLException if a database-access error occurs.
*/
public java.sql.ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String types[]) throws SQLException
{
// Handle default value for types
if(types==null)
types = defaultTableTypes;
if(tableNamePattern==null)
tableNamePattern="%";
// the field descriptors for the new ResultSet
Field f[] = new Field[5];
java.sql.ResultSet r; // ResultSet for the SQL query that we need to do
Vector v = new Vector(); // The new ResultSet tuple stuff
f[0] = new Field(connection, "TABLE_CAT", iVarcharOid, 32);
f[1] = new Field(connection, "TABLE_SCHEM", iVarcharOid, 32);
f[2] = new Field(connection, "TABLE_NAME", iVarcharOid, 32);
f[3] = new Field(connection, "TABLE_TYPE", iVarcharOid, 32);
f[4] = new Field(connection, "REMARKS", iVarcharOid, 32);
// Now form the query
StringBuffer sql = new StringBuffer("select relname,oid,relkind from pg_class where (");
boolean notFirst=false;
for(int i=0;i<types.length;i++) {
for(int j=0;j<getTableTypes.length;j++)
if(getTableTypes[j][0].equals(types[i])) {
if(notFirst)
sql.append(" or ");
sql.append(getTableTypes[j][1]);
notFirst=true;
}
}
// Added by Stefan Andreasen <stefan@linux.kapow.dk>
// Now take the pattern into account
sql.append(") and relname like '");
sql.append(tableNamePattern.toLowerCase());
sql.append("' order by relkind, relname");
// Now run the query
r = connection.ExecSQL(sql.toString());
byte remarks[];
while (r.next())
{
byte[][] tuple = new byte[5][0];
// Fetch the description for the table (if any)
java.sql.ResultSet dr = connection.ExecSQL("select description from pg_description where objoid="+r.getInt(2));
if(((org.postgresql.ResultSet)dr).getTupleCount()==1) {
dr.next();
remarks = dr.getBytes(1);
} else
remarks = defaultRemarks;
dr.close();
String relKind;
switch (r.getBytes(3)[0]) {
case 'r':
relKind = "TABLE";
break;
case 'i':
relKind = "INDEX";
break;
case 'S':
relKind = "SEQUENCE";
break;
default:
relKind = null;
}
tuple[0] = null; // Catalog name
tuple[1] = null; // Schema name
tuple[2] = r.getBytes(1); // Table name
tuple[3] = relKind.getBytes(); // Table type
tuple[4] = remarks; // Remarks
v.addElement(tuple);
}
r.close();
return new ResultSet(connection, f, v, "OK", 1);
}
// This array contains the valid values for the types argument
// in getTables().
// Each supported type consists of it's name, and the sql where
// clause to retrieve that value.
// IMPORTANT: the query must be enclosed in ( )
private static final String getTableTypes[][] = {
{"TABLE", "(relkind='r' and relhasrules='f' and relname !~ '^pg_')"},
{"VIEW", "(relkind='v' and relname !~ '^pg_')"},
{"INDEX", "(relkind='i' and relname !~ '^pg_')"},
{"SEQUENCE", "(relkind='S' and relname !~ '^pg_')"},
{"SYSTEM TABLE", "(relkind='r' and relname ~ '^pg_')"},
{"SYSTEM INDEX", "(relkind='i' and relname ~ '^pg_')"}
};
// These are the default tables, used when NULL is passed to getTables
// The choice of these provide the same behaviour as psql's \d
private static final String defaultTableTypes[] = {
"TABLE","VIEW","INDEX","SEQUENCE"
};
/**
* Get the schema names available in this database. The results
* are ordered by schema name.
*
* <P>The schema column is:
* <OL>
* <LI><B>TABLE_SCHEM</B> String => schema name
* </OL>
*
* @return ResultSet each row has a single String column that is a
* schema name
*/
public java.sql.ResultSet getSchemas() throws SQLException
{
// We don't use schemas, so we simply return a single schema name "".
Field f[] = new Field[1];
Vector v = new Vector();
byte[][] tuple = new byte[1][0];
f[0] = new Field(connection,"TABLE_SCHEM",iVarcharOid,32);
tuple[0] = "".getBytes();
v.addElement(tuple);
return new ResultSet(connection,f,v,"OK",1);
}
/**
* Get the catalog names available in this database. The results
* are ordered by catalog name.
*
* <P>The catalog column is:
* <OL>
* <LI><B>TABLE_CAT</B> String => catalog name
* </OL>
*
* @return ResultSet each row has a single String column that is a
* catalog name
*/
public java.sql.ResultSet getCatalogs() throws SQLException
{
// We don't use catalogs, so we simply return a single catalog name "".
Field f[] = new Field[1];
Vector v = new Vector();
byte[][] tuple = new byte[1][0];
f[0] = new Field(connection,"TABLE_CAT",iVarcharOid,32);
tuple[0] = "".getBytes();
v.addElement(tuple);
return new ResultSet(connection,f,v,"OK",1);
}
/**
* Get the table types available in this database. The results
* are ordered by table type.
*
* <P>The table type is:
* <OL>
* <LI><B>TABLE_TYPE</B> String => table type. Typical types are "TABLE",
* "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY",
* "LOCAL TEMPORARY", "ALIAS", "SYNONYM".
* </OL>
*
* @return ResultSet each row has a single String column that is a
* table type
*/
public java.sql.ResultSet getTableTypes() throws SQLException
{
Field f[] = new Field[1];
Vector v = new Vector();
f[0] = new Field(connection,new String("TABLE_TYPE"),iVarcharOid,32);
for(int i=0;i<getTableTypes.length;i++) {
byte[][] tuple = new byte[1][0];
tuple[0] = getTableTypes[i][0].getBytes();
v.addElement(tuple);
}
return new ResultSet(connection,f,v,"OK",1);
}
/**
* Get a description of table columns available in a catalog.
*
* <P>Only column descriptions matching the catalog, schema, table
* and column name criteria are returned. They are ordered by
* TABLE_SCHEM, TABLE_NAME and ORDINAL_POSITION.
*
* <P>Each column description has the following columns:
* <OL>
* <LI><B>TABLE_CAT</B> String => table catalog (may be null)
* <LI><B>TABLE_SCHEM</B> String => table schema (may be null)
* <LI><B>TABLE_NAME</B> String => table name
* <LI><B>COLUMN_NAME</B> String => column name
* <LI><B>DATA_TYPE</B> short => SQL type from java.sql.Types
* <LI><B>TYPE_NAME</B> String => Data source dependent type name
* <LI><B>COLUMN_SIZE</B> int => column size. For char or date
* types this is the maximum number of characters, for numeric or
* decimal types this is precision.
* <LI><B>BUFFER_LENGTH</B> is not used.
* <LI><B>DECIMAL_DIGITS</B> int => the number of fractional digits
* <LI><B>NUM_PREC_RADIX</B> int => Radix (typically either 10 or 2)
* <LI><B>NULLABLE</B> int => is NULL allowed?
* <UL>
* <LI> columnNoNulls - might not allow NULL values
* <LI> columnNullable - definitely allows NULL values
* <LI> columnNullableUnknown - nullability unknown
* </UL>
* <LI><B>REMARKS</B> String => comment describing column (may be null)
* <LI><B>COLUMN_DEF</B> String => default value (may be null)
* <LI><B>SQL_DATA_TYPE</B> int => unused
* <LI><B>SQL_DATETIME_SUB</B> int => unused
* <LI><B>CHAR_OCTET_LENGTH</B> int => for char types the
* maximum number of bytes in the column
* <LI><B>ORDINAL_POSITION</B> int => index of column in table
* (starting at 1)
* <LI><B>IS_NULLABLE</B> String => "NO" means column definitely
* does not allow NULL values; "YES" means the column might
* allow NULL values. An empty string means nobody knows.
* </OL>
*
* @param catalog a catalog name; "" retrieves those without a catalog
* @param schemaPattern a schema name pattern; "" retrieves those
* without a schema
* @param tableNamePattern a table name pattern
* @param columnNamePattern a column name pattern
* @return ResultSet each row is a column description
* @see #getSearchStringEscape
*/
public java.sql.ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException
{
// the field descriptors for the new ResultSet
Field f[] = new Field[18];
java.sql.ResultSet r; // ResultSet for the SQL query that we need to do
Vector v = new Vector(); // The new ResultSet tuple stuff
f[0] = new Field(connection, "TABLE_CAT", iVarcharOid, 32);
f[1] = new Field(connection, "TABLE_SCHEM", iVarcharOid, 32);
f[2] = new Field(connection, "TABLE_NAME", iVarcharOid, 32);
f[3] = new Field(connection, "COLUMN_NAME", iVarcharOid, 32);
f[4] = new Field(connection, "DATA_TYPE", iInt2Oid, 2);
f[5] = new Field(connection, "TYPE_NAME", iVarcharOid, 32);
f[6] = new Field(connection, "COLUMN_SIZE", iInt4Oid, 4);
f[7] = new Field(connection, "BUFFER_LENGTH", iVarcharOid, 32);
f[8] = new Field(connection, "DECIMAL_DIGITS", iInt4Oid, 4);
f[9] = new Field(connection, "NUM_PREC_RADIX", iInt4Oid, 4);
f[10] = new Field(connection, "NULLABLE", iInt4Oid, 4);
f[11] = new Field(connection, "REMARKS", iVarcharOid, 32);
f[12] = new Field(connection, "COLUMN_DEF", iVarcharOid, 32);
f[13] = new Field(connection, "SQL_DATA_TYPE", iInt4Oid, 4);
f[14] = new Field(connection, "SQL_DATETIME_SUB", iInt4Oid, 4);
f[15] = new Field(connection, "CHAR_OCTET_LENGTH", iVarcharOid, 32);
f[16] = new Field(connection, "ORDINAL_POSITION", iInt4Oid,4);
f[17] = new Field(connection, "IS_NULLABLE", iVarcharOid, 32);
// Added by Stefan Andreasen <stefan@linux.kapow.dk>
// If the pattern are null then set them to %
if (tableNamePattern == null) tableNamePattern="%";
if (columnNamePattern == null) columnNamePattern="%";
// Now form the query
r = connection.ExecSQL("select a.oid,c.relname,a.attname,a.atttypid,a.attnum,a.attnotnull,a.attlen,a.atttypmod from pg_class c, pg_attribute a where a.attrelid=c.oid and c.relname like '"+tableNamePattern.toLowerCase()+"' and a.attname like '"+columnNamePattern.toLowerCase()+"' and a.attnum>0 order by c.relname,a.attnum");
byte remarks[];
while(r.next()) {
byte[][] tuple = new byte[18][0];
// Fetch the description for the table (if any)
java.sql.ResultSet dr = connection.ExecSQL("select description from pg_description where objoid="+r.getInt(1));
if(((org.postgresql.ResultSet)dr).getTupleCount()==1) {
dr.next();
tuple[11] = dr.getBytes(1);
} else
tuple[11] = defaultRemarks;
dr.close();
tuple[0] = "".getBytes(); // Catalog name
tuple[1] = "".getBytes(); // Schema name
tuple[2] = r.getBytes(2); // Table name
tuple[3] = r.getBytes(3); // Column name
dr = connection.ExecSQL("select typname from pg_type where oid = "+r.getString(4));
dr.next();
String typname=dr.getString(1);
dr.close();
tuple[4] = Integer.toString(Field.getSQLType(typname)).getBytes(); // Data type
tuple[5] = typname.getBytes(); // Type name
// Column size
// Looking at the psql source,
// I think the length of a varchar as specified when the table was created
// should be extracted from atttypmod which contains this length + sizeof(int32)
if (typname.equals("bpchar") || typname.equals("varchar")) {
int atttypmod = r.getInt(8);
tuple[6] = Integer.toString(atttypmod != -1 ? atttypmod - VARHDRSZ : 0).getBytes();
} else
tuple[6] = r.getBytes(7);
tuple[7] = null; // Buffer length
tuple[8] = "0".getBytes(); // Decimal Digits - how to get this?
tuple[9] = "10".getBytes(); // Num Prec Radix - assume decimal
// tuple[10] is below
// tuple[11] is above
tuple[12] = null; // column default
tuple[13] = null; // sql data type (unused)
tuple[14] = null; // sql datetime sub (unused)
tuple[15] = tuple[6]; // char octet length
tuple[16] = r.getBytes(5); // ordinal position
String nullFlag = r.getString(6);
tuple[10] = Integer.toString(nullFlag.equals("f")?java.sql.DatabaseMetaData.columnNullable:java.sql.DatabaseMetaData.columnNoNulls).getBytes(); // Nullable
tuple[17] = (nullFlag.equals("f")?"YES":"NO").getBytes(); // is nullable
v.addElement(tuple);
}
r.close();
return new ResultSet(connection, f, v, "OK", 1);
}
/**
* Get a description of the access rights for a table's columns.
*
* <P>Only privileges matching the column name criteria are
* returned. They are ordered by COLUMN_NAME and PRIVILEGE.
*
* <P>Each privilige description has the following columns:
* <OL>
* <LI><B>TABLE_CAT</B> String => table catalog (may be null)
* <LI><B>TABLE_SCHEM</B> String => table schema (may be null)
* <LI><B>TABLE_NAME</B> String => table name
* <LI><B>COLUMN_NAME</B> String => column name
* <LI><B>GRANTOR</B> => grantor of access (may be null)
* <LI><B>GRANTEE</B> String => grantee of access
* <LI><B>PRIVILEGE</B> String => name of access (SELECT,
* INSERT, UPDATE, REFRENCES, ...)
* <LI><B>IS_GRANTABLE</B> String => "YES" if grantee is permitted
* to grant to others; "NO" if not; null if unknown
* </OL>
*
* @param catalog a catalog name; "" retrieves those without a catalog
* @param schema a schema name; "" retrieves those without a schema
* @param table a table name
* @param columnNamePattern a column name pattern
* @return ResultSet each row is a column privilege description
* @see #getSearchStringEscape
*/
public java.sql.ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern) throws SQLException
{
Field f[] = new Field[8];
Vector v = new Vector();
if(table==null)
table="%";
if(columnNamePattern==null)
columnNamePattern="%";
else
columnNamePattern=columnNamePattern.toLowerCase();
f[0] = new Field(connection,"TABLE_CAT",iVarcharOid,32);
f[1] = new Field(connection,"TABLE_SCHEM",iVarcharOid,32);
f[2] = new Field(connection,"TABLE_NAME",iVarcharOid,32);
f[3] = new Field(connection,"COLUMN_NAME",iVarcharOid,32);
f[4] = new Field(connection,"GRANTOR",iVarcharOid,32);
f[5] = new Field(connection,"GRANTEE",iVarcharOid,32);
f[6] = new Field(connection,"PRIVILEGE",iVarcharOid,32);
f[7] = new Field(connection,"IS_GRANTABLE",iVarcharOid,32);
// This is taken direct from the psql source
java.sql.ResultSet r = connection.ExecSQL("SELECT relname, relacl FROM pg_class, pg_user WHERE ( relkind = 'r' OR relkind = 'i') and relname !~ '^pg_' and relname !~ '^xin[vx][0-9]+' and usesysid = relowner and relname like '"+table.toLowerCase()+"' ORDER BY relname");
while(r.next()) {
byte[][] tuple = new byte[8][0];
tuple[0] = tuple[1]= "".getBytes();
DriverManager.println("relname=\""+r.getString(1)+"\" relacl=\""+r.getString(2)+"\"");
// For now, don't add to the result as relacl needs to be processed.
//v.addElement(tuple);
}
return new ResultSet(connection,f,v,"OK",1);
}
/**
* Get a description of the access rights for each table available
* in a catalog.
*
* <P>Only privileges matching the schema and table name
* criteria are returned. They are ordered by TABLE_SCHEM,
* TABLE_NAME, and PRIVILEGE.
*
* <P>Each privilige description has the following columns:
* <OL>
* <LI><B>TABLE_CAT</B> String => table catalog (may be null)
* <LI><B>TABLE_SCHEM</B> String => table schema (may be null)
* <LI><B>TABLE_NAME</B> String => table name
* <LI><B>COLUMN_NAME</B> String => column name
* <LI><B>GRANTOR</B> => grantor of access (may be null)
* <LI><B>GRANTEE</B> String => grantee of access
* <LI><B>PRIVILEGE</B> String => name of access (SELECT,
* INSERT, UPDATE, REFRENCES, ...)
* <LI><B>IS_GRANTABLE</B> String => "YES" if grantee is permitted
* to grant to others; "NO" if not; null if unknown
* </OL>
*
* @param catalog a catalog name; "" retrieves those without a catalog
* @param schemaPattern a schema name pattern; "" retrieves those
* without a schema
* @param tableNamePattern a table name pattern
* @return ResultSet each row is a table privilege description
* @see #getSearchStringEscape
*/
public java.sql.ResultSet getTablePrivileges(String catalog, String schemaPattern, String tableNamePattern) throws SQLException
{
// XXX-Not Implemented
return null;
}
/**
* Get a description of a table's optimal set of columns that
* uniquely identifies a row. They are ordered by SCOPE.
*
* <P>Each column description has the following columns:
* <OL>
* <LI><B>SCOPE</B> short => actual scope of result
* <UL>
* <LI> bestRowTemporary - very temporary, while using row
* <LI> bestRowTransaction - valid for remainder of current transaction
* <LI> bestRowSession - valid for remainder of current session
* </UL>
* <LI><B>COLUMN_NAME</B> String => column name
* <LI><B>DATA_TYPE</B> short => SQL data type from java.sql.Types
* <LI><B>TYPE_NAME</B> String => Data source dependent type name
* <LI><B>COLUMN_SIZE</B> int => precision
* <LI><B>BUFFER_LENGTH</B> int => not used
* <LI><B>DECIMAL_DIGITS</B> short => scale
* <LI><B>PSEUDO_COLUMN</B> short => is this a pseudo column
* like an Oracle ROWID
* <UL>
* <LI> bestRowUnknown - may or may not be pseudo column
* <LI> bestRowNotPseudo - is NOT a pseudo column
* <LI> bestRowPseudo - is a pseudo column
* </UL>
* </OL>
*
* @param catalog a catalog name; "" retrieves those without a catalog
* @param schema a schema name; "" retrieves those without a schema
* @param table a table name
* @param scope the scope of interest; use same values as SCOPE
* @param nullable include columns that are nullable?
* @return ResultSet each row is a column description
*/
// Implementation note: This is required for Borland's JBuilder to work
public java.sql.ResultSet getBestRowIdentifier(String catalog, String schema, String table, int scope, boolean nullable) throws SQLException
{
// for now, this returns an empty result set.
Field f[] = new Field[8];
ResultSet r; // ResultSet for the SQL query that we need to do
Vector v = new Vector(); // The new ResultSet tuple stuff
f[0] = new Field(connection, "SCOPE", iInt2Oid, 2);
f[1] = new Field(connection, "COLUMN_NAME", iVarcharOid, 32);
f[2] = new Field(connection, "DATA_TYPE", iInt2Oid, 2);
f[3] = new Field(connection, "TYPE_NAME", iVarcharOid, 32);
f[4] = new Field(connection, "COLUMN_SIZE", iInt4Oid, 4);
f[5] = new Field(connection, "BUFFER_LENGTH", iInt4Oid, 4);
f[6] = new Field(connection, "DECIMAL_DIGITS", iInt2Oid, 2);
f[7] = new Field(connection, "PSEUDO_COLUMN", iInt2Oid, 2);
return new ResultSet(connection, f, v, "OK", 1);
}
/**
* Get a description of a table's columns that are automatically
* updated when any value in a row is updated. They are
* unordered.
*
* <P>Each column description has the following columns:
* <OL>
* <LI><B>SCOPE</B> short => is not used
* <LI><B>COLUMN_NAME</B> String => column name
* <LI><B>DATA_TYPE</B> short => SQL data type from java.sql.Types
* <LI><B>TYPE_NAME</B> String => Data source dependent type name
* <LI><B>COLUMN_SIZE</B> int => precision
* <LI><B>BUFFER_LENGTH</B> int => length of column value in bytes
* <LI><B>DECIMAL_DIGITS</B> short => scale
* <LI><B>PSEUDO_COLUMN</B> short => is this a pseudo column
* like an Oracle ROWID
* <UL>
* <LI> versionColumnUnknown - may or may not be pseudo column
* <LI> versionColumnNotPseudo - is NOT a pseudo column
* <LI> versionColumnPseudo - is a pseudo column
* </UL>
* </OL>
*
* @param catalog a catalog name; "" retrieves those without a catalog
* @param schema a schema name; "" retrieves those without a schema
* @param table a table name
* @return ResultSet each row is a column description
*/
public java.sql.ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException
{
// XXX-Not Implemented
return null;
}
/**
* Get a description of a table's primary key columns. They
* are ordered by COLUMN_NAME.
*
* <P>Each column description has the following columns:
* <OL>
* <LI><B>TABLE_CAT</B> String => table catalog (may be null)
* <LI><B>TABLE_SCHEM</B> String => table schema (may be null)
* <LI><B>TABLE_NAME</B> String => table name
* <LI><B>COLUMN_NAME</B> String => column name
* <LI><B>KEY_SEQ</B> short => sequence number within primary key
* <LI><B>PK_NAME</B> String => primary key name (may be null)
* </OL>
*
* @param catalog a catalog name; "" retrieves those without a catalog
* @param schema a schema name pattern; "" retrieves those
* without a schema
* @param table a table name
* @return ResultSet each row is a primary key column description
*/
public java.sql.ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException
{
return connection.createStatement().executeQuery("SELECT " +
"'' as TABLE_CAT," +
"'' AS TABLE_SCHEM," +
"bc.relname AS TABLE_NAME," +
"a.attname AS COLUMN_NAME," +
"a.attnum as KEY_SEQ,"+
"ic.relname as PK_NAME " +
" FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a" +
" WHERE bc.relkind = 'r' " + // -- not indices
" and upper(bc.relname) = upper('"+table+"')" +
" and i.indrelid = bc.oid" +
" and i.indexrelid = ic.oid" +
" and ic.oid = a.attrelid" +
" and i.indisprimary='t' " +
" ORDER BY table_name, pk_name, key_seq"
);
}
/**
* Get a description of the primary key columns that are
* referenced by a table's foreign key columns (the primary keys
* imported by a table). They are ordered by PKTABLE_CAT,
* PKTABLE_SCHEM, PKTABLE_NAME, and KEY_SEQ.
*
* <P>Each primary key column description has the following columns:
* <OL>
* <LI><B>PKTABLE_CAT</B> String => primary key table catalog
* being imported (may be null)
* <LI><B>PKTABLE_SCHEM</B> String => primary key table schema
* being imported (may be null)
* <LI><B>PKTABLE_NAME</B> String => primary key table name
* being imported
* <LI><B>PKCOLUMN_NAME</B> String => primary key column name
* being imported
* <LI><B>FKTABLE_CAT</B> String => foreign key table catalog (may be null)
* <LI><B>FKTABLE_SCHEM</B> String => foreign key table schema (may be null)
* <LI><B>FKTABLE_NAME</B> String => foreign key table name
* <LI><B>FKCOLUMN_NAME</B> String => foreign key column name
* <LI><B>KEY_SEQ</B> short => sequence number within foreign key
* <LI><B>UPDATE_RULE</B> short => What happens to
* foreign key when primary is updated:
* <UL>
* <LI> importedKeyCascade - change imported key to agree
* with primary key update
* <LI> importedKeyRestrict - do not allow update of primary
* key if it has been imported
* <LI> importedKeySetNull - change imported key to NULL if
* its primary key has been updated
* </UL>
* <LI><B>DELETE_RULE</B> short => What happens to
* the foreign key when primary is deleted.
* <UL>
* <LI> importedKeyCascade - delete rows that import a deleted key
* <LI> importedKeyRestrict - do not allow delete of primary
* key if it has been imported
* <LI> importedKeySetNull - change imported key to NULL if
* its primary key has been deleted
* </UL>
* <LI><B>FK_NAME</B> String => foreign key name (may be null)
* <LI><B>PK_NAME</B> String => primary key name (may be null)
* </OL>
*
* @param catalog a catalog name; "" retrieves those without a catalog
* @param schema a schema name pattern; "" retrieves those
* without a schema
* @param table a table name
* @return ResultSet each row is a primary key column description
* @see #getExportedKeys
*/
public java.sql.ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException
{
// XXX-Not Implemented
return null;
}
/**
* Get a description of a foreign key columns that reference a
* table's primary key columns (the foreign keys exported by a
* table). They are ordered by FKTABLE_CAT, FKTABLE_SCHEM,
* FKTABLE_NAME, and KEY_SEQ.
*
* <P>Each foreign key column description has the following columns:
* <OL>
* <LI><B>PKTABLE_CAT</B> String => primary key table catalog (may be null)
* <LI><B>PKTABLE_SCHEM</B> String => primary key table schema (may be null)
* <LI><B>PKTABLE_NAME</B> String => primary key table name
* <LI><B>PKCOLUMN_NAME</B> String => primary key column name
* <LI><B>FKTABLE_CAT</B> String => foreign key table catalog (may be null)
* being exported (may be null)
* <LI><B>FKTABLE_SCHEM</B> String => foreign key table schema (may be null)
* being exported (may be null)
* <LI><B>FKTABLE_NAME</B> String => foreign key table name
* being exported
* <LI><B>FKCOLUMN_NAME</B> String => foreign key column name
* being exported
* <LI><B>KEY_SEQ</B> short => sequence number within foreign key
* <LI><B>UPDATE_RULE</B> short => What happens to
* foreign key when primary is updated:
* <UL>
* <LI> importedKeyCascade - change imported key to agree
* with primary key update
* <LI> importedKeyRestrict - do not allow update of primary
* key if it has been imported
* <LI> importedKeySetNull - change imported key to NULL if
* its primary key has been updated
* </UL>
* <LI><B>DELETE_RULE</B> short => What happens to
* the foreign key when primary is deleted.
* <UL>
* <LI> importedKeyCascade - delete rows that import a deleted key
* <LI> importedKeyRestrict - do not allow delete of primary
* key if it has been imported
* <LI> importedKeySetNull - change imported key to NULL if
* its primary key has been deleted
* </UL>
* <LI><B>FK_NAME</B> String => foreign key identifier (may be null)
* <LI><B>PK_NAME</B> String => primary key identifier (may be null)
* </OL>
*
* @param catalog a catalog name; "" retrieves those without a catalog
* @param schema a schema name pattern; "" retrieves those
* without a schema
* @param table a table name
* @return ResultSet each row is a foreign key column description
* @see #getImportedKeys
*/
public java.sql.ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException
{
// XXX-Not Implemented
return null;
}
/**
* Get a description of the foreign key columns in the foreign key
* table that reference the primary key columns of the primary key
* table (describe how one table imports another's key.) This
* should normally return a single foreign key/primary key pair
* (most tables only import a foreign key from a table once.) They
* are ordered by FKTABLE_CAT, FKTABLE_SCHEM, FKTABLE_NAME, and
* KEY_SEQ.
*
* <P>Each foreign key column description has the following columns:
* <OL>
* <LI><B>PKTABLE_CAT</B> String => primary key table catalog (may be null)
* <LI><B>PKTABLE_SCHEM</B> String => primary key table schema (may be null)
* <LI><B>PKTABLE_NAME</B> String => primary key table name
* <LI><B>PKCOLUMN_NAME</B> String => primary key column name
* <LI><B>FKTABLE_CAT</B> String => foreign key table catalog (may be null)
* being exported (may be null)
* <LI><B>FKTABLE_SCHEM</B> String => foreign key table schema (may be null)
* being exported (may be null)
* <LI><B>FKTABLE_NAME</B> String => foreign key table name
* being exported
* <LI><B>FKCOLUMN_NAME</B> String => foreign key column name
* being exported
* <LI><B>KEY_SEQ</B> short => sequence number within foreign key
* <LI><B>UPDATE_RULE</B> short => What happens to
* foreign key when primary is updated:
* <UL>
* <LI> importedKeyCascade - change imported key to agree
* with primary key update
* <LI> importedKeyRestrict - do not allow update of primary
* key if it has been imported
* <LI> importedKeySetNull - change imported key to NULL if
* its primary key has been updated
* </UL>
* <LI><B>DELETE_RULE</B> short => What happens to
* the foreign key when primary is deleted.
* <UL>
* <LI> importedKeyCascade - delete rows that import a deleted key
* <LI> importedKeyRestrict - do not allow delete of primary
* key if it has been imported
* <LI> importedKeySetNull - change imported key to NULL if
* its primary key has been deleted
* </UL>
* <LI><B>FK_NAME</B> String => foreign key identifier (may be null)
* <LI><B>PK_NAME</B> String => primary key identifier (may be null)
* </OL>
*
* @param catalog a catalog name; "" retrieves those without a catalog
* @param schema a schema name pattern; "" retrieves those
* without a schema
* @param table a table name
* @return ResultSet each row is a foreign key column description
* @see #getImportedKeys
*/
public java.sql.ResultSet getCrossReference(String primaryCatalog, String primarySchema, String primaryTable, String foreignCatalog, String foreignSchema, String foreignTable) throws SQLException
{
// XXX-Not Implemented
return null;
}
/**
* Get a description of all the standard SQL types supported by
* this database. They are ordered by DATA_TYPE and then by how
* closely the data type maps to the corresponding JDBC SQL type.
*
* <P>Each type description has the following columns:
* <OL>
* <LI><B>TYPE_NAME</B> String => Type name
* <LI><B>DATA_TYPE</B> short => SQL data type from java.sql.Types
* <LI><B>PRECISION</B> int => maximum precision
* <LI><B>LITERAL_PREFIX</B> String => prefix used to quote a literal
* (may be null)
* <LI><B>LITERAL_SUFFIX</B> String => suffix used to quote a literal
(may be null)
* <LI><B>CREATE_PARAMS</B> String => parameters used in creating
* the type (may be null)
* <LI><B>NULLABLE</B> short => can you use NULL for this type?
* <UL>
* <LI> typeNoNulls - does not allow NULL values
* <LI> typeNullable - allows NULL values
* <LI> typeNullableUnknown - nullability unknown
* </UL>
* <LI><B>CASE_SENSITIVE</B> boolean=> is it case sensitive?
* <LI><B>SEARCHABLE</B> short => can you use "WHERE" based on this type:
* <UL>
* <LI> typePredNone - No support
* <LI> typePredChar - Only supported with WHERE .. LIKE
* <LI> typePredBasic - Supported except for WHERE .. LIKE
* <LI> typeSearchable - Supported for all WHERE ..
* </UL>
* <LI><B>UNSIGNED_ATTRIBUTE</B> boolean => is it unsigned?
* <LI><B>FIXED_PREC_SCALE</B> boolean => can it be a money value?
* <LI><B>AUTO_INCREMENT</B> boolean => can it be used for an
* auto-increment value?
* <LI><B>LOCAL_TYPE_NAME</B> String => localized version of type name
* (may be null)
* <LI><B>MINIMUM_SCALE</B> short => minimum scale supported
* <LI><B>MAXIMUM_SCALE</B> short => maximum scale supported
* <LI><B>SQL_DATA_TYPE</B> int => unused
* <LI><B>SQL_DATETIME_SUB</B> int => unused
* <LI><B>NUM_PREC_RADIX</B> int => usually 2 or 10
* </OL>
*
* @return ResultSet each row is a SQL type description
*/
public java.sql.ResultSet getTypeInfo() throws SQLException
{
java.sql.ResultSet rs = connection.ExecSQL("select typname from pg_type");
if(rs!=null) {
Field f[] = new Field[18];
ResultSet r; // ResultSet for the SQL query that we need to do
Vector v = new Vector(); // The new ResultSet tuple stuff
f[0] = new Field(connection, "TYPE_NAME", iVarcharOid, 32);
f[1] = new Field(connection, "DATA_TYPE", iInt2Oid, 2);
f[2] = new Field(connection, "PRECISION", iInt4Oid, 4);
f[3] = new Field(connection, "LITERAL_PREFIX", iVarcharOid, 32);
f[4] = new Field(connection, "LITERAL_SUFFIX", iVarcharOid, 32);
f[5] = new Field(connection, "CREATE_PARAMS", iVarcharOid, 32);
f[6] = new Field(connection, "NULLABLE", iInt2Oid, 2);
f[7] = new Field(connection, "CASE_SENSITIVE", iBoolOid, 1);
f[8] = new Field(connection, "SEARCHABLE", iInt2Oid, 2);
f[9] = new Field(connection, "UNSIGNED_ATTRIBUTE", iBoolOid, 1);
f[10] = new Field(connection, "FIXED_PREC_SCALE", iBoolOid, 1);
f[11] = new Field(connection, "AUTO_INCREMENT", iBoolOid, 1);
f[12] = new Field(connection, "LOCAL_TYPE_NAME", iVarcharOid, 32);
f[13] = new Field(connection, "MINIMUM_SCALE", iInt2Oid, 2);
f[14] = new Field(connection, "MAXIMUM_SCALE", iInt2Oid, 2);
f[15] = new Field(connection, "SQL_DATA_TYPE", iInt4Oid, 4);
f[16] = new Field(connection, "SQL_DATETIME_SUB", iInt4Oid, 4);
f[17] = new Field(connection, "NUM_PREC_RADIX", iInt4Oid, 4);
// cache some results, this will keep memory useage down, and speed
// things up a little.
byte b9[] = "9".getBytes();
byte b10[] = "10".getBytes();
byte bf[] = "f".getBytes();
byte bnn[] = Integer.toString(typeNoNulls).getBytes();
byte bts[] = Integer.toString(typeSearchable).getBytes();
while(rs.next()) {
byte[][] tuple = new byte[18][];
String typname=rs.getString(1);
tuple[0] = typname.getBytes();
tuple[1] = Integer.toString(Field.getSQLType(typname)).getBytes();
tuple[2] = b9; // for now
tuple[6] = bnn; // for now
tuple[7] = bf; // false for now - not case sensitive
tuple[8] = bts;
tuple[9] = bf; // false for now - it's signed
tuple[10] = bf; // false for now - must handle money
tuple[11] = bf; // false for now - handle autoincrement
// 12 - LOCAL_TYPE_NAME is null
// 13 & 14 ?
// 15 & 16 are unused so we return null
tuple[17] = b10; // everything is base 10
v.addElement(tuple);
}
rs.close();
return new ResultSet(connection, f, v, "OK", 1);
}
return null;
}
/**
* Get a description of a table's indices and statistics. They are
* ordered by NON_UNIQUE, TYPE, INDEX_NAME, and ORDINAL_POSITION.
*
* <P>Each index column description has the following columns:
* <OL>
* <LI><B>TABLE_CAT</B> String => table catalog (may be null)
* <LI><B>TABLE_SCHEM</B> String => table schema (may be null)
* <LI><B>TABLE_NAME</B> String => table name
* <LI><B>NON_UNIQUE</B> boolean => Can index values be non-unique?
* false when TYPE is tableIndexStatistic
* <LI><B>INDEX_QUALIFIER</B> String => index catalog (may be null);
* null when TYPE is tableIndexStatistic
* <LI><B>INDEX_NAME</B> String => index name; null when TYPE is
* tableIndexStatistic
* <LI><B>TYPE</B> short => index type:
* <UL>
* <LI> tableIndexStatistic - this identifies table statistics that are
* returned in conjuction with a table's index descriptions
* <LI> tableIndexClustered - this is a clustered index
* <LI> tableIndexHashed - this is a hashed index
* <LI> tableIndexOther - this is some other style of index
* </UL>
* <LI><B>ORDINAL_POSITION</B> short => column sequence number
* within index; zero when TYPE is tableIndexStatistic
* <LI><B>COLUMN_NAME</B> String => column name; null when TYPE is
* tableIndexStatistic
* <LI><B>ASC_OR_DESC</B> String => column sort sequence, "A" => ascending
* "D" => descending, may be null if sort sequence is not supported;
* null when TYPE is tableIndexStatistic
* <LI><B>CARDINALITY</B> int => When TYPE is tableIndexStatisic then
* this is the number of rows in the table; otherwise it is the
* number of unique values in the index.
* <LI><B>PAGES</B> int => When TYPE is tableIndexStatisic then
* this is the number of pages used for the table, otherwise it
* is the number of pages used for the current index.
* <LI><B>FILTER_CONDITION</B> String => Filter condition, if any.
* (may be null)
* </OL>
*
* @param catalog a catalog name; "" retrieves those without a catalog
* @param schema a schema name pattern; "" retrieves those without a schema
* @param table a table name
* @param unique when true, return only indices for unique values;
* when false, return indices regardless of whether unique or not
* @param approximate when true, result is allowed to reflect approximate
* or out of data values; when false, results are requested to be
* accurate
* @return ResultSet each row is an index column description
*/
// Implementation note: This is required for Borland's JBuilder to work
public java.sql.ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate) throws SQLException
{
// for now, this returns an empty result set.
Field f[] = new Field[13];
ResultSet r; // ResultSet for the SQL query that we need to do
Vector v = new Vector(); // The new ResultSet tuple stuff
f[0] = new Field(connection, "TABLE_CAT", iVarcharOid, 32);
f[1] = new Field(connection, "TABLE_SCHEM", iVarcharOid, 32);
f[2] = new Field(connection, "TABLE_NAME", iVarcharOid, 32);
f[3] = new Field(connection, "NON_UNIQUE", iBoolOid, 1);
f[4] = new Field(connection, "INDEX_QUALIFIER", iVarcharOid, 32);
f[5] = new Field(connection, "INDEX_NAME", iVarcharOid, 32);
f[6] = new Field(connection, "TYPE", iInt2Oid, 2);
f[7] = new Field(connection, "ORDINAL_POSITION", iInt2Oid, 2);
f[8] = new Field(connection, "COLUMN_NAME", iVarcharOid, 32);
f[9] = new Field(connection, "ASC_OR_DESC", iVarcharOid, 32);
f[10] = new Field(connection, "CARDINALITY", iInt4Oid, 4);
f[11] = new Field(connection, "PAGES", iInt4Oid, 4);
f[12] = new Field(connection, "FILTER_CONDITION", iVarcharOid, 32);
return new ResultSet(connection, f, v, "OK", 1);
}
}
|
package org.postgresql.util;
import org.postgresql.Driver;
/**
* This class holds the current build number and a utility program to print
* it and the file it came from. The primary purpose of this is to keep
* from filling the cvs history of Driver.java.in with commits simply
* changing the build number. The utility program can also be helpful for
* people to determine what version they really have and resolve problems
* with old and unknown versions located somewhere in the classpath.
*/
public class PSQLDriverVersion {
public final static int buildNumber = 601;
public static void main(String args[]) {
java.net.URL url = Driver.class.getResource("/org/postgresql/Driver.class");
System.out.println(Driver.getVersion());
System.out.println("Found in: " + url);
}
}
|
package com.akjava.gwt.poseeditor.client;
import java.util.ArrayList;
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 com.akjava.bvh.client.BVH;
import com.akjava.bvh.client.BVHMotion;
import com.akjava.bvh.client.BVHNode;
import com.akjava.bvh.client.BVHParser;
import com.akjava.bvh.client.BVHParser.ParserListener;
import com.akjava.bvh.client.BVHWriter;
import com.akjava.gwt.bvh.client.poseframe.PoseEditorData;
import com.akjava.gwt.bvh.client.poseframe.PoseFrameData;
import com.akjava.gwt.bvh.client.threejs.AnimationBoneConverter;
import com.akjava.gwt.bvh.client.threejs.AnimationDataConverter;
import com.akjava.gwt.bvh.client.threejs.BVHConverter;
import com.akjava.gwt.html5.client.HTML5InputRange;
import com.akjava.gwt.html5.client.download.HTML5Download;
import com.akjava.gwt.html5.client.extra.HTML5Builder;
import com.akjava.gwt.lib.client.StorageControler;
import com.akjava.gwt.lib.client.StorageDataList.HeaderAndValue;
import com.akjava.gwt.poseeditor.client.PreferenceTabPanel.PreferenceListener;
import com.akjava.gwt.poseeditor.client.resources.PoseEditorBundles;
import com.akjava.gwt.three.client.THREE;
import com.akjava.gwt.three.client.core.Geometry;
import com.akjava.gwt.three.client.core.Intersect;
import com.akjava.gwt.three.client.core.Matrix4;
import com.akjava.gwt.three.client.core.Object3D;
import com.akjava.gwt.three.client.core.Projector;
import com.akjava.gwt.three.client.core.Vector3;
import com.akjava.gwt.three.client.core.Vector4;
import com.akjava.gwt.three.client.core.Vertex;
import com.akjava.gwt.three.client.extras.GeometryUtils;
import com.akjava.gwt.three.client.extras.ImageUtils;
import com.akjava.gwt.three.client.extras.loaders.JSONLoader.LoadHandler;
import com.akjava.gwt.three.client.gwt.GWTGeometryUtils;
import com.akjava.gwt.three.client.gwt.GWTThreeUtils;
import com.akjava.gwt.three.client.gwt.Object3DUtils;
import com.akjava.gwt.three.client.gwt.ThreeLog;
import com.akjava.gwt.three.client.gwt.animation.AngleAndPosition;
import com.akjava.gwt.three.client.gwt.animation.AnimationBone;
import com.akjava.gwt.three.client.gwt.animation.AnimationBonesData;
import com.akjava.gwt.three.client.gwt.animation.AnimationData;
import com.akjava.gwt.three.client.gwt.animation.AnimationHierarchyItem;
import com.akjava.gwt.three.client.gwt.animation.AnimationKey;
import com.akjava.gwt.three.client.gwt.animation.BoneLimit;
import com.akjava.gwt.three.client.gwt.animation.NameAndVector3;
import com.akjava.gwt.three.client.gwt.animation.WeightBuilder;
import com.akjava.gwt.three.client.gwt.animation.ik.CDDIK;
import com.akjava.gwt.three.client.gwt.animation.ik.IKData;
import com.akjava.gwt.three.client.gwt.core.BoundingBox;
import com.akjava.gwt.three.client.gwt.ui.SimpleTabDemoEntryPoint;
import com.akjava.gwt.three.client.lights.Light;
import com.akjava.gwt.three.client.materials.Material;
import com.akjava.gwt.three.client.objects.Mesh;
import com.akjava.gwt.three.client.renderers.WebGLRenderer;
import com.akjava.gwt.three.client.textures.Texture;
import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.dom.client.ImageElement;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.ContextMenuEvent;
import com.google.gwt.event.dom.client.ContextMenuHandler;
import com.google.gwt.event.dom.client.LoadEvent;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseMoveEvent;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.event.dom.client.MouseWheelEvent;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.MenuItem;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class PoseEditor extends SimpleTabDemoEntryPoint implements PreferenceListener{
private BVH bvh;
protected JsArray<AnimationBone> bones;
private AnimationData animationData;
public static DateTimeFormat dateFormat=DateTimeFormat.getFormat("yy/MM/dd HH:mm");
private String version="2.0";
@Override
protected void beforeUpdate(WebGLRenderer renderer) {
if(root!=null){
root.setPosition((double)positionXRange.getValue()/10, (double)positionYRange.getValue()/10, (double)positionZRange.getValue()/10);
root.getRotation().set(Math.toRadians(rotationXRange.getValue()),Math.toRadians(rotationYRange.getValue()),Math.toRadians(rotationZRange.getValue()));
}
}
@Override
public void resized(int width, int height) {
super.resized(width, height);
leftBottom(bottomPanel);
}
private WebGLRenderer renderer;
public static final String KEY_INDEX="DATA_INDEX";
public static final String KEY_DATA="DATA_VALUE";
public static final String KEY_IMAGE="DATA_IMAGE";
public static final String KEY_HEAD="DATA_HEAD";
public class ContextMenu implements ContextMenuHandler{
@Override
public void onContextMenu(ContextMenuEvent event) {
event.preventDefault();
event.stopPropagation();
showContextMenu(event.getNativeEvent().getClientX(), event.getNativeEvent().getClientY());
}
}
@Override
protected void initializeOthers(WebGLRenderer renderer) {
this.renderer=renderer;
canvas.addDomHandler(new ContextMenu(), ContextMenuEvent.getType());
storageControler = new StorageControler();
this.renderer=renderer;
canvas.setClearColorHex(0x333333);
scene.add(THREE.AmbientLight(0xffffff));
Light pointLight = THREE.DirectionalLight(0xffffff,1);
pointLight.setPosition(0, 10, 300);
scene.add(pointLight);
Light pointLight2 = THREE.DirectionalLight(0xffffff,1);//for fix back side dark problem
pointLight2.setPosition(0, 10, -300);
//scene.add(pointLight2);
root=THREE.Object3D();
scene.add(root);
Geometry geo=THREE.PlaneGeometry(100, 100,20,20);
Mesh mesh=THREE.Mesh(geo, THREE.MeshBasicMaterial().color(0xaaaaaa).wireFrame().build());
mesh.setRotation(Math.toRadians(-90), 0, 0);
root.add(mesh);
//line removed,because of flicking
Mesh xline=GWTGeometryUtils.createLineMesh(THREE.Vector3(-50, 0, 0.001), THREE.Vector3(50, 0, 0.001), 0x880000,3);
//root.add(xline);
Mesh zline=GWTGeometryUtils.createLineMesh(THREE.Vector3(0, 0, -50), THREE.Vector3(0, 0, 50), 0x008800,3);
//root.add(zline);
selectionMesh=THREE.Mesh(THREE.CubeGeometry(2, 2, 2), THREE.MeshBasicMaterial().color(0x00ff00).wireFrame(true).build());
root.add(selectionMesh);
selectionMesh.setVisible(false);
//line flicked think something
//delay make problem
//loadBVH("pose.bvh");//initial bone
IKData ikdata1=new IKData("LowerBack-Neck1");
//ikdata1.setTargetPos(THREE.Vector3(0, 20, 0));
ikdata1.setLastBoneName("Head");
ikdata1.setBones(new String[]{"Neck1","Neck","Spine","LowerBack"});
//ikdata1.setBones(new String[]{"Neck1","Neck","Spine1","Spine","LowerBack"});
ikdata1.setIteration(9);
ikdatas.add(ikdata1);
IKData ikdata0=new IKData("RightArm-RightForeArm");
//ikdata0.setTargetPos(THREE.Vector3(-10, 5, 0));
ikdata0.setLastBoneName("RightHand");
ikdata0.setBones(new String[]{"RightForeArm","RightArm"});
// ikdata0.setBones(new String[]{"RightForeArm","RightArm","RightShoulder"});
ikdata0.setIteration(7);
ikdatas.add(ikdata0);
IKData ikdata=new IKData("RightUpLeg-RightLeg");
//ikdata.setTargetPos(THREE.Vector3(0, -10, 0));
ikdata.setLastBoneName("RightFoot");
ikdata.setBones(new String[]{"RightLeg","RightUpLeg"});
ikdata.setIteration(5);
ikdatas.add(ikdata);
IKData ikdata2=new IKData("LeftArm-LeftForeArm");
//ikdata0.setTargetPos(THREE.Vector3(-10, 5, 0));
ikdata2.setLastBoneName("LeftHand");
//ikdata2.setBones(new String[]{"LeftForeArm","LeftArm","LeftShoulder"});
ikdata2.setBones(new String[]{"LeftForeArm","LeftArm"});
ikdata2.setIteration(7);
ikdatas.add(ikdata2);
IKData ikdata3=new IKData("LeftUpLeg-LeftLeg");
//ikdata.setTargetPos(THREE.Vector3(0, -10, 0));
ikdata3.setLastBoneName("LeftFoot");
ikdata3.setBones(new String[]{"LeftLeg","LeftUpLeg"});
ikdata3.setIteration(5);
ikdatas.add(ikdata3);
//updateIkLabels();
//calcurate by bvh 80_*
/*
boneLimits.put("RightForeArm",BoneLimit.createBoneLimit(-118, 0, 0, 60, -170, 0));
boneLimits.put("RightArm",BoneLimit.createBoneLimit(-180, 180, -60, 91, -180, 180));
boneLimits.put("RightShoulder",BoneLimit.createBoneLimit(0, 0, 0, 0,0, 0));
boneLimits.put("LeftForeArm",BoneLimit.createBoneLimit(-40, 10, -170, 0, 0, 0));
boneLimits.put("LeftArm",BoneLimit.createBoneLimit(-80, 60, -91, 40, -120, 50));
boneLimits.put("LeftShoulder",BoneLimit.createBoneLimit(-15, 25, -20, 20,-10, 10));
boneLimits.put("RightLeg",BoneLimit.createBoneLimit(0, 160, 0, 0, 0, 20));
boneLimits.put("RightUpLeg",BoneLimit.createBoneLimit(-85, 91, -35, 5, -80, 40));
boneLimits.put("LeftLeg",BoneLimit.createBoneLimit(0, 160, 0, 0, -20, 0));
boneLimits.put("LeftUpLeg",BoneLimit.createBoneLimit(-85, 91, -5, 35, -40, 80));
boneLimits.put("LowerBack",BoneLimit.createBoneLimit(-30, 30, -60, 60, -30, 30));
boneLimits.put("Spine",BoneLimit.createBoneLimit(-30, 30, -40, 40, -40, 40));
//boneLimits.put("Spine1",BoneLimit.createBoneLimit(-30, 30, -30, 30, -30, 30));
boneLimits.put("Neck",BoneLimit.createBoneLimit(-45, 45, -45, 45, -45, 45));
boneLimits.put("Neck1",BoneLimit.createBoneLimit(-15, 15, -15, 15, -15, 15));
*/
//there are gimbal lock problem angle must be under 90
/*
* to manual change to joint angle,keep under 90 is better.
but gimbal lock problem happend alreay at IK result converted to eular angle
*/
/*
boneLimits.put("RightForeArm",BoneLimit.createBoneLimit(-89, 10, 0, 89, -10, 10));
boneLimits.put("RightArm",BoneLimit.createBoneLimit(-80, 60, -40, 89, -50,89));
boneLimits.put("LeftForeArm",BoneLimit.createBoneLimit(-89, 10, -89.9, 0, -10, 10));
boneLimits.put("LeftArm",BoneLimit.createBoneLimit(-80, 60, -89, 40, -89, 50));
boneLimits.put("RightLeg",BoneLimit.createBoneLimit(0, 89, 0, 0, 0, 40));
boneLimits.put("RightUpLeg",BoneLimit.createBoneLimit(-85, 89, -35, 5, -80, 40));
boneLimits.put("LeftLeg",BoneLimit.createBoneLimit(0, 89, 0, 0, -40, 0));
boneLimits.put("LeftUpLeg",BoneLimit.createBoneLimit(-85, 89, -5, 35, -40, 80));
boneLimits.put("LowerBack",BoneLimit.createBoneLimit(-30, 30, -60, 60, -30, 30));
boneLimits.put("Spine",BoneLimit.createBoneLimit(-30, 30, -40, 40, -40, 40));
//boneLimits.put("Spine1",BoneLimit.createBoneLimit(-30, 30, -30, 30, -30, 30));
boneLimits.put("Neck",BoneLimit.createBoneLimit(-35, 35, -35, 35, -35, 35));
boneLimits.put("Neck1",BoneLimit.createBoneLimit(-5, 5, -5, 5, -5, 5));
*/
//manual
boneLimits.put("RightForeArm",BoneLimit.createBoneLimit(-40, 10, 0, 140, -30, 10));
boneLimits.put("RightArm",BoneLimit.createBoneLimit(-80, 60, -75, 91, -70, 115));
boneLimits.put("LeftForeArm",BoneLimit.createBoneLimit(-40, 10, -140, 0, -10, 30));
boneLimits.put("LeftArm",BoneLimit.createBoneLimit(-80, 60, -91, 75, -115, 70));
boneLimits.put("RightLeg",BoneLimit.createBoneLimit(0, 160, 0, 0, 0, 20));
boneLimits.put("RightUpLeg",BoneLimit.createBoneLimit(-120, 60, -35, 5, -80, 40));
boneLimits.put("LeftLeg",BoneLimit.createBoneLimit(0, 160, 0, 0, -20, 0));
boneLimits.put("LeftUpLeg",BoneLimit.createBoneLimit(-120, 60, -5, 35, -40, 80));
boneLimits.put("LowerBack",BoneLimit.createBoneLimit(-30, 30, -60, 60, -30, 30));
boneLimits.put("Spine",BoneLimit.createBoneLimit(-30, 30, -40, 40, -40, 40));
//boneLimits.put("Spine1",BoneLimit.createBoneLimit(-30, 30, -30, 30, -30, 30));
boneLimits.put("Neck",BoneLimit.createBoneLimit(-29, 29, -29, 29, -29, 29));
boneLimits.put("Neck1",BoneLimit.createBoneLimit(-5, 5, -5, 5, -5, 5));
//for initialize texture
texture=ImageUtils.loadTexture("female001_texture1.jpg");//initial one
//generateTexture();
parseInitialBVHAndLoadModels(PoseEditorBundles.INSTANCE.pose().getText());
createTabs();
updateDatasPanel();
}
private void updateDatasPanel(){
datasPanel.clear();
int index=storageControler.getValue(KEY_INDEX, 0);
for(int i=index;i>=0;i
String b64=storageControler.getValue(KEY_IMAGE+i,null);
String json=storageControler.getValue(KEY_DATA+i,null);
String head=storageControler.getValue(KEY_HEAD+i,null);
if(b64!=null && json!=null){
DataPanel dp=new DataPanel(i,head,b64,json);
//dp.setSize("200px", "200px");
datasPanel.add(dp);
}
}
}
public class DataPanel extends HorizontalPanel{
private int index;
private String name;
private long cdate;
private String json;
public DataPanel(final int ind,String head,String base64, String text){
json=text;
this.index=ind;
Image img=new Image();
img.setUrl(base64);
this.setVerticalAlignment(ALIGN_MIDDLE);
String name_cdate[]=head.split("\t");
name=name_cdate[0];
cdate=(long)(Double.parseDouble(name_cdate[1]));
String dlabel=dateFormat.format(new Date(cdate));
add(new Label(dlabel));
add(img);
final Label nameLabel=new Label(name);
nameLabel.setWidth("160px");
add(nameLabel);
Button loadBt=new Button("Load");
add(loadBt);
loadBt.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
int loadedIndex=isLoaded(ind);
if(loadedIndex!=-1){
selectPoseEditorDatas(loadedIndex);
tabPanel.selectTab(0);//datas
return;
}
PoseEditorData ped=PoseEditorData.readData(json);
if(ped!=null){
ped.setFileId(ind);
doLoad(ped);
}else{
//TODO error catch
Window.alert("load faild");
}
}
});
Button editBt=new Button("Edit Name");
add(editBt);
editBt.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
JSONValue jsonValue=JSONParser.parseLenient(json);
JSONObject ped=jsonValue.isObject();
if(ped!=null){
String newName=Window.prompt("Change Name",name);
//ped.setName(newName);
name=newName;
ped.put("name", new JSONString(name));
json=ped.toString();
nameLabel.setText(name);
//JSONObject data=PoseEditorData.writeData(ped);
storageControler.setValue(KEY_DATA+index, json);
storageControler.setValue(KEY_HEAD+index, name+"\t"+cdate);
//rewrite
}else{
//TODO error catch
Window.alert("load faild");
}
}
});
Button removeBt=new Button("Delate");
add(removeBt);
removeBt.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
boolean ret=Window.confirm("Delete data:"+name);
if(ret){
doRemoveData(index);
}
}
});
Button exportBt=new Button("Export");
add(exportBt);
exportBt.addClickHandler(new ClickHandler() {
private Anchor anchor;
@Override
public void onClick(ClickEvent event) {
PoseEditorData ped=PoseEditorData.readData(json);
String bvhText=convertBVHText(ped);
if(anchor!=null){
anchor.removeFromParent();
}
anchor = HTML5Download.generateTextDownloadLink(bvhText, nameLabel.getText()+".bvh", "Click to download",true);
add(anchor);
}
});
}
}
private int isLoaded(int index){
for(int i=0;i<poseEditorDatas.size();i++){
PoseEditorData data=poseEditorDatas.get(i);
if(data.getFileId()==index){
return i;
}
}
return -1;
}
private void doRemoveData(int index){
storageControler.setValue(KEY_DATA+index, null);
storageControler.setValue(KEY_IMAGE+index, null);
storageControler.setValue(KEY_HEAD+index, null);
updateDatasPanel();
}
private void createTabs(){
tabPanel.addSelectionHandler(new SelectionHandler<Integer>() {
@Override
public void onSelection(SelectionEvent<Integer> event) {
int selection=event.getSelectedItem();
if(selection==0){
stats.setVisible(true);
showControl();
bottomPanel.setVisible(true);
dialog2.setVisible(true);
}else{
stats.setVisible(false);
bottomPanel.setVisible(false);
hideControl();
dialog2.setVisible(false);
}
resized(screenWidth,screenHeight);//for some blackout;
}
});
VerticalPanel datasRoot=new VerticalPanel();
tabPanel.add(datasRoot,"Datas");
datasPanel = new VerticalPanel();
//datasPanel.setStyleName("debug");
ScrollPanel scroll=new ScrollPanel(datasPanel);
scroll.setSize("720px", "500px");
datasRoot.add(scroll);
log("selection:"+storageControler.getValue(PreferenceTabPanel.KEY_MODEL_SELECTION, 0));
//storageControler.setValue(PreferenceTabPanel.KEY_MODEL_SELECTION, 0);
preferencePanel=new PreferenceTabPanel(storageControler,this);
tabPanel.add(preferencePanel,"Preference");
//about
String html="";
html+="<br/>"+"[Howto Move]<br/><b>Select Nothing:</b><br/>Mouse Drag=Rotatation-XY<br/>Mouse Wheel= Zoom<br/> +ALT Move-XY Camera";
html+="<br/><br/>"+"<b>Select IK(Green Box):</b><br/>Mouse Drag=Move IK-XY <br/>Mouse Wheel=Move IK-Z <br/>+Shift=smoth-change <br/>+Alt=Move Only<br/>+ALT+Shift Follow other IK";
html+="<br/><br/>"+"<b>Select Bone(Red Box):</b><br/>Mouse Drag=Rotate-XY<br/>Mouse Wheel=Rotate-Z";
html+="<br/><br/>"+"<b>Select Root(Red Large Box):</b><br/>Mouse Drag=Rotate-XY<br/>Mouse Wheel=Rotate-Z +Shift=Follow IK +Alt=Move Position";
html+="<br/><br/>"+"yello box means under Y:0,orange box means near Y:0";
html+="<br/>On IK-Moving switching normal & +Shift(Smooth) is good tactics.";
html+="<br/>"+"<a href='http://webgl.akjava.com'>More info at webgl.akjava.com</a>";
HTML htmlP=new HTML(html);
VerticalPanel aboutRoot=new VerticalPanel();
//TODO credit
aboutRoot.add(htmlP);
tabPanel.add(aboutRoot,"About");
}
PreferenceTabPanel preferencePanel;
Map<String,BoneLimit> boneLimits=new HashMap<String,BoneLimit>();
private void updateIkLabels(){
//log(""+boneNamesBox);
boneNamesBox.clear();
if(currentSelectionIkName!=null){
setEnableBoneRanges(false,false);//no root
boneNamesBox.addItem("");
for(int i=0;i<getCurrentIkData().getBones().size();i++){
boneNamesBox.addItem(getCurrentIkData().getBones().get(i));
}
boneNamesBox.setSelectedIndex(0);
}else if(selectedBone!=null){
setEnableBoneRanges(true,true);
boneNamesBox.addItem(selectedBone);
boneNamesBox.setSelectedIndex(0);
updateBoneRanges();
}else{
setEnableBoneRanges(false,false);
}
if(boneNamesBox.getItemCount()==0){
rotateAndPosList.setEnabled(false);
boneRotationsPanel.setVisible(false);
bonePositionsPanel.setVisible(false);
}else{
rotateAndPosList.setEnabled(true);
if(rotateAndPosList.getSelectedIndex()==0){
boneRotationsPanel.setVisible(true);
}else{
bonePositionsPanel.setVisible(true);
}
}
}
private void setEnableBoneRanges(boolean rotate,boolean pos){
rotationBoneXRange.setEnabled(rotate);
rotationBoneYRange.setEnabled(rotate);
rotationBoneZRange.setEnabled(rotate);
positionXBoneRange.setEnabled(pos);
positionYBoneRange.setEnabled(pos);
positionZBoneRange.setEnabled(pos);
}
int ikdataIndex=1;
List<IKData> ikdatas=new ArrayList<IKData>();
private String currentSelectionIkName;
Mesh selectionMesh;
final Projector projector=THREE.Projector();
@Override
public void onMouseClick(ClickEvent event) {
//not work correctly on zoom
//Vector3 pos=GWTUtils.toWebGLXY(event.getX(), event.getY(), camera, screenWidth, screenHeight);
// targetPos.setX(pos.getX());
//targetPos.setY(pos.getY());
//doCDDIk();
//doPoseIkk(0);
}
private boolean isSelectedIk(){
return currentSelectionIkName!=null;
}
private void switchSelectionIk(String name){
currentSelectionIkName=name;
currentMatrixs=AnimationBonesData.cloneAngleAndMatrix(ab.getBonesAngleAndMatrixs());
if(currentSelectionIkName!=null){
List<List<NameAndVector3>> result=createBases(getCurrentIkData());
//log("switchd:"+result.size());
List<NameAndVector3> tmp=result.get(result.size()-1);
for(NameAndVector3 value:tmp){
// log(value.getName()+":"+ThreeLog.get(value.getVector3()));
}
if(candiateAngleAndMatrixs!=null){
candiateAngleAndMatrixs.clear();
}else{
candiateAngleAndMatrixs=new ArrayList<List<AngleAndPosition>>();
}
//log("result-size:"+result.size());
int index=0;
for(List<NameAndVector3> nv:result){
//log("candiate:"+index);
List<AngleAndPosition> bm=AnimationBonesData.cloneAngleAndMatrix(currentMatrixs);
applyMatrix(bm, nv);
//deb
for(String bname:getCurrentIkData().getBones()){
Vector3 angle=bm.get(ab.getBoneIndex(bname)).getAngle();
//log(bname+":"+ThreeLog.get(angle));
}
candiateAngleAndMatrixs.add(bm);
index++;
}
}else{
// log("null selected");
}
updateIkLabels();
}
public List<List<NameAndVector3>> createBases(IKData data){
int angle=30;
if(data.getLastBoneName().equals("RightFoot") || data.getLastBoneName().equals("LeftFoot")){
//something special for foot
angle=20;
}
List<List<NameAndVector3>> all=new ArrayList();
List<List<NameAndVector3>> result=new ArrayList();
for(int i=0;i<data.getBones().size();i++){
String name=data.getBones().get(i);
List<NameAndVector3> patterns=createBases(name,angle); //90 //60 is slow
all.add(patterns);
//log(name+"-size:"+patterns.size());
}
//log(data.getLastBoneName()+"-joint-size:"+all.size());
addBase(all,result,data.getBones(),0,null,2);
return result;
}
private void addBase(List<List<NameAndVector3>> all,
List<List<NameAndVector3>> result, List<String> boneNames, int index,List<NameAndVector3> tmp,int depth) {
if(index>=boneNames.size() || index==depth){
result.add(tmp);
return;
}
if(index==0){
tmp=new ArrayList<NameAndVector3>();
}
for(NameAndVector3 child:all.get(index)){
//copied
List<NameAndVector3> list=new ArrayList<NameAndVector3>();
for(int i=0;i<tmp.size();i++){
list.add(tmp.get(i));
}
list.add(child);
addBase(all,result,boneNames,index+1,list,2);
}
}
private List<NameAndVector3> createBases(String name,int step){
Set<NameAndVector3> patterns=new HashSet<NameAndVector3>();
BoneLimit limit=boneLimits.get(name);
/*
for(int x=-180;x<180;x+=step){
for(int y=-180;y<180;y+=step){
for(int z=-180;z<180;z+=step){
boolean pass=true;
if(limit!=null){
if(limit.getMinXDegit()>x || limit.getMaxXDegit()<x){
pass=false;
}
if(limit.getMinYDegit()>y || limit.getMaxYDegit()<y){
pass=false;
}
if(limit.getMinZDegit()>z || limit.getMaxZDegit()<z){
pass=false;
}
}
if(x==180||x==-180 || y==180||y==-180||z==180||z==-180){
//pass=false;//no need to limit?
}
if(pass){
log(name+" pass:"+x+","+y+","+z);
NameAndVector3 nvec=new NameAndVector3(name, Math.toRadians(x),Math.toRadians(y),Math.toRadians(z));
patterns.add(nvec);
}
}
}
}*/
//0 - -180
for(int x=0;x>=-180;x-=step){
for(int y=0;y>=-180;y-=step){
for(int z=0;z>=-180;z-=step){
boolean pass=true;
if(limit!=null){
if(limit.getMinXDegit()>x || limit.getMaxXDegit()<x){
pass=false;
}
if(limit.getMinYDegit()>y || limit.getMaxYDegit()<y){
pass=false;
}
if(limit.getMinZDegit()>z || limit.getMaxZDegit()<z){
pass=false;
}
}
if(x==180||x==-180 || y==180||y==-180||z==180||z==-180){
//pass=false;//no need to limit?
}
if(pass){
// log(name+" pass:"+x+","+y+","+z);
NameAndVector3 nvec=new NameAndVector3(name, Math.toRadians(x),Math.toRadians(y),Math.toRadians(z));
patterns.add(nvec);
}
}
}
}
//step - 179
for(int x=0;x<180;x+=step){
for(int y=0;y<180;y+=step){
for(int z=0;z<180;z+=step){
boolean pass=true;
if(limit!=null){
if(limit.getMinXDegit()>x || limit.getMaxXDegit()<x){
pass=false;
}
if(limit.getMinYDegit()>y || limit.getMaxYDegit()<y){
pass=false;
}
if(limit.getMinZDegit()>z || limit.getMaxZDegit()<z){
pass=false;
}
}
if(x==180||x==-180 || y==180||y==-180||z==180||z==-180){
//pass=false;//no need to limit?
}
if(pass){
// log(name+" pass:"+x+","+y+","+z);
NameAndVector3 nvec=new NameAndVector3(name, Math.toRadians(x),Math.toRadians(y),Math.toRadians(z));
patterns.add(nvec);
}
}
}
}
if(patterns.size()==0){
log(name+":use zero base");
patterns.add(new NameAndVector3(name,0,0,0));//empty not allowd
}
return new ArrayList<NameAndVector3>(patterns);
}
PopupPanel contextMenu;
private void showContextMenu(int left,int top){
if(contextMenu==null){
createContextMenu();
}
contextMenu.setPopupPosition(left, top);
contextMenu.show();
}
private void hideContextMenu(){
if(contextMenu!=null){
contextMenu.hide();
}
}
private void createContextMenu(){
contextMenu=new PopupPanel();
MenuBar rootBar=new MenuBar(true);
contextMenu.add(rootBar);
rootBar.setAutoOpen(true);
MenuBar ikBar=new MenuBar(true);
rootBar.addItem("Ik",ikBar);
ikBar.addItem("Exec", new Command(){
@Override
public void execute() {
for(IKData ik:ikdatas){
doPoseIkk(0,false,45,ik,10);
}
hideContextMenu();
}});
ikBar.addItem("Follow target", new Command(){
@Override
public void execute() {
for(IKData ik:ikdatas){
String name=ik.getLastBoneName();
Vector3 pos=ab.getBonePosition(name);
ik.getTargetPos().set(pos.getX(), pos.getY(), pos.getZ());
doPoseByMatrix(ab);
hideContextMenu();
}
}});
ikBar.addItem("Y-Zero", new Command(){
@Override
public void execute() {
for(IKData ik:ikdatas){
String name=ik.getLastBoneName();
Vector3 pos=ab.getBonePosition(name);
ik.getTargetPos().setY(0);
doPoseByMatrix(ab);
hideContextMenu();
}
}});
ikBar.addItem("Move to First-IK-XZ", new Command(){
@Override
public void execute() {
for(IKData ik:ikdatas){
String name=ik.getBones().get(0);
Vector3 pos=ab.getBonePosition(name);
ik.getTargetPos().setX(pos.getX());
ik.getTargetPos().setZ(pos.getZ());
doPoseByMatrix(ab);
hideContextMenu();
}
}});
ikBar.addItem("Move to Last-IK-XZ", new Command(){
@Override
public void execute() {
for(IKData ik:ikdatas){
String name=ik.getBones().get(ik.getBones().size()-1);
Vector3 pos=ab.getBonePosition(name);
ik.getTargetPos().setX(pos.getX());
ik.getTargetPos().setZ(pos.getZ());
doPoseByMatrix(ab);
hideContextMenu();
}
}});
createContextMenuRoot(rootBar);
MenuBar boneLimitBar=new MenuBar(true);
MenuItem boneLimitMenuItem = new MenuItem("Bone Limit",boneLimitBar);//menu item can change label dynamic
rootBar.addItem(boneLimitMenuItem);
boneLimitBar.addItem("Change bones'limit to none", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
IKData ik=getCurrentIkData();
for(String boneName:ik.getBones()){
boneLock.clearX(boneName);
boneLock.clearY(boneName);
boneLock.clearZ(boneName);
}
updateBoneRotationRanges();
hideContextMenu();
}});
boneLimitBar.addItem("Change bones'limit to X", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
IKData ik=getCurrentIkData();
for(String boneName:ik.getBones()){
boneLock.clearY(boneName);
boneLock.clearZ(boneName);
boneLock.setX(boneName,ab.getBoneAngleAndMatrix(boneName).getAngle().getX());
}
updateBoneRotationRanges();
hideContextMenu();
}});
boneLimitBar.addItem("Change bones'limit to Y", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
IKData ik=getCurrentIkData();
for(String boneName:ik.getBones()){
boneLock.clearX(boneName);
boneLock.clearZ(boneName);
boneLock.setY(boneName,ab.getBoneAngleAndMatrix(boneName).getAngle().getY());
}
updateBoneRotationRanges();
hideContextMenu();
}});
boneLimitBar.addItem("Change bones'limit to Z", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
IKData ik=getCurrentIkData();
for(String boneName:ik.getBones()){
boneLock.clearZ(boneName);
boneLock.clearZ(boneName);
boneLock.setZ(boneName,ab.getBoneAngleAndMatrix(boneName).getAngle().getZ());
}
updateBoneRotationRanges();
hideContextMenu();
}});
boneLimitBar.addItem("Change bones'limit to Y,Z", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
IKData ik=getCurrentIkData();
for(String boneName:ik.getBones()){
boneLock.clearX(boneName);
boneLock.setY(boneName,ab.getBoneAngleAndMatrix(boneName).getAngle().getY());
boneLock.setZ(boneName,ab.getBoneAngleAndMatrix(boneName).getAngle().getZ());
}
updateBoneRotationRanges();
hideContextMenu();
}});
boneLimitBar.addItem("Change bones'limit to X,Z", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
IKData ik=getCurrentIkData();
for(String boneName:ik.getBones()){
boneLock.clearY(boneName);
boneLock.setX(boneName,ab.getBoneAngleAndMatrix(boneName).getAngle().getX());
boneLock.setZ(boneName,ab.getBoneAngleAndMatrix(boneName).getAngle().getZ());
}
updateBoneRotationRanges();
hideContextMenu();
}});
boneLimitBar.addItem("Change bones'limit to Y,X", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
IKData ik=getCurrentIkData();
for(String boneName:ik.getBones()){
boneLock.clearZ(boneName);
boneLock.setY(boneName,ab.getBoneAngleAndMatrix(boneName).getAngle().getY());
boneLock.setX(boneName,ab.getBoneAngleAndMatrix(boneName).getAngle().getX());
}
updateBoneRotationRanges();
hideContextMenu();
}});
//createContextMenuFrames(rootBar);
MenuBar cameraBar=new MenuBar(true);
rootBar.addItem("Camera",cameraBar);
cameraBar.addItem("Front", new Command(){
@Override
public void execute() {
rotationXRange.setValue(0);
rotationYRange.setValue(0);
rotationZRange.setValue(0);
positionXRange.setValue(0);
positionYRange.setValue(-140);
hideContextMenu();
}});
cameraBar.addItem("Back", new Command(){
@Override
public void execute() {
rotationXRange.setValue(0);
rotationYRange.setValue(180);
rotationZRange.setValue(0);
positionXRange.setValue(0);
positionYRange.setValue(-140);
hideContextMenu();
}});
cameraBar.addItem("Quoter", new Command(){
@Override
public void execute() {
rotationXRange.setValue(45);
rotationYRange.setValue(45);
rotationZRange.setValue(0);
positionXRange.setValue(0);
positionYRange.setValue(-140);
hideContextMenu();
}});
cameraBar.addItem("Top", new Command(){
@Override
public void execute() {
rotationXRange.setValue(90);
rotationYRange.setValue(0);
rotationZRange.setValue(0);
positionXRange.setValue(0);
positionYRange.setValue(0);
hideContextMenu();
}});
cameraBar.addItem("Bottom", new Command(){
@Override
public void execute() {
rotationXRange.setValue(-90);
rotationYRange.setValue(0);
rotationZRange.setValue(0);
positionXRange.setValue(0);
positionYRange.setValue(0);
hideContextMenu();
}});
cameraBar.addItem("Right", new Command(){
@Override
public void execute() {
rotationXRange.setValue(0);
rotationYRange.setValue(90);
rotationZRange.setValue(0);
positionXRange.setValue(0);
positionYRange.setValue(-140);
hideContextMenu();
}});
cameraBar.addItem("Left", new Command(){
@Override
public void execute() {
rotationXRange.setValue(0);
rotationYRange.setValue(-90);
rotationZRange.setValue(0);
positionXRange.setValue(0);
positionYRange.setValue(-140);
hideContextMenu();
}});
}
private void createContextMenuRoot(MenuBar rootBar){
MenuBar rootBoneBar=new MenuBar(true);
rootBar.addItem("Root",rootBoneBar);
rootBoneBar.addItem("touch ground(Y-0)", new Command(){
@Override
public void execute() {
bodyMesh.getGeometry().computeBoundingBox();
log(bodyMesh.getGeometry());
BoundingBox box=bodyMesh.getGeometry().getBoundingBox();
Vector3 currentRoot=ab.getBonePosition(0);
currentRoot.setY(currentRoot.getY()-box.getMin().getY());
log("min:"+ThreeLog.get(box.getMin()));
log("max:"+ThreeLog.get(box.getMax()));
ab.getBoneAngleAndMatrix(0).getPosition().setY(currentRoot.getY());
ab.getBoneAngleAndMatrix(0).updateMatrix();
doPoseByMatrix(ab);
hideContextMenu();
}});
rootBoneBar.addItem("initial Position", new Command(){
@Override
public void execute() {
ab.getBoneAngleAndMatrix(0).setPosition(getInitialPoseFrameData().getPositions().get(0).clone());
ab.getBoneAngleAndMatrix(0).updateMatrix();
doPoseByMatrix(ab);
hideContextMenu();
}});
rootBoneBar.addItem("Move to selection IK-X", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
Vector3 target=getCurrentIkData().getTargetPos();
Vector3 rootPos=ab.getBonePosition(0);
Vector3 diff=target.clone().subSelf(rootPos);
diff.setY(0);
diff.setZ(0);
ab.getBoneAngleAndMatrix(0).setPosition(rootPos.addSelf(diff));
ab.getBoneAngleAndMatrix(0).updateMatrix();
doPoseByMatrix(ab);
hideContextMenu();
}});
rootBoneBar.addItem("Move to selection IK-Y", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
Vector3 target=getCurrentIkData().getTargetPos();
Vector3 rootPos=ab.getBonePosition(0);
Vector3 diff=target.clone().subSelf(rootPos);
diff.setX(0);
diff.setZ(0);
ab.getBoneAngleAndMatrix(0).setPosition(rootPos.addSelf(diff));
ab.getBoneAngleAndMatrix(0).updateMatrix();
doPoseByMatrix(ab);
hideContextMenu();
}});
rootBoneBar.addItem("Move to selection IK-Z", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
Vector3 target=getCurrentIkData().getTargetPos();
Vector3 rootPos=ab.getBonePosition(0);
Vector3 diff=target.clone().subSelf(rootPos);
diff.setY(0);
diff.setX(0);
ab.getBoneAngleAndMatrix(0).setPosition(rootPos.addSelf(diff));
ab.getBoneAngleAndMatrix(0).updateMatrix();
doPoseByMatrix(ab);
hideContextMenu();
}});
rootBoneBar.addItem("Move to selection IK", new Command(){
@Override
public void execute() {
if(!isSelectedIk()){
hideContextMenu();
return;
}
Vector3 target=getCurrentIkData().getTargetPos();
Vector3 rootPos=ab.getBonePosition(0);
Vector3 diff=target.clone().subSelf(rootPos);
ab.getBoneAngleAndMatrix(0).setPosition(rootPos.addSelf(diff));
ab.getBoneAngleAndMatrix(0).updateMatrix();
doPoseByMatrix(ab);
hideContextMenu();
/*
for(IKData ik:ikdatas){
ik.getTargetPos().addSelf(diff);
doPoseByMatrix(ab);
hideContextMenu();
}
*/
}});
rootBoneBar.addItem("180 to -180", new Command(){
@Override
public void execute() {
Vector3 angle=ab.getBoneAngleAndMatrix(0).getAngle();
log(ThreeLog.get(angle));
if(angle.getX()==180){
angle.setX(-180);
}else if(angle.getX()==-180){
angle.setX(180);
}
if(angle.getY()==180){
angle.setY(-180);
}else if(angle.getY()==-180){
angle.setY(180);
}
if(angle.getZ()==180){
angle.setZ(-180);
}else if(angle.getZ()==-180){
angle.setZ(180);
}
//ab.getBoneAngleAndMatrix(0).setPosition(getInitialPoseFrameData().getPositions().get(0).clone());
ab.getBoneAngleAndMatrix(0).updateMatrix();
doPoseByMatrix(ab);
updateBoneRotationRanges();
hideContextMenu();
}});
}
//TODO future
private boolean isShowPrevIk;
private void createContextMenuFrames(MenuBar rootBar){
MenuBar framesBar=new MenuBar(true);
contextMenuShowPrevFrame = new MenuItem("Show Prev Iks",true,new Command(){
@Override
public void execute() {
contextMenuShowPrevFrame.setHTML("<b>"+"Show Prev Iks"+"</b>");
contextMenuHidePrefIks.setHTML("Hide Prev Iks");
isShowPrevIk=true;
hideContextMenu();
}});
framesBar.addItem(contextMenuShowPrevFrame);
contextMenuHidePrefIks = new MenuItem("<b>"+"Hide Prev Iks"+"</b>",true,new Command(){
@Override
public void execute() {
contextMenuShowPrevFrame.setHTML(""+"Show Prev Iks"+"");
contextMenuHidePrefIks.setHTML("<b>"+"Hide Prev Iks"+"</b>");
isShowPrevIk=false;
hideContextMenu();
}});
framesBar.addItem(contextMenuHidePrefIks);
rootBar.addItem("Frames",framesBar);
}
private PoseFrameData getInitialPoseFrameData(){
return initialPoseFrameData;
}
@Override
public void onMouseDown(MouseDownEvent event) {
mouseDown=true;
mouseDownX=event.getX();
mouseDownY=event.getY();
if(event.getNativeButton()==NativeEvent.BUTTON_RIGHT){
// showContextMenu(mouseDownX, mouseDownY);
return;
}else{
hideContextMenu();
}
//middle cant select anything
if(event.getNativeButton()==NativeEvent.BUTTON_MIDDLE){
return;
}
//log(mouseDownX+","+mouseDownY+":"+screenWidth+"x"+screenHeight);
//log("mouse-click:"+event.getX()+"x"+event.getY());
JsArray<Intersect> intersects=projector.gwtPickIntersects(event.getX(), event.getY(), screenWidth, screenHeight, camera,scene);
//log("intersects-length:"+intersects.length());
for(int i=0;i<intersects.length();i++){
Intersect sect=intersects.get(i);
Object3D target=sect.getObject();
if(!target.getName().isEmpty()){
if(target.getName().startsWith("ik:")){
String bname=target.getName().substring(3);
for(int j=0;j<ikdatas.size();j++){
if(ikdatas.get(j).getLastBoneName().equals(bname)){
ikdataIndex=j;
selectionMesh.setVisible(true);
selectionMesh.setPosition(target.getPosition());
selectionMesh.getMaterial().getColor().setHex(0x00ff00);
if(!bname.equals(currentSelectionIkName)){
switchSelectionIk(bname);
}
selectedBone=null;
return;//ik selected
}
}
}else{
//maybe bone or root
//log("select:"+target.getName());
selectedBone=target.getName();
selectionMesh.setVisible(true);
selectionMesh.setPosition(target.getPosition());
selectionMesh.getMaterial().getColor().setHex(0xff0000);
switchSelectionIk(null);
return;
}
}
}
//log("no-selection");
selectedBone=null;
selectionMesh.setVisible(false);
switchSelectionIk(null);
}
private String selectedBone;
@Override
public void onMouseUp(MouseUpEvent event) {
mouseDown=false;
}
@Override
public void onMouseOut(MouseOutEvent event) {
mouseDown=false;
}
@Override
public void onMouseMove(MouseMoveEvent event) {
double diffX=event.getX()-mouseDownX;
double diffY=event.getY()-mouseDownY;
mouseDownX=event.getX();
mouseDownY=event.getY();
if(event.getNativeEvent().getButton()==NativeEvent.BUTTON_MIDDLE){
changeCamera((int)diffX,(int)diffY,event.isShiftKeyDown(),event.isAltKeyDown(),event.isControlKeyDown());
return;
}
if(mouseDown){
if(isSelectedIk()){
diffX*=0.1;
diffY*=-0.1;
getCurrentIkData().getTargetPos().incrementX(diffX);
getCurrentIkData().getTargetPos().incrementY(diffY);
if(event.isAltKeyDown()){//slow
if(event.isShiftKeyDown()){
log("shift+alt");
doPoseIkk(0,false,1,getCurrentIkData(),1);
log("pik");
for(IKData ik:ikdatas){
//log("ik:"+ik.getName());
if(ik!=getCurrentIkData()){
doPoseIkk(0,false,5,ik,1);
}
}
}else{
//not work correctly
doPoseIkk(0,false,1,getCurrentIkData(),10);
}
}else if(event.isShiftKeyDown()){//move only
//doPoseIkk(0,true,1,getCurrentIkData(),1);
doPoseByMatrix(ab);
}else{
doPoseIkk(0,true,1,getCurrentIkData(),5);
}
}else if(isSelectedBone()){
if(event.isShiftKeyDown()){//move position
int boneIndex=ab.getBoneIndex(selectedBone);
Vector3 pos=null;
if(boneIndex==0){//this version support moving root only
pos=ab.getBonePosition(boneIndex);
}
positionXBoneRange.setValue(positionXBoneRange.getValue()+(int)diffX);
positionYBoneRange.setValue(positionYBoneRange.getValue()-(int)diffY);
positionToBone();
if(event.isAltKeyDown()){//not follow ik
// switchSelectionIk(null);
//effect-ik
for(IKData ik:ikdatas){
doPoseIkk(0,false,5,ik,1);
}
}else{ //follow ik
if(boneIndex==0){
Vector3 movedPos=ab.getBonePosition(boneIndex);
movedPos.subSelf(pos);
for(IKData ik:ikdatas){
ik.getTargetPos().addSelf(movedPos);
}
doPoseByMatrix(ab);//redraw
}
}
}else{
Vector3 angle=ab.getBoneAngleAndMatrix(selectedBone).getAngle();
rotationBoneXRange.setValue(getRotationRangeValue(rotationBoneXRange.getValue(),(int)diffY));
rotationBoneYRange.setValue(getRotationRangeValue(rotationBoneYRange.getValue(),(int)diffX));
//rotationBoneXRange.setValue(rotationBoneXRange.getValue()+diffY);
//rotationBoneYRange.setValue(rotationBoneYRange.getValue()+diffX);
rotToBone();
if(event.isAltKeyDown()){
// switchSelectionIk(null);
//effect-ik
for(IKData ik:ikdatas){
doPoseIkk(0,false,5,ik,1);
}
}else{
Vector3 rootPos=ab.getBonePosition(0);
Vector3 movedAngle=ab.getBoneAngleAndMatrix(selectedBone).getAngle().clone();
movedAngle.subSelf(angle);
log("before:"+ThreeLog.get(angle)+" moved:"+ThreeLog.get(movedAngle));
Matrix4 mx=GWTThreeUtils.degitRotationToMatrix4(movedAngle);
for(IKData ik:ikdatas){
/*
Vector3 ikpos=ik.getTargetPos().clone().subSelf(rootPos);
mx.multiplyVector3(ikpos);
ik.setTargetPos(ikpos.addSelf(rootPos));
*/
String name=ik.getLastBoneName();
Vector3 pos=ab.getBonePosition(name);
ik.getTargetPos().set(pos.getX(), pos.getY(), pos.getZ());
}
doPoseByMatrix(ab);//redraw
}
}
}
else{//global
changeCamera((int)diffX,(int)diffY,event.isShiftKeyDown(),event.isAltKeyDown(),event.isControlKeyDown());
}
}
}
private void changeCamera(int diffX,int diffY,boolean shiftKey,boolean AltKey,boolean ctrlKey){
if(shiftKey){
positionXRange.setValue(positionXRange.getValue()+diffX);
positionYRange.setValue(positionYRange.getValue()-diffY);
}else{
rotationXRange.setValue(getRotationRangeValue(rotationXRange.getValue(),diffY));
rotationYRange.setValue(getRotationRangeValue(rotationYRange.getValue(),diffX));
}
}
private int getRotationRangeValue(int oldValue,int diffValue){
int angle=oldValue+diffValue;
if(angle>180){
int over=angle-180;
angle=-180+over;
}
if(angle<-180){
int under=angle+180;
angle=180+under;
}
return angle;
}
private boolean isSelectedBone(){
return !isSelectedIk() && selectedBone!=null;
}
private IKData getCurrentIkData(){
return ikdatas.get(ikdataIndex);
}
@Override
public void onMouseWheel(MouseWheelEvent event) {
if(isSelectedIk()){
double dy=event.getDeltaY()*0.2;
getCurrentIkData().getTargetPos().incrementZ(dy);
if(event.isAltKeyDown()){//slow
if(event.isShiftKeyDown()){
doPoseIkk(0,false,1,getCurrentIkData(),1);
for(IKData ik:ikdatas){
if(ik!=getCurrentIkData()){
doPoseIkk(0,false,5,ik,1);
}
}
}else{
doPoseIkk(0,false,1,getCurrentIkData(),10);
}
}else if(event.isShiftKeyDown()){//move only
//doPoseIkk(0,true,1,getCurrentIkData(),1);
doPoseByMatrix(ab);
}else{
doPoseIkk(0,true,1,getCurrentIkData(),5);
}
}else if(isSelectedBone()){
if(event.isShiftKeyDown()){//move
int diff=event.getDeltaY();
int boneIndex=ab.getBoneIndex(selectedBone);
Vector3 pos=null;
if(boneIndex==0){//this version support moving root only
pos=ab.getBonePosition(boneIndex);
}
positionZBoneRange.setValue(positionZBoneRange.getValue()+diff);
positionToBone();
if(event.isAltKeyDown()){
//switchSelectionIk(null);
//effect-ik
for(IKData ik:ikdatas){
doPoseIkk(0,false,5,ik,1);
}
}else{//follow
if(boneIndex==0){
Vector3 moved=ab.getBonePosition(boneIndex);
moved.subSelf(pos);
for(IKData ik:ikdatas){
ik.getTargetPos().addSelf(moved);
}
}
}
}else{
int diff=event.getDeltaY();
Vector3 angle=ab.getBoneAngleAndMatrix(selectedBone).getAngle();
rotationBoneZRange.setValue(getRotationRangeValue(rotationBoneZRange.getValue(),diff));
//rotationBoneZRange.setValue(rotationBoneZRange.getValue()+diff);
rotToBone();
if(event.isAltKeyDown()){
// switchSelectionIk(null);
//effect-ik
for(IKData ik:ikdatas){
doPoseIkk(0,false,5,ik,1);
}
}else{
Vector3 rootPos=ab.getBonePosition(0);
Vector3 movedAngle=ab.getBoneAngleAndMatrix(selectedBone).getAngle().clone();
movedAngle.subSelf(angle);
log("before:"+ThreeLog.get(angle)+" moved:"+ThreeLog.get(movedAngle));
Matrix4 mx=GWTThreeUtils.degitRotationToMatrix4(movedAngle);
for(IKData ik:ikdatas){
/*
* i faild turn
Vector3 ikpos=ik.getTargetPos().clone().subSelf(rootPos);
mx.multiplyVector3(ikpos);
ik.setTargetPos(ikpos.addSelf(rootPos));
*/
String name=ik.getLastBoneName();
Vector3 pos=ab.getBonePosition(name);
ik.getTargetPos().set(pos.getX(), pos.getY(), pos.getZ());
}
doPoseByMatrix(ab);//redraw
}
}
}
else{
//TODO make class
long t=System.currentTimeMillis();
if(mouseLast+100>t){
tmpZoom*=2;
}else{
tmpZoom=defaultZoom;
}
//GWT.log("wheel:"+event.getDeltaY());
int tmp=cameraZ+event.getDeltaY()*tmpZoom;
tmp=Math.max(minCamera, tmp);
tmp=Math.min(4000, tmp);
cameraZ=tmp;
mouseLast=t;
}
}
private HTML5InputRange positionXRange;
private HTML5InputRange positionYRange;
private HTML5InputRange positionZRange;
//private HTML5InputRange frameRange;
private HTML5InputRange rotationXRange;
private HTML5InputRange rotationYRange;
private HTML5InputRange rotationZRange;
private HTML5InputRange rotationBoneXRange;
private HTML5InputRange rotationBoneYRange;
private HTML5InputRange rotationBoneZRange;
private PopupPanel bottomPanel;
private HTML5InputRange currentFrameRange;
private Label currentFrameLabel;
private HTML5InputRange positionXBoneRange;
private HTML5InputRange positionYBoneRange;
private HTML5InputRange positionZBoneRange;
private CheckBox ylockCheck;
private CheckBox xlockCheck;
private List<String> ikLocks=new ArrayList<String>();
private CheckBox showBonesCheck;
@Override
public void createControl(Panel parent) {
HorizontalPanel h1=new HorizontalPanel();
rotationXRange = new HTML5InputRange(-180,180,0);
parent.add(HTML5Builder.createRangeLabel("X-Rotate:", rotationXRange));
parent.add(h1);
h1.add(rotationXRange);
Button reset=new Button("Reset");
reset.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotationXRange.setValue(0);
}
});
h1.add(reset);
HorizontalPanel h2=new HorizontalPanel();
rotationYRange = new HTML5InputRange(-180,180,0);
parent.add(HTML5Builder.createRangeLabel("Y-Rotate:", rotationYRange));
parent.add(h2);
h2.add(rotationYRange);
Button reset2=new Button("Reset");
reset2.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotationYRange.setValue(0);
}
});
h2.add(reset2);
HorizontalPanel h3=new HorizontalPanel();
rotationZRange = new HTML5InputRange(-180,180,0);
parent.add(HTML5Builder.createRangeLabel("Z-Rotate:", rotationZRange));
parent.add(h3);
h3.add(rotationZRange);
Button reset3=new Button("Reset");
reset3.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotationZRange.setValue(0);
}
});
h3.add(reset3);
HorizontalPanel h4=new HorizontalPanel();
positionXRange = new HTML5InputRange(-300,300,0);
parent.add(HTML5Builder.createRangeLabel("X-Position:", positionXRange,10));
parent.add(h4);
h4.add(positionXRange);
Button reset4=new Button("Reset");
reset4.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionXRange.setValue(0);
}
});
h4.add(reset4);
HorizontalPanel h5=new HorizontalPanel();
positionYRange = new HTML5InputRange(-300,300,0);
parent.add(HTML5Builder.createRangeLabel("Y-Position:", positionYRange,10));
parent.add(h5);
h5.add(positionYRange);
Button reset5=new Button("Reset");
reset5.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionYRange.setValue(0);
}
});
h5.add(reset5);
//maybe z no need,there are whell-zoom
HorizontalPanel h6=new HorizontalPanel();
positionZRange = new HTML5InputRange(-300,300,0);
//parent.add(HTML5Builder.createRangeLabel("Z-Position:", positionZRange,10));
//parent.add(h6);
h6.add(positionZRange);
Button reset6=new Button("Reset");
reset6.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionZRange.setValue(0);
}
});
h6.add(reset6);
transparentCheck = new CheckBox();
parent.add(transparentCheck);
transparentCheck.setText("transparent");
transparentCheck.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
updateMaterial();
}
});
transparentCheck.setValue(true);
basicMaterialCheck = new CheckBox();
parent.add(basicMaterialCheck);
basicMaterialCheck.setText("BasicMaterial");
basicMaterialCheck.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
updateMaterial();
}
});
showBonesCheck = new CheckBox();
parent.add(showBonesCheck);
showBonesCheck.setText("Show Bones");
showBonesCheck.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
updateBonesVisible();
}
});
showBonesCheck.setValue(true);
//dont need now
/*
HorizontalPanel frames=new HorizontalPanel();
frameRange = new HTML5InputRange(0,1,0);
parent.add(HTML5Builder.createRangeLabel("Frame:", frameRange));
//parent.add(frames);
frames.add(frameRange);
*/
/*
frameRange.addListener(new HTML5InputRangeListener() {
@Override
public void changed(int newValue) {
doPose(frameRange.getValue());
}
});
*/
HorizontalPanel boneInfo=new HorizontalPanel();
parent.add(boneInfo);
boneInfo.add(new Label("Bone"));
rotateAndPosList = new ListBox();
boneInfo.add(rotateAndPosList);
rotateAndPosList.addItem("Rotation");
rotateAndPosList.addItem("Position");
rotateAndPosList.setSelectedIndex(0);
rotateAndPosList.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
switchRotateAndPosList();
}
});
HorizontalPanel boneNames=new HorizontalPanel();
parent.add(boneNames);
boneNamesBox = new ListBox();
boneNamesBox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
updateBoneRanges();
}
});
boneNames.add(boneNamesBox);
ikLockCheck = new CheckBox("ik-lock");
boneNames.add(ikLockCheck);
ikLockCheck.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
//String name=boneNameBox.get
if(ikLockCheck.getValue()){
ikLocks.add(getSelectedBoneName());
}else{
ikLocks.remove(getSelectedBoneName());
}
}
});
//mirror
HorizontalPanel mButtons=new HorizontalPanel();
Button mirror=new Button("do Mirror");
mirror.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doMirror();
}
});
parent.add(mButtons);
mButtons.add(mirror);
Button swap=new Button("do Swap");
swap.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doSwap();
}
});
mButtons.add(swap);
bonePostionAndRotationContainer = new VerticalPanel();
bonePostionAndRotationContainer.setSize("210px", "150px");
bonePostionAndRotationContainer.setVerticalAlignment(VerticalPanel.ALIGN_MIDDLE);
parent.add(bonePostionAndRotationContainer);
//positions
bonePositionsPanel = new VerticalPanel();
bonePostionAndRotationContainer.add(bonePositionsPanel);
bonePositionsPanel.setVisible(false);
HorizontalPanel h1bpos=new HorizontalPanel();
positionXBoneRange = new HTML5InputRange(-300,300,0);
bonePositionsPanel.add(HTML5Builder.createRangeLabel("X-Pos:", positionXBoneRange,10));
bonePositionsPanel.add(h1bpos);
h1bpos.add(positionXBoneRange);
Button resetB1pos=new Button("Reset");
resetB1pos.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionXBoneRange.setValue(0);
positionToBone();
}
});
h1bpos.add(resetB1pos);
positionXBoneRange.addMouseUpHandler(new MouseUpHandler() {
@Override
public void onMouseUp(MouseUpEvent event) {
positionToBone();
}
});
HorizontalPanel h2bpos=new HorizontalPanel();
positionYBoneRange = new HTML5InputRange(-300,300,0);
bonePositionsPanel.add(HTML5Builder.createRangeLabel("Y-Pos:", positionYBoneRange,10));
bonePositionsPanel.add(h2bpos);
h2bpos.add(positionYBoneRange);
Button reset2bpos=new Button("Reset");
reset2bpos.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionYBoneRange.setValue(0);
positionToBone();
}
});
h2bpos.add(reset2bpos);
positionYBoneRange.addMouseUpHandler(new MouseUpHandler() {
@Override
public void onMouseUp(MouseUpEvent event) {
positionToBone();
}
});
HorizontalPanel h3bpos=new HorizontalPanel();
positionZBoneRange = new HTML5InputRange(-300,300,0);
bonePositionsPanel.add(HTML5Builder.createRangeLabel("Z-Pos:", positionZBoneRange,10));
bonePositionsPanel.add(h3bpos);
h3bpos.add(positionZBoneRange);
Button reset3bpos=new Button("Reset");
reset3bpos.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
positionZBoneRange.setValue(0);
positionToBone();
}
});
h3bpos.add(reset3bpos);
positionZBoneRange.addMouseUpHandler(new MouseUpHandler() {
@Override
public void onMouseUp(MouseUpEvent event) {
positionToBone();
}
});
boneRotationsPanel = new VerticalPanel();
bonePostionAndRotationContainer.add(boneRotationsPanel);
HorizontalPanel h1b=new HorizontalPanel();
xlockCheck = new CheckBox();
h1b.add(xlockCheck);
xlockCheck.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if(xlockCheck.getValue()){
boneLock.setX(getSelectedBoneName(), rotationBoneXRange.getValue());
rotationBoneXRange.setEnabled(false);
}else{
boneLock.clearX(getSelectedBoneName());
rotationBoneXRange.setEnabled(true);
}
}
});
rotationBoneXRange = new HTML5InputRange(-180,180,0);
boneRotationsPanel.add(HTML5Builder.createRangeLabel("X-Rotate:", rotationBoneXRange));
boneRotationsPanel.add(h1b);
h1b.add(rotationBoneXRange);
Button resetB1=new Button("Reset");
resetB1.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotationBoneXRange.setValue(0);
rotToBone();
}
});
h1b.add(resetB1);
rotationBoneXRange.addMouseUpHandler(new MouseUpHandler() {
@Override
public void onMouseUp(MouseUpEvent event) {
rotToBone();
}
});
HorizontalPanel h2b=new HorizontalPanel();
ylockCheck = new CheckBox();
h2b.add(ylockCheck);
ylockCheck.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if(ylockCheck.getValue()){
boneLock.setY(getSelectedBoneName(), rotationBoneYRange.getValue());
rotationBoneYRange.setEnabled(false);
}else{
boneLock.clearY(getSelectedBoneName());
rotationBoneYRange.setEnabled(true);
}
}
});
rotationBoneYRange = new HTML5InputRange(-180,180,0);
boneRotationsPanel.add(HTML5Builder.createRangeLabel("Y-Rotate:", rotationBoneYRange));
boneRotationsPanel.add(h2b);
h2b.add(rotationBoneYRange);
Button reset2b=new Button("Reset");
reset2b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotationBoneYRange.setValue(0);
rotToBone();
}
});
h2b.add(reset2b);
rotationBoneYRange.addMouseUpHandler(new MouseUpHandler() {
@Override
public void onMouseUp(MouseUpEvent event) {
rotToBone();
}
});
HorizontalPanel h3b=new HorizontalPanel();
zlockCheck = new CheckBox();
h3b.add(zlockCheck);
zlockCheck.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if(zlockCheck.getValue()){
boneLock.setZ(getSelectedBoneName(), rotationBoneZRange.getValue());
rotationBoneZRange.setEnabled(false);
}else{
boneLock.clearZ(getSelectedBoneName());
rotationBoneZRange.setEnabled(true);
}
}
});
rotationBoneZRange = new HTML5InputRange(-180,180,0);
boneRotationsPanel.add(HTML5Builder.createRangeLabel("Z-Rotate:", rotationBoneZRange));
boneRotationsPanel.add(h3b);
h3b.add(rotationBoneZRange);
Button reset3b=new Button("Reset");
reset3b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
rotationBoneZRange.setValue(0);
rotToBone();
}
});
h3b.add(reset3b);
rotationBoneZRange.addMouseUpHandler(new MouseUpHandler() {
@Override
public void onMouseUp(MouseUpEvent event) {
rotToBone();
}
});
/*
* crash so oftern if you use don't forget add
* THREE.WebGLRenderer(GWTRenderObject.create().preserveDrawingBuffer());
*
Button test=new Button("screen-shot");
parent.add(test);
test.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
//better screen shot
//Keep before setting
//change setting if
//re render
//back to setting
String url=renderer.gwtPngDataUrl();
//log(url);
//String text="<img style='position:absolute;top:0;left:0' src='"+url+"'>";
//ExportUtils.openTabHtml(text, "screenshot"+screenShotIndex);
ExportUtils.openTabImage(url, "screenshot"+screenShotIndex);
screenShotIndex++;
//Window.open(url, "newwin"+screenShotIndex, null); sometime crash and kill owner
screenShotIndex++;
}
});
*/
/*
parent.add(new Label("Texture Image"));
final FileUploadForm textureUpload=new FileUploadForm();
parent.add(textureUpload);
textureUpload.getFileUpload().addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
JsArray<File> files = FileUtils.toFile(event.getNativeEvent());
final FileReader reader=FileReader.createFileReader();
reader.setOnLoad(new FileHandler() {
@Override
public void onLoad() {
//log("load:"+Benchmark.end("load"));
//GWT.log(reader.getResultAsString());
textureUrl=reader.getResultAsString();
updateMaterial();
}
});
reader.readAsDataURL(files.get(0));
textureUpload.reset();
}
});
*/
positionYRange.setValue(-140);//for test
updateIkLabels();
createBottomPanel();
showControl();
}
private int screenShotIndex;
protected void doSwap() {
if(isSelectedIk() && getSelectedBoneName().isEmpty()){
IKData ik=getCurrentIkData();
for(String name:ik.getBones()){
String targetName=getMirroredName(name);
if(targetName==null){
continue;
}
int index=ab.getBoneIndex(targetName);
int srcIndex=ab.getBoneIndex(name);
if(index!=-1 && srcIndex!=-1){
Vector3 angle1=ab.getBoneAngleAndMatrix(srcIndex).getAngle();
Vector3 angle=ab.getBoneAngleAndMatrix(index).getAngle();
rotToBone(name, angle.getX(), -angle.getY(), -angle.getZ());
rotToBone(targetName, angle1.getX(), -angle1.getY(), -angle1.getZ());
}
}
//move ik pos
IKData targetIk=getIk(getMirroredName(ik.getName()));
if(targetIk!=null){
Vector3 root=ab.getBonePosition(0);
Vector3 targetPos=targetIk.getTargetPos().clone().subSelf(root);
targetPos.setX(targetPos.getX()*-1);
targetPos.addSelf(root);
Vector3 srcPos=ik.getTargetPos().clone().subSelf(root);
srcPos.setX(srcPos.getX()*-1);
srcPos.addSelf(root);
ik.getTargetPos().set(targetPos.getX(),targetPos.getY(),targetPos.getZ());
targetIk.getTargetPos().set(srcPos.getX(),srcPos.getY(),srcPos.getZ());
doPoseByMatrix(ab);
}
}else{
String name=getSelectedBoneName();
if(name==null){
return;
}
//h mirror
String targetName=getMirroredName(name);
if(targetName==null){
return;
}
int index=ab.getBoneIndex(targetName);
if(index!=-1){
Vector3 targetAngle=ab.getBoneAngleAndMatrix(index).getAngle();
double x=rotationBoneXRange.getValue();
double y=rotationBoneYRange.getValue()*-1;
double z=rotationBoneZRange.getValue()*-1;
rotationBoneXRange.setValue((int) targetAngle.getX());
rotationBoneYRange.setValue((int) targetAngle.getY()*-1);
rotationBoneZRange.setValue((int) targetAngle.getZ()*-1);
rotToBone(targetName,x,y,z);
rotToBone();
}
}
}
private IKData getIk(String name){
for(IKData ik:ikdatas){
if(ik.getName().equals(name)){
return ik;
}
}
return null;
}
protected void doMirror() {
if(isSelectedIk() && getSelectedBoneName().isEmpty()){
IKData ik=getCurrentIkData();
for(String name:ik.getBones()){
String targetName=getMirroredName(name);
if(targetName==null){
continue;
}
int index=ab.getBoneIndex(targetName);
if(index!=-1){
Vector3 angle=ab.getBoneAngleAndMatrix(index).getAngle();
rotToBone(name, angle.getX(), -angle.getY(), -angle.getZ());
}
}
//move ik pos
IKData targetIk=getIk(getMirroredName(ik.getName()));
if(targetIk!=null){
Vector3 root=ab.getBonePosition(0);
Vector3 targetPos=targetIk.getTargetPos().clone().subSelf(root);
targetPos.setX(targetPos.getX()*-1);
targetPos.addSelf(root);
ik.getTargetPos().set(targetPos.getX(),targetPos.getY(),targetPos.getZ());
doPoseByMatrix(ab);
}
}else{//single bone
String name=getSelectedBoneName();
if(name==null){
return;
}
//h mirror
String targetName=getMirroredName(name);
log("mirror:"+targetName);
if(targetName==null){
return;
}
int index=ab.getBoneIndex(targetName);
if(index!=-1){
log("mirror:"+index);
Vector3 angle=ab.getBoneAngleAndMatrix(index).getAngle();
rotationBoneXRange.setValue((int) angle.getX());
rotationBoneYRange.setValue((int) angle.getY()*-1);
rotationBoneZRange.setValue((int) angle.getZ()*-1);
rotToBone();
}
}
}
protected void updateBonesVisible() {
if(bone3D!=null){
Object3DUtils.setVisibleAll(bone3D, showBonesCheck.getValue());
}
}
protected String getMirroredName(String name) {
if(name.indexOf("Right")!=-1){
return name.replace("Right", "Left");
}
if(name.indexOf("right")!=-1){
return name.replace("right", "left");
}
if(name.indexOf("Left")!=-1){
return name.replace("Left", "Right");
}
if(name.indexOf("left")!=-1){
return name.replace("left", "right");
}
return null;
}
private void LoadJsonModel(String jsonText){
GWTGeometryUtils.loadJsonModel(jsonText,new LoadHandler() {
@Override
public void loaded(Geometry geometry) {
if(bodyMesh!=null){
root.remove(bodyMesh);//for initialzie
bodyMesh=null;
}
ab=null;//for remake matrix.
baseGeometry=geometry;//change body mesh
if(baseGeometry.getBones()!=null){
log("create-bone from geometry");
setBone(baseGeometry.getBones());
}else{
log("bvh:"+bvh);
//initialize default bone
AnimationBoneConverter converter=new AnimationBoneConverter();
setBone(converter.convertJsonBone(bvh));
}
//log(""+(baseGeometry.getBones()!=null));
//log(baseGeometry.getBones());
doRePose(0);
//log("snapped");
if(poseEditorDatas.size()==0){//initial new list
initialPoseFrameData=snapCurrentFrameData();//get invalid pose
updateMaterial();
doNewFile();
}
}
});
}
private String getSelectedBoneName(){
if(boneNamesBox.getSelectedIndex()==-1){
return "";
}
return boneNamesBox.getValue(boneNamesBox.getSelectedIndex());
}
protected void positionToBone() {
String name=boneNamesBox.getItemText(boneNamesBox.getSelectedIndex());
int index=ab.getBoneIndex(name);
if(index!=0){
//limit root only
//TODO limit by bvh channel
return;
}
Vector3 pos=THREE.Vector3(positionXBoneRange.getValue(),
positionYBoneRange.getValue()
, positionZBoneRange.getValue()).multiplyScalar(0.1);
/*
Vector3 angles=GWTThreeUtils.rotationToVector3(ab.getBoneAngleAndMatrix(index).getMatrix());
Matrix4 posMx=GWTThreeUtils.translateToMatrix4(pos);
Matrix4 rotMx=GWTThreeUtils.rotationToMatrix4(angles);
rotMx.multiply(posMx,rotMx);
ab.getBoneAngleAndMatrix(index).setMatrix(rotMx);
*/
ab.getBoneAngleAndMatrix(index).setPosition(pos);
ab.getBoneAngleAndMatrix(index).updateMatrix();
doPoseByMatrix(ab);
if( isSelectedBone()){
selectionMesh.setPosition(pos);
}
}
protected void switchRotateAndPosList() {
int index=rotateAndPosList.getSelectedIndex();
if(index==0){
bonePositionsPanel.setVisible(false);
boneRotationsPanel.setVisible(true);
}else{
bonePositionsPanel.setVisible(true);
boneRotationsPanel.setVisible(false);
}
}
private String getNewName(){
return "Untitled"+(fileIndex);
}
private int fileIndex;
private void createBottomPanel(){
bottomPanel = new PopupPanel();
bottomPanel.setVisible(true);
bottomPanel.setSize("650px", "96px");
VerticalPanel main=new VerticalPanel();
bottomPanel.add(main);
//upper
HorizontalPanel topPanel=new HorizontalPanel();
main.add(topPanel);
fileNames = new ListBox();
fileNames.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
selectPoseEditorDatas(fileNames.getSelectedIndex());
}
});
topPanel.add(fileNames);
Button newFile=new Button("New");
topPanel.add(newFile);
newFile.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doNewFile();
}
});
saveButton = new Button("Save");
topPanel.add(saveButton);
saveButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doSaveFile();
}
});
Button saveAsButton = new Button("SaveAs");
topPanel.add(saveAsButton);
saveAsButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doSaveAsFile(getSelectedPoseEditorData());
}
});
HorizontalPanel upperPanel=new HorizontalPanel();
upperPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE);
main.add(upperPanel);
Button snap=new Button("Add");//TODO before,after
upperPanel.add(snap);
snap.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
insertFrame(getSelectedPoseEditorData().getPoseFrameDatas().size(),false);
}
});
Button replace=new Button("Replace");//TODO before,after
upperPanel.add(replace);
replace.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
insertFrame(currentFrameRange.getValue(),true);
}
});
/*
*should think system
Button cut=new Button("Cut");
upperPanel.add(cut);
cut.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doCut();
}
});
*/
Button copy=new Button("Copy");
upperPanel.add(copy);
copy.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doCopy();
}
});
Button paste=new Button("Paste");
upperPanel.add(paste);
paste.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doPaste();
getSelectedPoseEditorData().setModified(true);
updateSaveButtons();
}
});
Button remove=new Button("Remove");
upperPanel.add(remove);
remove.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
getSelectedPoseEditorData().getPoseFrameDatas().remove(poseFrameDataIndex);
getSelectedPoseEditorData().setModified(true);
updatePoseIndex(Math.max(0,poseFrameDataIndex-1));
updateSaveButtons();
}
});
HorizontalPanel pPanel=new HorizontalPanel();
main.add(pPanel);
pPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE);
currentFrameRange = new HTML5InputRange(0,0,0);
currentFrameRange.setWidth("420px");
pPanel.add(currentFrameRange);
currentFrameRange.addMouseUpHandler(new MouseUpHandler() {
@Override
public void onMouseUp(MouseUpEvent event) {
updatePoseIndex(currentFrameRange.getValue());
}
});
Button prev=new Button("Prev");
pPanel.add(prev);
prev.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
int value=currentFrameRange.getValue();
if(value>0){
value
currentFrameRange.setValue(value);
updatePoseIndex(value);
}
}
});
Button next=new Button("Next");
pPanel.add(next);
next.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
int value=currentFrameRange.getValue();
if(value<getSelectedPoseEditorData().getPoseFrameDatas().size()-1){
value++;
currentFrameRange.setValue(value);
updatePoseIndex(value);
}
}
});
currentFrameLabel = new Label();
currentFrameLabel.setWidth("40px");
pPanel.add(currentFrameLabel);
Button first=new Button("First");
pPanel.add(first);
first.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
currentFrameRange.setValue(0);
updatePoseIndex(0);
}
});
bottomPanel.show();
super.leftBottom(bottomPanel);
}
protected void doSaveAsFile(PoseEditorData pdata) {
String result=Window.prompt("Save File", pdata.getName());
if(result!=null){
pdata.setName(result);
JSONObject data=PoseEditorData.writeData(pdata);
fileNames.setItemText(poseEditorDataSelection, result);
//TODO
if(!storageControler.isAvailable()){
//TODO just export
Window.alert("not saved because your browser not supoort HTML5 storage");
return;
}
// Window.alert("hello");
//save database
int dataIndex=storageControler.getValue(KEY_INDEX, 0);
//TODO method?
Canvas canvas=Canvas.createIfSupported();
int thumbW=32;
int thumbH=32;
canvas.setSize(thumbW+"px", thumbH+"px");
canvas.setCoordinateSpaceWidth(thumbW);
canvas.setCoordinateSpaceHeight(thumbH);
//log(renderer.gwtCanvas());
//now stop write image.
//canvas.getContext2d().drawImage(renderer.gwtCanvas(),0,0,screenWidth,screenHeight,0,0,thumbW,thumbH);
String thumbnail=canvas.toDataUrl();
log(thumbnail);
// Window.alert("hello1");
//Window.alert("hello1");
//Window.open(thumbnail, "tmp", null);
try{
storageControler.setValue(KEY_DATA+dataIndex, data.toString());
// Window.alert("hello2");
storageControler.setValue(KEY_IMAGE+dataIndex, thumbnail);
storageControler.setValue(KEY_HEAD+dataIndex, pdata.getName()+"\t"+pdata.getCdate());
// Window.alert("hello3:"+dataIndex);
pdata.setFileId(dataIndex);
//increment
dataIndex++;
storageControler.setValue(KEY_INDEX, dataIndex);
pdata.setModified(false);
updateSaveButtons();
updateDatasPanel();
tabPanel.selectTab(1);//datas
}catch(Exception e){
alert(e.getMessage());
}
}
}
public static void alert(String message){
log(message);
if(message.indexOf("(QUOTA_EXCEEDED_ERR)")!=-1){
String title="QUOTA EXCEEDED_ERR\n";
title+="over internal HTML5 storage capacity.\n";
title+="please remove unused textures or models from Preference Tab";
Window.alert(title);
}else{
Window.alert("Error:"+message);
}
}
protected void doSaveFile() {
PoseEditorData pdata=getSelectedPoseEditorData();
int fileId=pdata.getFileId();
if(fileId!=-1){
JSONObject data=PoseEditorData.writeData(pdata);
try{
storageControler.setValue(KEY_DATA+fileId, data.toString());
pdata.setModified(false);
updateSaveButtons();
updateDatasPanel();
}catch(Exception e){
alert(e.getMessage());
}
}else{
doSaveAsFile(pdata);
}
//log(data.toString());
/*
//test
PoseEditorData readData=PoseEditorData.readData(data.toString());
readData.updateMatrix(ab);
readData.setName("tmp1");
doLoad(readData);
*/
}
private int poseEditorDataSelection;
List<PoseEditorData> poseEditorDatas=new ArrayList<PoseEditorData>();
public void selectPoseEditorDatas(int index){
poseEditorDataSelection=index;
fileNames.setSelectedIndex(index);
updatePoseIndex(0);
updateSaveButtons();
}
private PoseEditorData getSelectedPoseEditorData(){
return poseEditorDatas.get(poseEditorDataSelection);
}
protected void doNewFile() {
fileIndex++;
String newName=getNewName();
PoseEditorData ped=new PoseEditorData();
ped.setModified(true);//new always
ped.setName(newName);
ped.setCdate(System.currentTimeMillis());
List<PoseFrameData> pfList=new ArrayList<PoseFrameData>();
ped.setPoseFrameDatas(pfList);
pfList.add(initialPoseFrameData.clone());
ped.setBones(boneList);
poseEditorDatas.add(ped);
fileNames.addItem(newName);
fileNames.setSelectedIndex(fileNames.getItemCount()-1);
selectPoseEditorDatas(fileNames.getItemCount()-1);
updateSaveButtons();
}
public void doLoad(PoseEditorData ped){
ped.updateMatrix(ab);//need bone data
poseEditorDatas.add(ped);
fileNames.addItem(ped.getName());
selectPoseEditorDatas(poseEditorDatas.size()-1);
tabPanel.selectTab(0);//datas
//called addChangeHandler
updateSaveButtons();
}
protected void doPaste() {
if(clipboard!=null){
getSelectedPoseEditorData().getPoseFrameDatas().add(currentFrameRange.getValue()+1,clipboard.clone());
updatePoseIndex(currentFrameRange.getValue()+1);
}
}
protected void doCut() {
// TODO Auto-generated method stub
}
PoseFrameData clipboard;
private boolean availIk(IKData ik){
if(ab.getBoneIndex(ik.getLastBoneName())==-1){
return false;
}
for(String name:ik.getBones()){
if(ab.getBoneIndex(name)==-1){
return false;
}
}
return true;
}
protected void doCopy() {
// TODO Auto-generated method stub
clipboard=snapCurrentFrameData();
}
private PoseFrameData initialPoseFrameData;
private PoseFrameData snapCurrentFrameData(){
List<AngleAndPosition> matrixs=AnimationBonesData.cloneAngleAndMatrix(ab.getBonesAngleAndMatrixs());
List<Vector3> angles=new ArrayList<Vector3>();
List<Vector3> positions=new ArrayList<Vector3>();
for(int i=0;i<matrixs.size();i++){
Vector3 angle=matrixs.get(i).getAngle().clone();
angles.add(angle);
Vector3 position=ab.getMatrixPosition(i);//TODO getPosition()?
position.subSelf(ab.getBaseBoneRelativePosition(i));
positions.add(position);
// log(ab.getBoneName(i)+" pos="+ThreeLog.get(position)+",base="+ThreeLog.get(ab.getBaseBoneRelativePosition(i)));
}
List<Vector3> targets=new ArrayList<Vector3>();
List<String> names=new ArrayList<String>();
Map<String,Vector3> ikDataMap=new LinkedHashMap<String,Vector3>();
for(IKData ikdata:ikdatas){
if(!availIk(ikdata)){//check ik
continue;
}
Vector3 pos=ikdata.getTargetPos().clone();
pos.subSelf(ab.getBonePosition(ikdata.getLastBoneName()));//relative path
ikDataMap.put(ikdata.getName(), pos);
}
PoseFrameData ps=new PoseFrameData(matrixs, ikDataMap);
ps.setAngles(angles);
ps.setPositions(positions);
return ps;
}
private void insertFrame(int index,boolean overwrite){
if(index<0){
index=0;
}
PoseFrameData ps=snapCurrentFrameData();
if(overwrite){
getSelectedPoseEditorData().getPoseFrameDatas().set(index,ps);
updatePoseIndex(index);
}else{
getSelectedPoseEditorData().getPoseFrameDatas().add(index,ps);
updatePoseIndex(getSelectedPoseEditorData().getPoseFrameDatas().size()-1);
}
getSelectedPoseEditorData().setModified(true);
updateSaveButtons();
}
private void updateSaveButtons() {
if(getSelectedPoseEditorData().isModified()){
saveButton.setEnabled(true);
}else{
saveButton.setEnabled(false);
}
}
protected String convertBVHText(PoseEditorData ped) {
ped.updateMatrix(ab);//current-bone
BVH exportBVH=new BVH();
BVHConverter converter=new BVHConverter();
BVHNode node=converter.convertBVHNode(bones);
exportBVH.setHiearchy(node);
converter.setChannels(node,0,"XYZ"); //TODO support other order
BVHMotion motion=new BVHMotion();
motion.setFrameTime(.25);
for(PoseFrameData pose:ped.getPoseFrameDatas()){
double[] values=converter.angleAndMatrixsToMotion(pose.getAngleAndMatrixs(),BVHConverter.ROOT_POSITION_ROTATE_ONLY,"XYZ");
motion.add(values);
}
motion.setFrames(motion.getMotions().size());
exportBVH.setMotion(motion);
//log("frames:"+exportBVH.getFrames());
BVHWriter writer=new BVHWriter();
String bvhText=writer.writeToString(exportBVH);
return bvhText;
/*
//log(bvhText);
ExportUtils.exportTextAsDownloadDataUrl(bvhText, "UTF-8", "poseeditor"+exportIndex);
//ExportUtils.openTabTextChrome(bvhText,"poseeditor"+exportIndex);//
exportIndex++;
*/
}
private int exportIndex=0;
private int poseFrameDataIndex=0;
//private List<PoseFrameData> poseFrameDatas=new ArrayList<PoseFrameData>();
private void updatePoseIndex(int index){
if(index==-1){
currentFrameRange.setMax(0);
currentFrameRange.setValue(0);
currentFrameLabel.setText("");
}else{
//poseIndex=index;
currentFrameRange.setMax(getSelectedPoseEditorData().getPoseFrameDatas().size()-1);
currentFrameRange.setValue(index);
currentFrameLabel.setText((index+1)+"/"+getSelectedPoseEditorData().getPoseFrameDatas().size());
selectFrameData(index);
}
}
private void selectFrameData(int index) {
poseFrameDataIndex=index;
PoseFrameData pfd=getSelectedPoseEditorData().getPoseFrameDatas().get(index);
currentMatrixs=AnimationBonesData.cloneAngleAndMatrix(pfd.getAngleAndMatrixs());
ab.setBonesAngleAndMatrixs(currentMatrixs);
//update
for(int i=0;i<ikdatas.size();i++){
if(!availIk(ikdatas.get(i))){
continue;
}
String ikName=ikdatas.get(i).getName();
Vector3 vec=pfd.getIkTargetPosition(ikName);
//TODO auto generate
if(vec!=null){
vec=vec.clone();
vec.addSelf(ab.getBonePosition(ikdatas.get(i).getLastBoneName()));//relative path
ikdatas.get(i).getTargetPos().set(vec.getX(), vec.getY(), vec.getZ());
}
}
if(isSelectedIk()){
switchSelectionIk(getCurrentIkData().getLastBoneName());
}
doPoseByMatrix(ab);
updateBoneRanges();
}
private void rotToBone(String name,double x,double y,double z){
int index=ab.getBoneIndex(name);
//Matrix4 mx=ab.getBoneMatrix(name);
Vector3 degAngles=THREE.Vector3(x,y,z);
Vector3 angles=GWTThreeUtils.degreeToRagiant(degAngles);
//log("set-angle:"+ThreeLog.get(GWTThreeUtils.radiantToDegree(angles)));
//mx.setRotationFromEuler(angles, "XYZ");
Vector3 pos=GWTThreeUtils.toPositionVec(ab.getBoneAngleAndMatrix(index).getMatrix());
//log("pos:"+ThreeLog.get(pos));
Matrix4 posMx=GWTThreeUtils.translateToMatrix4(pos);
Matrix4 rotMx=GWTThreeUtils.rotationToMatrix4(angles);
rotMx.multiply(posMx,rotMx);
//log("bone-pos:"+ThreeLog.get(bones.get(index).getPos()));
ab.getBoneAngleAndMatrix(index).setMatrix(rotMx);
ab.getBoneAngleAndMatrix(index).setAngle(degAngles);
doPoseByMatrix(ab);
}
private void rotToBone(){
String name=boneNamesBox.getItemText(boneNamesBox.getSelectedIndex());
int index=ab.getBoneIndex(name);
//Matrix4 mx=ab.getBoneMatrix(name);
Vector3 degAngles=THREE.Vector3(rotationBoneXRange.getValue(),rotationBoneYRange.getValue(),rotationBoneZRange.getValue());
Vector3 angles=GWTThreeUtils.degreeToRagiant(degAngles);
//log("set-angle:"+ThreeLog.get(GWTThreeUtils.radiantToDegree(angles)));
//mx.setRotationFromEuler(angles, "XYZ");
Vector3 pos=GWTThreeUtils.toPositionVec(ab.getBoneAngleAndMatrix(index).getMatrix());
//log("pos:"+ThreeLog.get(pos));
Matrix4 posMx=GWTThreeUtils.translateToMatrix4(pos);
Matrix4 rotMx=GWTThreeUtils.rotationToMatrix4(angles);
rotMx.multiply(posMx,rotMx);
//log("bone-pos:"+ThreeLog.get(bones.get(index).getPos()));
ab.getBoneAngleAndMatrix(index).setMatrix(rotMx);
ab.getBoneAngleAndMatrix(index).setAngle(degAngles);
log("set angle:"+ThreeLog.get(degAngles));
doPoseByMatrix(ab);
}
private void updateBoneRanges(){
updateBoneRotationRanges();
updateBonePositionRanges();
}
private void updateBoneRotationRanges(){
if(isSelectEmptyBoneListBox()){
setEnableBoneRanges(false,false);//no root
return;
}
String name=boneNamesBox.getItemText(boneNamesBox.getSelectedIndex());
if(ikLocks.contains(name)){
ikLockCheck.setValue(true);
}else{
ikLockCheck.setValue(false);
}
int boneIndex=ab.getBoneIndex(name);
if(boneIndex!=0){//only root has position
rotateAndPosList.setSelectedIndex(0);
switchRotateAndPosList();
}
//Quaternion q=GWTThreeUtils.jsArrayToQuaternion(bones.get(boneIndex).getRotq());
//log("bone:"+ThreeLog.get(GWTThreeUtils.radiantToDegree(GWTThreeUtils.rotationToVector3(q))));
Vector3 mAngles=GWTThreeUtils.toDegreeAngle(ab.getBoneAngleAndMatrix(name).getMatrix());
//log("updateBoneRotationRanges():"+ThreeLog.get(mAngles));
Vector3 angles=ab.getBoneAngleAndMatrix(name).getAngle();
int x=(int) angles.getX();
rotationBoneXRange.setValue(x);
if(boneLock.hasX(name)){
xlockCheck.setValue(true);
rotationBoneXRange.setEnabled(false);
}else{
xlockCheck.setValue(false);
rotationBoneXRange.setEnabled(true);
}
int y=(int) angles.getY();
rotationBoneYRange.setValue(y);
if(boneLock.hasY(name)){
ylockCheck.setValue(true);
rotationBoneYRange.setEnabled(false);
}else{
ylockCheck.setValue(false);
rotationBoneYRange.setEnabled(true);
}
int z=(int) angles.getZ();
rotationBoneZRange.setValue(z);
if(boneLock.hasZ(name)){
zlockCheck.setValue(true);
rotationBoneZRange.setEnabled(false);
}else{
zlockCheck.setValue(false);
rotationBoneZRange.setEnabled(true);
}
}
private boolean isSelectEmptyBoneListBox(){
return boneNamesBox.getSelectedIndex()==-1 || boneNamesBox.getItemText(boneNamesBox.getSelectedIndex()).isEmpty();
}
private void updateBonePositionRanges(){
if(isSelectEmptyBoneListBox()){
return;
}
String name=boneNamesBox.getItemText(boneNamesBox.getSelectedIndex());
Vector3 values=GWTThreeUtils.toPositionVec(ab.getBoneAngleAndMatrix(name).getMatrix());
values.multiplyScalar(10);
int x=(int) values.getX();
positionXBoneRange.setValue(x);
int y=(int) values.getY();
positionYBoneRange.setValue(y);
int z=(int) values.getZ();
positionZBoneRange.setValue(z);
}
private Material bodyMaterial;
private String textureUrl="female001_texture1.jpg";//default
private Texture texture;
protected void updateMaterial() {
Material material=null;
boolean transparent=transparentCheck.getValue();
double opacity=1;
if(transparent){
opacity=0.75;
}
if(texture==null){//some case happend
material=THREE.MeshBasicMaterial().transparent(transparent).opacity(opacity).build();
//only initial happend
}else{
if(basicMaterialCheck.getValue()){
material=THREE.MeshBasicMaterial().map(texture).transparent(transparent).opacity(opacity).build();
}else{
material=THREE.MeshLambertMaterial().map(texture).transparent(transparent).opacity(opacity).build();
}
}
bodyMaterial=material;
if(bodyMesh!=null){
bodyMesh.setMaterial(material);
}
}
//TODO use for load bvh
private void loadBVH(String path){
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(path));
try {
builder.sendRequest(null, new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
String bvhText=response.getText();
parseInitialBVHAndLoadModels(bvhText);
}
@Override
public void onError(Request request, Throwable exception) {
Window.alert("load faild:");
}
});
} catch (RequestException e) {
log(e.getMessage());
e.printStackTrace();
}
}
private Geometry baseGeometry;
private List<String> boneList=new ArrayList<String>();
protected void parseInitialBVHAndLoadModels(String bvhText) {
final BVHParser parser=new BVHParser();
parser.parseAsync(bvhText, new ParserListener() {
@Override
public void onFaild(String message) {
log(message);
}
@Override
public void onSuccess(BVH bv) {
bvh=bv;
//createBonesFromBVH
AnimationBoneConverter converter=new AnimationBoneConverter();
setBone(converter.convertJsonBone(bvh));
if(preferencePanel!=null){
preferencePanel.loadSelectionModel();
preferencePanel.loadSelectionTexture();
}
//frameRange.setMax(animationData.getHierarchy().get(0).getKeys().length());
/*
JSONLoader loader=THREE.JSONLoader();
loader.load("men3menb.js", new LoadHandler() {
@Override
public void loaded(Geometry geometry) {
baseGeometry=geometry;
//doPose(0);
doPose(0);//bug i have no idea,need call twice to better initial pose
initialPoseFrameData=snapCurrentFrameData();
doNewFile();
//insertFrame(getSelectedPoseEditorData().getPoseFrameDatas().size(),false);//initial pose-frame
}
});
*/
}
});
}
private void setBone(JsArray<AnimationBone> bo){
bones=bo;
AnimationDataConverter dataConverter=new AnimationDataConverter();
dataConverter.setSkipFirst(false);
animationData = dataConverter.convertJsonAnimation(bones,bvh);//use for first pose
boneList.clear();
for(int i=0;i<bones.length();i++){
boneList.add(bones.get(i).getName());
//log(bones.get(i).getName()+","+ThreeLog.get(GWTThreeUtils.jsArrayToVector3(bones.get(i).getPos())));
}
}
public static class MatrixAndVector3{
public MatrixAndVector3(){}
private Vector3 position;
public Vector3 getPosition() {
return position;
}
public void setPosition(Vector3 position) {
this.position = position;
}
private Vector3 absolutePosition;
public Vector3 getAbsolutePosition() {
return absolutePosition;
}
public void setAbsolutePosition(Vector3 absolutePosition) {
this.absolutePosition = absolutePosition;
}
public Matrix4 getMatrix() {
return matrix;
}
public void setMatrix(Matrix4 matrix) {
this.matrix = matrix;
}
private Matrix4 matrix;
}
private List<MatrixAndVector3> boneMatrix;
/*
private Vector3 calculateBonedPos(Vector3 pos,AnimationBone bone,int animationIndex){
}
*/
public static List<MatrixAndVector3> boneToBoneMatrix(JsArray<AnimationBone> bones,AnimationData animationData,int index){
List<MatrixAndVector3> boneMatrix=new ArrayList<MatrixAndVector3>();
//analyze bone matrix
for(int i=0;i<bones.length();i++){
AnimationBone bone=bones.get(i);
AnimationHierarchyItem item=animationData.getHierarchy().get(i);
AnimationKey motion=item.getKeys().get(index);
//log(bone.getName());
Matrix4 mx=THREE.Matrix4();
Vector3 motionPos=GWTThreeUtils.jsArrayToVector3(motion.getPos());
//seems same as bone
// LogUtils.log(motionPos);
mx.setPosition(motionPos);
mx.setRotationFromQuaternion(GWTThreeUtils.jsArrayToQuaternion(motion.getRot()));
/*
Matrix4 mx2=THREE.Matrix4();
mx2.setRotationFromQuaternion(motion.getRot());
mx.multiplySelf(mx2);
*/
/*
Vector3 tmpRot=THREE.Vector3();
tmpRot.setRotationFromMatrix(mx);
Vector3 tmpPos=THREE.Vector3();
tmpPos.setPositionFromMatrix(mx);
*/
//LogUtils.log(tmpPos.getX()+","+tmpPos.getY()+","+tmpPos.getZ());
//LogUtils.log(Math.toDegrees(tmpRot.))
MatrixAndVector3 mv=new MatrixAndVector3();
Vector3 bpos=AnimationBone.jsArrayToVector3(bone.getPos());
mv.setPosition(bpos);//not effected self matrix
mv.setMatrix(mx);
if(bone.getParent()!=-1){
MatrixAndVector3 parentMv=boneMatrix.get(bone.getParent());
Vector3 apos=bpos.clone();
apos.addSelf(parentMv.getAbsolutePosition());
mv.setAbsolutePosition(apos);
}else{
//root
mv.setAbsolutePosition(bpos.clone());
}
boneMatrix.add(mv);
}
return boneMatrix;
}
private List<List<Integer>> bonePath;
public static List<List<Integer>> boneToPath(JsArray<AnimationBone> bones){
List<List<Integer>> data=new ArrayList<List<Integer>>();
for(int i=0;i<bones.length();i++){
List<Integer> path=new ArrayList<Integer>();
AnimationBone bone=bones.get(i);
path.add(i);
data.add(path);
while(bone.getParent()!=-1){
//path.add(bone.getParent());
path.add(0,bone.getParent());
bone=bones.get(bone.getParent());
}
}
return data;
}
private JsArray<Vector4> bodyIndices;
private JsArray<Vector4> bodyWeight;
Mesh bodyMesh;
Object3D root;
Object3D bone3D;
private CheckBox transparentCheck;
private CheckBox basicMaterialCheck;
/**
* called after load
* @param index
*/
/*
* trying to fix leg problem
Vector3 rootOffset=GWTThreeUtils.jsArrayToVector3(animationData.getHierarchy().get(0).getKeys().get(index).getPos());
//initial pose is base for motions
baseGeometry=GeometryUtils.clone(bodyMesh.getGeometry());
for(int i=0;i<baseGeometry.vertices().length();i++){
Vertex vertex=baseGeometry.vertices().get(i);
vertex.getPosition().subSelf(rootOffset);
}
*/
//for after loading
private void doRePose(int index){
//initializeBodyMesh();
initializeAnimationData(index,true);
//stepCDDIk();
doPoseByMatrix(ab);
updateBoneRanges();
log("update-bone-range");
}
AnimationBonesData ab;
List<AngleAndPosition> baseMatrixs;
private void applyMatrix(List<AngleAndPosition> matrix,List<NameAndVector3> samples){
for(NameAndVector3 nv:samples){
int boneIndex=ab.getBoneIndex(nv.getName());
Matrix4 translates=GWTThreeUtils.translateToMatrix4(GWTThreeUtils.toPositionVec(ab.getBoneAngleAndMatrix(boneIndex).getMatrix()));
Matrix4 newMatrix=GWTThreeUtils.rotationToMatrix4(nv.getVector3());
newMatrix.multiply(translates,newMatrix);
//log("apply-matrix");
matrix.get(boneIndex).setAngle(GWTThreeUtils.radiantToDegree(nv.getVector3()));
matrix.get(boneIndex).setMatrix(newMatrix);
}
}
List<List<AngleAndPosition>> candiateAngleAndMatrixs;
/*
private void initializeBodyMesh(){
//initializeBodyMesh
if(bodyMesh==null){//initial Indices & weight,be careful bodyMesh create in doPoseByMatrix
bodyIndices = (JsArray<Vector4>) JsArray.createArray();
bodyWeight = (JsArray<Vector4>) JsArray.createArray();
//geometry initialized 0 indices & weights
if(baseGeometry.getSkinIndices().length()!=0 && baseGeometry.getSkinWeight().length()!=0){
log("auto-weight from geometry:");
WeightBuilder.autoWeight(baseGeometry, bones, WeightBuilder.MODE_FROM_GEOMETRY, bodyIndices, bodyWeight);
}else{
//WeightBuilder.autoWeight(baseGeometry, bones, WeightBuilder.MODE_NearParentAndChildren, bodyIndices, bodyWeight);
WeightBuilder.autoWeight(baseGeometry, bones, WeightBuilder.MODE_NearParentAndChildren, bodyIndices, bodyWeight);
}
//WeightBuilder.autoWeight(baseGeometry, bones, WeightBuilder.MODE_NearAgressive, bodyIndices, bodyWeight);
log("initialized-weight:"+bodyIndices.length());
for(int i=0;i<bodyIndices.length();i++){
log(bodyIndices.get(i).getX()+" x "+bodyIndices.get(i).getY());
}
}else{
root.remove(bodyMesh);
}
}
*/
List<AngleAndPosition> currentMatrixs;
private void initializeAnimationData(int index,boolean resetMatrix){
//initialize AnimationBone
if(ab==null){
baseMatrixs=AnimationBonesData.boneToAngleAndMatrix(bones, animationData, index);
ab=new AnimationBonesData(bones,AnimationBonesData.cloneAngleAndMatrix(baseMatrixs) );
currentMatrixs=null;
for(int i=0;i<bones.length();i++){
// log(bones.get(i).getName()+":"+ThreeLog.get(baseMatrixs.get(i).getPosition()));
}
}
//TODO make automatic
//this is find base matrix ,because sometime cdd-ik faild from some position
//nearMatrix=new ArrayList<List<Matrix4>>();
//nearMatrix.add(AnimationBonesData.cloneMatrix(baseMatrixs));
/*
* for foot
List<NameAndVector3> sample=new ArrayList<NameAndVector3>();
sample.add(new NameAndVector3("RightLeg", GWTThreeUtils.degreeToRagiant(THREE.Vector3(90, 0, 0)), 0));
sample.add(new NameAndVector3("RightUpLeg", GWTThreeUtils.degreeToRagiant(THREE.Vector3(-90, 0, 0)), 0));
List<Matrix4> bm=AnimationBonesData.cloneMatrix(baseMatrixs);
applyMatrix(bm, sample);
nearMatrix.add(bm);
List<NameAndVector3> sample1=new ArrayList<NameAndVector3>();
sample1.add(new NameAndVector3("RightLeg", GWTThreeUtils.degreeToRagiant(THREE.Vector3(0, 0, 0)), 0));
sample1.add(new NameAndVector3("RightUpLeg", GWTThreeUtils.degreeToRagiant(THREE.Vector3(0, 0, 45)), 0));
List<Matrix4> bm1=AnimationBonesData.cloneMatrix(baseMatrixs);
applyMatrix(bm1, sample);
//ab.setBonesMatrixs(findStartMatrix("RightFoot",getCurrentIkData().getTargetPos()));//
*/
if(currentMatrixs!=null && resetMatrix){
if(candiateAngleAndMatrixs!=null){
//need bone limit
ab.setBonesAngleAndMatrixs(AnimationBonesData.cloneAngleAndMatrix(findStartMatrix(getCurrentIkData().getLastBoneName(),getCurrentIkData().getTargetPos())));
}else{
ab.setBonesAngleAndMatrixs(AnimationBonesData.cloneAngleAndMatrix(currentMatrixs));
}
//TODO only need?
}else{
}
}
private BoneLockControler boneLock=new BoneLockControler();
//this new position base ikk faild
private Vector3 findNextStep(int boneIndex,int lastBoneIndex,Vector3 targetPos){
Vector3 lastTrans=ab.getMatrixPosition(lastBoneIndex);
List<Integer> path=ab.getBonePath(lastBoneIndex);
Matrix4 matrix=THREE.Matrix4();
for(int i=0;i<path.size()-1;i++){
int bindex=path.get(i);
AngleAndPosition am=ab.getBoneAngleAndMatrix(bindex);
matrix.multiplySelf(am.getMatrix());
}
Vector3 base=THREE.Vector3(0,0,0);
Vector3 pos=matrix.multiplyVector3(lastTrans.clone());
double length=pos.subSelf(targetPos).length();
//log("length:"+length+","+0+"x"+0+"x"+0);
Vector3 tmpVec=THREE.Vector3();
for(int x=-1;x<=1;x++){
for(int y=-1;y<=1;y++){
for(int z=-1;z<=1;z++){
if(x==0 && y==0 && z==0){
continue;
}
tmpVec.set(x*5, y*5, z*5);
matrix=THREE.Matrix4();
for(int i=0;i<path.size()-1;i++){
int bindex=path.get(i);
AngleAndPosition am=ab.getBoneAngleAndMatrix(bindex);
Matrix4 m=am.getMatrix();
if(bindex==boneIndex){
Vector3 newAngle=am.getAngle().clone().addSelf(tmpVec);
Vector3 pv=GWTThreeUtils.toPositionVec(m);
m=THREE.Matrix4();
m.setPosition(pv);
m.setRotationFromEuler(newAngle, "XYZ");
}
matrix.multiplySelf(m);
}
pos=matrix.multiplyVector3(lastTrans.clone());
double tmpl=pos.subSelf(targetPos).length();
//log("length:"+tmpl+","+x+"x"+y+"x"+z);
if(tmpl<length){
base.set(x*5,y*5,z*5);
length=tmpl;
}
}
}
}
//log("mutch:"+ThreeLog.get(base));
return base.addSelf(ab.getBoneAngleAndMatrix(boneIndex).getAngle());
}
private boolean doLimit=true;
private boolean ignorePerLimit=false;
private void stepCDDIk(int perLimit,IKData ikData,int cddLoop){
//do CDDIK
//doCDDIk();
Vector3 tmp1=null,tmp2=null;
currentIkJointIndex=0;
List<AngleAndPosition> minMatrix=AnimationBonesData.cloneAngleAndMatrix(ab.getBonesAngleAndMatrixs());
double minLength=ab.getBonePosition(ikData.getLastBoneName()).clone().subSelf(ikData.getTargetPos()).length();
for(int i=0;i<ikData.getIteration()*cddLoop;i++){
String targetBoneName=ikData.getBones().get(currentIkJointIndex);
if(ikLocks.contains(targetBoneName)){
currentIkJointIndex++;
if(currentIkJointIndex>=ikData.getBones().size()){
currentIkJointIndex=0;
}
continue;
}
int boneIndex=ab.getBoneIndex(targetBoneName);
Vector3 ikkedAngle=null;
Matrix4 jointRot=ab.getBoneAngleAndMatrix(targetBoneName).getMatrix();
Matrix4 translates=GWTThreeUtils.translateToMatrix4(GWTThreeUtils.toPositionVec(jointRot));
Vector3 currentAngle=ab.getBoneAngleAndMatrix(targetBoneName).getAngle().clone();
//log("current:"+ThreeLog.get(currentAngle));
String beforeAngleLog="";
if(perLimit>0){
Vector3 lastJointPos=ab.getBonePosition(ikData.getLastBoneName());
//Vector3 jointPos=ab.getParentPosition(targetName);
Vector3 jointPos=ab.getBonePosition(targetBoneName);
//Vector3 beforeAngles=GWTThreeUtils.radiantToDegree(GWTThreeUtils.rotationToVector3(jointRot));
Vector3 beforeAngle=ab.getBoneAngleAndMatrix(targetBoneName).getAngle().clone();
//Matrix4 newMatrix=cddIk.doStep(lastJointPos, jointPos, jointRot, ikData.getTargetPos());
//TODO add parent bone angles
AngleAndPosition root=ab.getBoneAngleAndMatrix(0);
Vector3 parentAngle=ab.getParentAngles(boneIndex);
Matrix4 newMatrix=cddIk.getStepAngleMatrix(parentAngle,lastJointPos, jointPos, jointRot, ikData.getTargetPos());
beforeAngleLog=targetBoneName+","+"parent:"+ThreeLog.get(parentAngle)+",joint:"+ThreeLog.get(currentAngle);
if(newMatrix==null){//invalid value
log("null matrix");
continue;
}
//limit per angles
/*
* if angle value over 90 usually value is invalid.
* but i dont know how to detect or fix it.
*/
ikkedAngle=GWTThreeUtils.rotationToVector3(newMatrix);
//Vector3 diffAngles=GWTThreeUtils.radiantToDegree(ikkedAngle).subSelf(currentAngle);
Vector3 diffAngles=GWTThreeUtils.radiantToDegree(ikkedAngle);
if(perLimit==1){
//diffAngles.normalize();
}
//diffAngles.normalize().addScalar(perLimit);//miss choice
//log("diff:"+ThreeLog.get(diffAngles));
if(!ignorePerLimit){
if(Math.abs(diffAngles.getX())>perLimit){
double diff=perLimit;
if(diffAngles.getX()<0){
diff*=-1;
}
diffAngles.setX(diff);
}
if(Math.abs(diffAngles.getY())>perLimit){
double diff=perLimit;
if(diffAngles.getY()<0){
diff*=-1;
}
diffAngles.setY(diff);
}
if(Math.abs(diffAngles.getZ())>perLimit){
double diff=perLimit;
if(diffAngles.getZ()<0){
diff*=-1;
}
diffAngles.setZ(diff);
}
}
currentAngle.addSelf(diffAngles);
//log("added:"+ThreeLog.get(currentAngle));
//currentAngle.setX(0);//keep x
ikkedAngle=GWTThreeUtils.degreeToRagiant(currentAngle);
}else{
//faild TODO fix it
Vector3 angle=findNextStep(boneIndex, ab.getBoneIndex(ikData.getLastBoneName()), ikData.getTargetPos());
//log(targetBoneName+" before:"+ThreeLog.get(ab.getBoneAngleAndMatrix(boneIndex).getAngle())+" after:"+ThreeLog.get(angle));
ikkedAngle=GWTThreeUtils.degreeToRagiant(angle);
}
//log("before:"+ThreeLog.get(beforeAngle)+" after:"+ThreeLog.get(currentAngle));
//limit max
BoneLimit blimit=boneLimits.get(targetBoneName);
//log(targetBoneName);
//log("before-limit:"+ThreeLog.get(GWTThreeUtils.radiantToDegree(angles)));
if(blimit!=null && doLimit){
blimit.apply(ikkedAngle);
}
//invalid ignore
if("NaN".equals(""+ikkedAngle.getX())){
continue;
}
if("NaN".equals(""+ikkedAngle.getY())){
continue;
}
if("NaN".equals(""+ikkedAngle.getZ())){
continue;
}
if(boneLock.hasX(targetBoneName)){
ikkedAngle.setX(Math.toRadians(boneLock.getX(targetBoneName)));
}
if(boneLock.hasY(targetBoneName)){
ikkedAngle.setY(Math.toRadians(boneLock.getY(targetBoneName)));
}
if(boneLock.hasZ(targetBoneName)){
ikkedAngle.setZ(Math.toRadians(boneLock.getZ(targetBoneName)));
}
String afterAngleLog=("after-limit:"+ThreeLog.get(GWTThreeUtils.radiantToDegree(ikkedAngle)));
Matrix4 newMatrix=GWTThreeUtils.rotationToMatrix4(ikkedAngle);
newMatrix.multiply(translates,newMatrix);
ab.getBoneAngleAndMatrix(boneIndex).setMatrix(newMatrix);
ab.getBoneAngleAndMatrix(boneIndex).setAngle(GWTThreeUtils.radiantToDegree(ikkedAngle));
//log(targetName+":"+ThreeLog.getAngle(jointRot)+",new"+ThreeLog.getAngle(newMatrix));
//log("parentPos,"+ThreeLog.get(jointPos)+",lastPos,"+ThreeLog.get(lastJointPos));
Vector3 diffPos=ab.getBonePosition(ikData.getLastBoneName()).clone().subSelf(ikData.getTargetPos());
/*
if(diffPos.length()>2){
//usually ivalid
log(i+","+"length="+diffPos.length()+" diff:"+ThreeLog.get(diffPos));
log(beforeAngleLog);
log(afterAngleLog);
}*/
if(diffPos.length()<minLength){
minMatrix=AnimationBonesData.cloneAngleAndMatrix(ab.getBonesAngleAndMatrixs());
}
currentIkJointIndex++;
if(currentIkJointIndex>=ikData.getBones().size()){
currentIkJointIndex=0;
}
if(diffPos.length()<0.02){
break;
}
//tmp1=lastJointPos;
//tmp2=jointPos;
}
ab.setBonesAngleAndMatrixs(minMatrix);//use min
}
private void doPoseIkk(int index,boolean resetMatrix,int perLimit,IKData ikdata,int cddLoop){
//initializeBodyMesh();
initializeAnimationData(index,resetMatrix);
stepCDDIk(perLimit,ikdata,cddLoop);
doPoseByMatrix(ab);
updateBoneRanges();
}
private List<AngleAndPosition> findStartMatrix(String boneName,Vector3 targetPos) {
List<AngleAndPosition> retMatrix=candiateAngleAndMatrixs.get(0);
ab.setBonesAngleAndMatrixs(retMatrix);//TODO without set
Vector3 tpos=ab.getBonePosition(boneName);
double minlength=targetPos.clone().subSelf(tpos).length();
for(int i=1;i<candiateAngleAndMatrixs.size();i++){
List<AngleAndPosition> mxs=candiateAngleAndMatrixs.get(i);
ab.setBonesAngleAndMatrixs(mxs);//TODO change
Vector3 tmpPos=ab.getBonePosition(boneName);
double tmpLength=targetPos.clone().subSelf(tmpPos).length();
if(tmpLength<minlength){
minlength=tmpLength;
retMatrix=mxs;
}
}
for(String name:getCurrentIkData().getBones()){
//Matrix4 mx=retMatrix.get(ab.getBoneIndex(name));
// log(name+":"+ThreeLog.get(GWTThreeUtils.rotationToVector3(mx)));
// log(name+":"+ThreeLog.get(GWTThreeUtils.toDegreeAngle(mx)));
}
return retMatrix;
}
/*
private void doCDDIk(){
String targetName=getCurrentIkData().getBones().get(currentIkJointIndex);
int boneIndex=ab.getBoneIndex(targetName);
Vector3 lastJointPos=ab.getPosition("RightFoot");
Vector3 jointPos=ab.getParentPosition(targetName);
Matrix4 jointRot=ab.getBoneMatrix(targetName);
Matrix4 newMatrix=cddIk.doStep(lastJointPos, jointPos, jointRot, getCurrentIkData().getTargetPos());
ab.setBoneMatrix(boneIndex, newMatrix);
//log(targetName+":"+ThreeLog.getAngle(jointRot)+",new"+ThreeLog.getAngle(newMatrix));
//log("parentPos,"+ThreeLog.get(jointPos)+",lastPos,"+ThreeLog.get(lastJointPos));
currentIkJointIndex++;
if(currentIkJointIndex>=getCurrentIkData().getBones().size()){
currentIkJointIndex=0;
}
doPoseByMatrix(ab);
}
*/
CDDIK cddIk=new CDDIK();
int currentIkJointIndex=0;
//private String[] ikTestNames={"RightLeg","RightUpLeg"};
//Vector3 targetPos=THREE.Vector3(-10, -3, 0);
private ListBox boneNamesBox;
private void doPoseByMatrix(AnimationBonesData animationBonesData){
if(isSelectedBone()){
selectionMesh.setPosition(ab.getBoneAngleAndMatrix(selectedBone).getPosition());
}
List<AngleAndPosition> boneMatrix=animationBonesData.getBonesAngleAndMatrixs();
bonePath=boneToPath(bones);
if(bone3D!=null){
root.remove(bone3D);
}
bone3D=THREE.Object3D();
root.add(bone3D);
//selection
//test ikk
/*
Mesh cddIk0=THREE.Mesh(THREE.CubeGeometry(1.5, 1.5, 1.5),THREE.MeshLambertMaterial().color(0x00ff00).build());
cddIk0.setPosition(getCurrentIkData().getTargetPos());
bone3D.add(cddIk0);
*/
List<Matrix4> moveMatrix=new ArrayList<Matrix4>();
List<Vector3> bonePositions=new ArrayList<Vector3>();
for(int i=0;i<bones.length();i++){
Matrix4 mv=boneMatrix.get(i).getMatrix();
double bsize=.7;
if(i==0){
bsize=1.5;
}
Mesh mesh=THREE.Mesh(THREE.CubeGeometry(bsize,bsize, bsize),THREE.MeshLambertMaterial().color(0xff0000).build());
bone3D.add(mesh);
Vector3 pos=THREE.Vector3();
pos.setPositionFromMatrix(boneMatrix.get(i).getMatrix());
//Vector3 rot=GWTThreeUtils.rotationToVector3(GWTThreeUtils.jsArrayToQuaternion(bones.get(i).getRotq()));
Vector3 rot=GWTThreeUtils.degreeToRagiant(ab.getBoneAngleAndMatrix(i).getAngle());
List<Integer> path=bonePath.get(i);
String boneName=bones.get(i).getName();
//log(boneName);
mesh.setName(boneName);
Matrix4 matrix=THREE.Matrix4();
for(int j=0;j<path.size()-1;j++){//last is boneself
// log(""+path.get(j));
Matrix4 mx=boneMatrix.get(path.get(j)).getMatrix();
matrix.multiply(matrix, mx);
}
matrix.multiplyVector3(pos);
matrix.multiply(matrix, boneMatrix.get(path.get(path.size()-1)).getMatrix());//last one
moveMatrix.add(matrix);
if(bones.get(i).getParent()!=-1){
Vector3 ppos=bonePositions.get(bones.get(i).getParent());
//pos.addSelf(ppos);
//log(boneName+":"+ThreeLog.get(pos)+","+ThreeLog.get(ppos));
Mesh line=GWTGeometryUtils.createLineMesh(pos, ppos, 0xffffff);
bone3D.add(line);
//cylinder
/* better bone faild
Vector3 halfPos=pos.clone().subSelf(ppos).multiplyScalar(0.5).addSelf(ppos);
Mesh boneMesh=THREE.Mesh(THREE.CylinderGeometry(.1,.1,.2,6), THREE.MeshLambertMaterial().color(0xffffff).build());
boneMesh.setPosition(halfPos);
boneMesh.setName(boneName);
bone3D.add(boneMesh);
BoxData data=boxDatas.get(boneName);
if(data!=null){
boneMesh.setScale(data.getScaleX(), data.getScaleY(), data.getScaleZ());
boneMesh.getRotation().setZ(Math.toRadians(data.getRotateZ()));
}
*/
for(IKData ik:ikdatas){
if(ik.getLastBoneName().equals(boneName)){//valid ik
Mesh ikMesh=targetMeshs.get(boneName);
if(ikMesh==null){//at first call this from non-ik stepped.
//log("xxx");
//initial
Vector3 ikpos=pos.clone().subSelf(ppos).multiplyScalar(1.5).addSelf(ppos);
//ikpos=pos.clone();
ikMesh=THREE.Mesh(THREE.CubeGeometry(1.5, 1.5, 1.5),THREE.MeshLambertMaterial().color(0x00ff00).build());
ikMesh.setPosition(ikpos);
ikMesh.setName("ik:"+boneName);
// log(boneName+":"+ThreeLog.get(ikpos));
//log(ThreeLog.get(pos));
ik.getTargetPos().set(ikpos.getX(), ikpos.getY(), ikpos.getZ());
targetMeshs.put(boneName, ikMesh);
}else{
ikMesh.getParent().remove(ikMesh);
}
bone3D.add(ikMesh);
ikMesh.setPosition(ik.getTargetPos());
Mesh ikline=GWTGeometryUtils.createLineMesh(pos, ik.getTargetPos(), 0xffffff);
bone3D.add(ikline);
}
}
}
mesh.setRotation(rot);
mesh.setPosition(pos);
//mesh color
if(pos.getY()<0){
mesh.getMaterial().setColor(THREE.Color(0xffee00));//over color
}else if(pos.getY()<1){
mesh.getMaterial().setColor(THREE.Color(0xff8800));//over color
}
bonePositions.add(pos);
}
//dont work
Object3DUtils.setVisibleAll(bone3D, showBonesCheck.getValue());
//bone3D.setVisible(showBonesCheck.getValue());
//Geometry geo=GeometryUtils.clone(baseGeometry);
//initialize AutoWeight
if(bodyMesh==null){//initial
bodyIndices = (JsArray<Vector4>) JsArray.createArray();
bodyWeight = (JsArray<Vector4>) JsArray.createArray();
//geometry initialized 0 indices & weights
if(baseGeometry.getSkinIndices().length()!=0 && baseGeometry.getSkinWeight().length()!=0){
log("auto-weight from geometry:");
WeightBuilder.autoWeight(baseGeometry, bones, WeightBuilder.MODE_FROM_GEOMETRY, bodyIndices, bodyWeight);
}else{
WeightBuilder.autoWeight(baseGeometry, bones, WeightBuilder.MODE_NearParentAndChildren, bodyIndices, bodyWeight);
}
}else{
root.remove(bodyMesh);
}
//Geometry geo=bodyMesh.getGeometry();
Geometry geo=GeometryUtils.clone(baseGeometry);
//log("bi-length:"+bodyIndices.length());
for(int i=0;i<baseGeometry.vertices().length();i++){
Vertex baseVertex=baseGeometry.vertices().get(i);
Vector3 vertexPosition=baseVertex.getPosition().clone();
Vertex targetVertex=geo.vertices().get(i);
int boneIndex1=(int) bodyIndices.get(i).getX();
int boneIndex2=(int) bodyIndices.get(i).getY();
String name=animationBonesData.getBoneName(boneIndex1);
//log(boneIndex1+"x"+boneIndex2);
/*
*
if(name.equals("RightLeg")){//test parent base
Vector3 parentPos=animationBonesData.getBaseParentBonePosition(boneIndex1);
Matrix4 tmpMatrix=GWTThreeUtils.rotationToMatrix4(GWTThreeUtils.degreeToRagiant(THREE.Vector3(0, 0, 20)));
vertexPosition.subSelf(parentPos);
tmpMatrix.multiplyVector3(vertexPosition);
vertexPosition.addSelf(parentPos);
boneIndex2=boneIndex1; //dont work without this
}*/
Vector3 bonePos=animationBonesData.getBaseBonePosition(boneIndex1);
Vector3 relatePos=bonePos.clone();
relatePos.sub(vertexPosition,bonePos);
//double length=relatePos.length();
moveMatrix.get(boneIndex1).multiplyVector3(relatePos);
/*
if(name.equals("RightLeg")){
Vector3 parentPos=animationBonesData.getParentPosition(boneIndex1);
relatePos.subSelf(parentPos);
Matrix4 tmpMatrix2=GWTThreeUtils.rotationToMatrix4(GWTThreeUtils.degreeToRagiant(THREE.Vector3(0, 0, -20)));
tmpMatrix2.multiplyVector3(relatePos);
relatePos.addSelf(parentPos);
}*/
//relatePos.addSelf(bonePos);
if(boneIndex2!=boneIndex1){
Vector3 bonePos2=animationBonesData.getBaseBonePosition(boneIndex2);
Vector3 relatePos2=bonePos2.clone();
relatePos2.sub(baseVertex.getPosition(),bonePos2);
double length2=relatePos2.length();
moveMatrix.get(boneIndex2).multiplyVector3(relatePos2);
//scalar weight
relatePos.multiplyScalar(bodyWeight.get(i).getX());
relatePos2.multiplyScalar(bodyWeight.get(i).getY());
relatePos.addSelf(relatePos2);
//keep distance1 faild
/*
if(length<1){ //length2
Vector3 abpos=THREE.Vector3();
abpos.sub(relatePos, bonePositions.get(boneIndex1));
double scar=abpos.length()/length;
abpos.multiplyScalar(scar);
abpos.addSelf(bonePositions.get(boneIndex1));
relatePos.set(abpos.getX(), abpos.getY(), abpos.getZ());
}*/
if(length2<1){
Vector3 abpos=THREE.Vector3();
abpos.sub(relatePos, bonePositions.get(boneIndex2));
double scar=abpos.length()/length2;
abpos.multiplyScalar(scar);
abpos.addSelf(bonePositions.get(boneIndex2));
relatePos.set(abpos.getX(), abpos.getY(), abpos.getZ());
}
/*
Vector3 diff=THREE.Vector3();
diff.sub(relatePos2, relatePos);
diff.multiplyScalar(bodyWeight.get(i).getY());
relatePos.addSelf(diff);
*/
}else{
if(name.equals("RightLeg")){
// Matrix4 tmpMatrix2=GWTThreeUtils.rotationToMatrix4(GWTThreeUtils.degreeToRagiant(THREE.Vector3(0, 0, -20)));
// tmpMatrix2.multiplyVector3(relatePos);
}
}
targetVertex.getPosition().set(relatePos.getX(), relatePos.getY(), relatePos.getZ());
}
geo.computeFaceNormals();
geo.computeVertexNormals();
//Material material=THREE.MeshLambertMaterial().map(ImageUtils.loadTexture("men3smart_texture.png")).build();
bodyMesh=THREE.Mesh(geo, bodyMaterial);
root.add(bodyMesh);
//selection
//selectionMesh=THREE.Mesh(THREE.CubeGeometry(2, 2, 2), THREE.MeshBasicMaterial().color(0x00ff00).wireFrame(true).build());
if(isSelectedIk()){
selectionMesh.setPosition(getCurrentIkData().getTargetPos());
}
//bone3D.add(selectionMesh);
//selectionMesh.setVisible(false);
/*
geo.setDynamic(true);
geo.setDirtyVertices(true);
geo.computeBoundingSphere();
*/
//bodyMesh.setGeometry(geo);
//bodyMesh.gwtBoundingSphere();
//geo.computeTangents();
/*
geo.setDynamic(true);
geo.setDirtyVertices(true);
geo.computeFaceNormals();
geo.computeVertexNormals();
geo.computeTangents();
*/
}
private Map<String,Mesh> targetMeshs=new HashMap<String,Mesh>();
private ListBox rotateAndPosList;
private VerticalPanel bonePositionsPanel;
private VerticalPanel boneRotationsPanel;
private CheckBox zlockCheck;
private CheckBox ikLockCheck;
private ListBox fileNames;
private StorageControler storageControler;
private VerticalPanel datasPanel;
private Button saveButton;
private VerticalPanel bonePostionAndRotationContainer;
private MenuItem contextMenuShowPrevFrame;
private MenuItem contextMenuHidePrefIks;
;
/**
* @deprecated
*/
private void doPose(List<MatrixAndVector3> boneMatrix){
bonePath=boneToPath(bones);
if(bone3D!=null){
root.remove(bone3D);
}
bone3D=THREE.Object3D();
root.add(bone3D);
//test ikk
Mesh cddIk0=THREE.Mesh(THREE.CubeGeometry(.5, .5, .5),THREE.MeshLambertMaterial().color(0x00ff00).build());
cddIk0.setPosition(getCurrentIkData().getTargetPos());
bone3D.add(cddIk0);
List<Matrix4> moveMatrix=new ArrayList<Matrix4>();
List<Vector3> bonePositions=new ArrayList<Vector3>();
for(int i=0;i<bones.length();i++){
MatrixAndVector3 mv=boneMatrix.get(i);
Mesh mesh=THREE.Mesh(THREE.CubeGeometry(.2, .2, .2),THREE.MeshLambertMaterial().color(0xff0000).build());
bone3D.add(mesh);
Vector3 pos=mv.getPosition().clone();
List<Integer> path=bonePath.get(i);
String boneName=bones.get(i).getName();
//log(boneName);
Matrix4 tmpmx=boneMatrix.get(path.get(path.size()-1)).getMatrix();
Vector3 tmpp=THREE.Vector3();
tmpp.setPositionFromMatrix(tmpmx);
//log(pos.getX()+","+pos.getY()+","+pos.getZ()+":"+tmpp.getX()+","+tmpp.getY()+","+tmpp.getZ());
Matrix4 matrix=THREE.Matrix4();
for(int j=0;j<path.size()-1;j++){//last is boneself
// log(""+path.get(j));
Matrix4 mx=boneMatrix.get(path.get(j)).getMatrix();
matrix.multiply(matrix, mx);
}
matrix.multiplyVector3(pos);
matrix.multiply(matrix, boneMatrix.get(path.get(path.size()-1)).getMatrix());//last one
moveMatrix.add(matrix);
if(bones.get(i).getParent()!=-1){
Vector3 ppos=bonePositions.get(bones.get(i).getParent());
//pos.addSelf(ppos);
Mesh line=GWTGeometryUtils.createLineMesh(pos, ppos, 0xffffff);
bone3D.add(line);
}else{
//root action
Matrix4 mx=boneMatrix.get(0).getMatrix();
mx.multiplyVector3(pos);
}
mesh.setPosition(pos);
bonePositions.add(pos);
}
//Geometry geo=GeometryUtils.clone(baseGeometry);
//Geometry geo=bodyMesh.getGeometry();
Geometry geo=GeometryUtils.clone(baseGeometry);
for(int i=0;i<baseGeometry.vertices().length();i++){
Vertex baseVertex=baseGeometry.vertices().get(i);
Vertex targetVertex=geo.vertices().get(i);
int boneIndex1=(int) bodyIndices.get(i).getX();
int boneIndex2=(int) bodyIndices.get(i).getY();
Vector3 bonePos=boneMatrix.get(boneIndex1).getAbsolutePosition();
Vector3 relatePos=bonePos.clone();
relatePos.sub(baseVertex.getPosition(),bonePos);
double length=relatePos.length();
moveMatrix.get(boneIndex1).multiplyVector3(relatePos);
//relatePos.addSelf(bonePos);
if(boneIndex2!=boneIndex1){
Vector3 bonePos2=boneMatrix.get(boneIndex2).getAbsolutePosition();
Vector3 relatePos2=bonePos2.clone();
relatePos2.sub(baseVertex.getPosition(),bonePos2);
double length2=relatePos2.length();
moveMatrix.get(boneIndex2).multiplyVector3(relatePos2);
//scalar weight
relatePos.multiplyScalar(bodyWeight.get(i).getX());
relatePos2.multiplyScalar(bodyWeight.get(i).getY());
relatePos.addSelf(relatePos2);
//keep distance1 faild
/*
if(length<1){ //length2
Vector3 abpos=THREE.Vector3();
abpos.sub(relatePos, bonePositions.get(boneIndex1));
double scar=abpos.length()/length;
abpos.multiplyScalar(scar);
abpos.addSelf(bonePositions.get(boneIndex1));
relatePos.set(abpos.getX(), abpos.getY(), abpos.getZ());
}*/
if(length2<1){
Vector3 abpos=THREE.Vector3();
abpos.sub(relatePos, bonePositions.get(boneIndex2));
double scar=abpos.length()/length2;
abpos.multiplyScalar(scar);
abpos.addSelf(bonePositions.get(boneIndex2));
relatePos.set(abpos.getX(), abpos.getY(), abpos.getZ());
}
/*
Vector3 diff=THREE.Vector3();
diff.sub(relatePos2, relatePos);
diff.multiplyScalar(bodyWeight.get(i).getY());
relatePos.addSelf(diff);
*/
}
targetVertex.getPosition().set(relatePos.getX(), relatePos.getY(), relatePos.getZ());
}
geo.computeFaceNormals();
geo.computeVertexNormals();
//Material material=THREE.MeshLambertMaterial().map(ImageUtils.loadTexture("men3smart_texture.png")).build();
bodyMesh=THREE.Mesh(geo, bodyMaterial);
root.add(bodyMesh);
/*
geo.setDynamic(true);
geo.setDirtyVertices(true);
geo.computeBoundingSphere();
*/
//bodyMesh.setGeometry(geo);
//bodyMesh.gwtBoundingSphere();
//geo.computeTangents();
/*
geo.setDynamic(true);
geo.setDirtyVertices(true);
geo.computeFaceNormals();
geo.computeVertexNormals();
geo.computeTangents();
*/
}
@Override
public String getHtml(){
String html="Pose Editor ver."+version+" "+super.getHtml();
return html;
}
@Override
public String getTabTitle() {
return "Editor";
}
@Override
public void modelChanged(HeaderAndValue model) {
//log("model-load:"+model.getData());
LoadJsonModel(model.getData());
selectFrameData(currentFrameRange.getValue());//re pose
}
@Override
public void textureChanged(HeaderAndValue textureValue) {
textureUrl=textureValue.getData();
generateTexture();
}
private void generateTexture(){
final Image img=new Image(textureUrl);
img.setVisible(false);
RootPanel.get().add(img);
img.addLoadHandler(new com.google.gwt.event.dom.client.LoadHandler() {
@Override
public void onLoad(LoadEvent event) {
Canvas canvas=Canvas.createIfSupported();
canvas.setCoordinateSpaceWidth(img.getWidth());
canvas.setCoordinateSpaceHeight(img.getHeight());
canvas.getContext2d().drawImage(ImageElement.as(img.getElement()),0,0);
texture=THREE.Texture(canvas.getCanvasElement());
texture.setNeedsUpdate(true);
img.removeFromParent();
log("generate-texture");
updateMaterial();
}
});
}
}
|
package com.bitgrind.android;
import java.util.Arrays;
import jsqlite.Callback;
import jsqlite.Exception;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
public class SpatialiteTestActivity extends Activity {
private static final String TAG = SpatialiteTestActivity.class.getName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
jsqlite.Database db = new jsqlite.Database();
try {
db.open(Environment.getExternalStorageDirectory() + "/spatialite_test.db",
jsqlite.Constants.SQLITE_OPEN_READONLY);
Callback cb = new Callback() {
@Override
public void columns(String[] coldata) {
Log.v(TAG, "Columns: " + Arrays.toString(coldata));
}
@Override
public void types(String[] types) {
Log.v(TAG, "Types: " + Arrays.toString(types));
}
@Override
public boolean newrow(String[] rowdata) {
Log.v(TAG, "Row: " + Arrays.toString(rowdata));
// Careful (from parent javadoc):
// "If true is returned the running SQLite query is aborted."
return false;
}
};
db.exec("SELECT name, peoples, AsText(GaiaGeometry) from Towns where peoples > 350000 order by peoples DESC;", cb);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
/*
* A lightweight HTML editor for SWEN-262.
*
*
* @author aac6012
* @author thn1069
* @author jlt8213
* @author edf7470
*
* @version $Id:$
*/
package htmleditor;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.beans.property.ReadOnlyDoubleProperty;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.control.*;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.*;
import javafx.scene.Group;
import javafx.scene.layout.BorderPane;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextField;
import javafx.scene.control.TextArea;
import javafx.scene.paint.Paint;
import javafx.scene.text.Font;
import javafx.scene.control.SelectionModel;
import javafx.event.EventHandler;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkEvent.EventType;
/**
*
* @author trh8614
*/
public class HTMLEditor extends Application {
// Version of application
final int VERSION = 1;
final String BACKGROUND_STYLE_CSS = "-fx-background-color: linear-gradient(to bottom, rgb(98, 98, 98), rgb(45, 45, 45));";
final String STYLE_CSS = HTMLEditor.class.getResource("styles.css").toExternalForm();
final private KeyCombination CTRL_S = new KeyCodeCombination(KeyCode.S, KeyCombination.CONTROL_DOWN);
final private KeyCombination CTRL_X = new KeyCodeCombination(KeyCode.X, KeyCombination.CONTROL_DOWN);
final private KeyCombination CTRL_W = new KeyCodeCombination(KeyCode.W, KeyCombination.CONTROL_DOWN);
final private KeyCombination CTRL_O = new KeyCodeCombination(KeyCode.O, KeyCombination.CONTROL_DOWN);
private Stage stage;
private Group rootGroup;
private Scene scene;
private MenuBar menuBar;
private BorderPane canvas;
private TabPane tabPane;
private FileChooser fileChooser;
@Override
public void start(Stage primaryStage) {
this.stage = primaryStage;
this.rootGroup = new Group();
this.scene = new Scene(rootGroup, 800, 400, Color.DARKGREY);
this.menuBar = buildMenuBarWithMenus(primaryStage.widthProperty());
this.fileChooser = new FileChooser();
this.fileChooser.setTitle("Select an HTML file...");
this.canvas = new BorderPane();
this.tabPane = new TabPane();
if (this.tabPane.getTabs().size() == 0){
this.addNewTab();
this.tabPane.getSelectionModel().select(0);
this.tabPane.getSelectionModel().getSelectedItem().getContent().requestFocus();
}
this.canvas.setTop(this.menuBar);
this.canvas.setCenter(this.tabPane);
this.canvas.prefHeightProperty().bind(this.scene.heightProperty());
this.canvas.prefWidthProperty().bind(this.scene.widthProperty());
this.scene.getStylesheets().clear();
this.scene.getStylesheets().add(STYLE_CSS);
//rootGroup.getChildren().add(menuBar);
this.rootGroup.getChildren().add(this.canvas);
this.stage.setTitle("HTML Editor");
this.stage.setScene(this.scene);
this.stage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
private MenuBar buildMenuBarWithMenus(final ReadOnlyDoubleProperty menuWidthProperty){
final MenuBar menuBar = new MenuBar();
menuBar.setStyle(STYLE_CSS);
// Prepare left-most 'File' drop-down menu
final Menu fileMenu = new Menu("File");
fileMenu.setStyle("-fx-text-fill: white");
//New File item
MenuItem newItem = new MenuItem("New") ;
newItem.setMnemonicParsing(true);
newItem.setAccelerator(new KeyCodeCombination(KeyCode.N,KeyCombination.CONTROL_DOWN));
newItem.setOnAction(new MyEventHandler(new NewFileCommand(this)));
//Open File item
MenuItem openItem = new MenuItem("Open") ;
openItem.setMnemonicParsing(true);
openItem.setAccelerator(new KeyCodeCombination(KeyCode.O,KeyCombination.CONTROL_DOWN));
openItem.setOnAction(new MyEventHandler(new OpenFileCommand(this)));
//Save File item
MenuItem saveItem = new MenuItem("Save") ;
saveItem.setAccelerator(new KeyCodeCombination(KeyCode.S,KeyCombination.CONTROL_DOWN));
saveItem.setOnAction(new MyEventHandler(new SaveFileCommand(this)));
//SaveAs File item
MenuItem saveAsItem = new MenuItem("Save As...") ;
saveAsItem.setAccelerator(new KeyCodeCombination(KeyCode.S,KeyCombination.CONTROL_DOWN, KeyCombination.SHIFT_DOWN));
saveAsItem.setOnAction(new MyEventHandler(new SaveAsCommand(this)));
//Add all items to the left-most dropdown menu
fileMenu.getItems().add(newItem);
fileMenu.getItems().add(openItem);
fileMenu.getItems().add(saveItem);
fileMenu.getItems().add(saveAsItem);
// Seperator
fileMenu.getItems().add(new SeparatorMenuItem());
// Exit
MenuItem exitItem = new MenuItem("Exit", null);
exitItem.setMnemonicParsing(true);
exitItem.setAccelerator(new KeyCodeCombination(KeyCode.X,KeyCombination.CONTROL_DOWN));
exitItem.setOnAction(new MyEventHandler(new ExitCommand(this))) ;
fileMenu.getItems().add(exitItem);
menuBar.getMenus().add(fileMenu);
// Prepare 'Insert' drop-down menu
final Menu insertMenu = new Menu("Insert");
fileMenu.setStyle("-fx-text-fill: white");
//Bold item
MenuItem boldItem = new MenuItem("Bold") ;
boldItem.setAccelerator(new KeyCodeCombination(KeyCode.B,KeyCombination.CONTROL_DOWN));
boldItem.setOnAction(new MyEventHandler(new InsertCommand(this, Tag.BOLD)));
insertMenu.getItems().add(boldItem);
//Italics item
MenuItem italicsItem = new MenuItem("Italics") ;
italicsItem.setAccelerator(new KeyCodeCombination(KeyCode.I,KeyCombination.CONTROL_DOWN));
italicsItem.setOnAction(new MyEventHandler(new InsertCommand(this, Tag.ITALICS)));
insertMenu.getItems().add(italicsItem);
menuBar.getMenus().add(insertMenu);
// Prepare 'Options' drop-down menu
final Menu optionsMenu = new Menu("Options");
// Text Wrapping item
MenuItem textWrapItem = new MenuItem("Wrap Text (On/Off)");
textWrapItem.setOnAction(new MyEventHandler(new WrapTextSwitchCommand(this)));
optionsMenu.getItems().add(textWrapItem);
menuBar.getMenus().add(optionsMenu);
// Prepare 'Help' drop-down menu
final Menu helpMenu = new Menu("Help");
final MenuItem searchMenuItem = new MenuItem("Search");
searchMenuItem.setDisable(true);
helpMenu.getItems().add(searchMenuItem);
final MenuItem onlineManualMenuItem = new MenuItem("Online Manual");
onlineManualMenuItem.setVisible(false);
helpMenu.getItems().add(onlineManualMenuItem);
helpMenu.getItems().add(new SeparatorMenuItem());
final MenuItem aboutMenuItem =
MenuItemBuilder.create()
.text("About")
.onAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent e){ aboutApp(); }
})
.accelerator(
new KeyCodeCombination(
KeyCode.A, KeyCombination.CONTROL_DOWN))
.build();
helpMenu.getItems().add(aboutMenuItem);
menuBar.getMenus().add(helpMenu);
// bind width of menu bar to width of associated stage
menuBar.prefWidthProperty().bind(menuWidthProperty);
return menuBar;
}
public void addNewTab(){
Tab tab = new Tab();
/*
if (this.tabPane.getTabs().size() == 0){
tab.setId("0");
tab.setText("Untitled " + tab.getId());
}else{
int i = 0;
for (Tab t : this.tabPane.getTabs()){
if (Integer.parseInt(t.getId()) == i){
i += 1;
}
else if (Integer.parseInt(t.getId()) > i){
i -= 1;
//System.out.println(this.tabPane.getTabs());
tab.setId(Integer.toString(i));
tab.setText("Untitled " + Integer.toString(i));
}
else{
i += 1;
tab.setId(Integer.toString(i));
tab.setText("Untitled " + Integer.toString(i));
}
}
}
*/
tab.setText("Untitled");
TextArea ta = new TextArea();
ta.setWrapText(true);
ta.prefHeightProperty().bind(this.scene.heightProperty());
ta.prefWidthProperty().bind(this.scene.widthProperty());
ta.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>(){
public void handle(KeyEvent event){
if (CTRL_S.match(event)){
saveFile();
}else if (CTRL_W.match(event)){
closeCurrentTab();
}else if (CTRL_O.match(event)){
openFile();
}else if (CTRL_X.match(event)){
System.exit(0);
}
}
});
tab.setContent(ta);
/*
tab.setOnSelectionChanged(new EventHandler<Event>() {
@Override
public void handle(Event t) {
Tab currentTab = tabPane.getSelectionModel().getSelectedItem();
currentTab.getContent().requestFocus();
TextArea currentText = (TextArea)currentTab.getContent();
currentText.requestFocus();
System.out.println(currentTab.getContent());
}
});
*/
this.tabPane.getTabs().add(this.tabPane.getTabs().size(), tab);
this.tabPane.getSelectionModel().select(tab);
if (tab.isSelected()){
tab.getContent().requestFocus();
}
}
/* Returns text string currently in active buffer */
public String getBuffer(){
Tab thisTab = this.tabPane.getSelectionModel().getSelectedItem();
TextArea thisTA = (TextArea)thisTab.getContent();
return thisTA.getText();
}
/* Returns file name currently in active buffer */
public String getFileName(){
Tab thisTab = this.tabPane.getSelectionModel().getSelectedItem();
return thisTab.getText();
}
public TextArea getText(){
Tab thisTab = this.tabPane.getSelectionModel().getSelectedItem();
return (TextArea)thisTab.getContent();
}
public void closeCurrentTab(){
this.tabPane.getTabs().remove(this.tabPane.getSelectionModel().getSelectedItem());
}
public void openFile(){
File file = this.fileChooser.showOpenDialog(this.stage);
if (file != null){
TextArea ta;
Tab thisTab = this.tabPane.getSelectionModel().getSelectedItem();
if(getBuffer().trim().equals("")){
ta = (TextArea) this.tabPane.getSelectionModel().getSelectedItem().getContent();
ta.setText(this.readFile(file));
thisTab.setText(file.getName());
}
else{
Tab newTab = new Tab();
ta = new TextArea();
ta.setText(this.readFile(file));
newTab.setContent(ta);
newTab.setText(file.getName());
this.tabPane.getTabs().add(newTab);
this.tabPane.getSelectionModel().select(newTab);
}
}
}
private String readFile(File file){
StringBuilder stringBuffer = new StringBuilder();
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(file));
String text;
while ((text = bufferedReader.readLine()) != null) {
stringBuffer.append(text);
stringBuffer.append('\n');
}
} catch (FileNotFoundException ex) {
Logger.getLogger(HTMLEditor.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(HTMLEditor.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
bufferedReader.close();
} catch (IOException ex) {
Logger.getLogger(HTMLEditor.class.getName()).log(Level.SEVERE, null, ex);
}
}
return stringBuffer.toString();
}
public void saveAsChooser(){
String htmlText = getBuffer();
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Save HTML");
FileWriter fileWriter = null;
File file = fileChooser.showSaveDialog(stage);
if (file != null) {
try {
fileWriter = new FileWriter(file);
fileWriter.write(htmlText);
fileWriter.close();
Tab thisTab = this.tabPane.getSelectionModel().getSelectedItem();
thisTab.setText(file.getName());
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
public void saveFile(){
//check if well formed, if not, give them ability to cancel save
}
public void closeApp(){
// we should also cycle through all open documents and check if they were saved.
System.exit(0);
}
public void wrapTextSwitch(){
TextArea ta = (TextArea) this.tabPane.getSelectionModel().getSelectedItem().getContent();
ta.setWrapText(!ta.isWrapText());
}
public void aboutApp(){
double widthAppWindow = 400;
Label description = new Label("HTML Editor v." + VERSION
+ "\n\nSWEN-262 (Group 2)"
+ "\n\nBy Thomas Heissenberger, Emily Filmer, Jordan Tice, Michael Schug, Austin Cook, David Thong Nguyen"
+ "\n\nA light weight HTML editor used for editing HTML files.");
description.autosize();
description.setWrapText(true);
description.setMaxWidth(widthAppWindow * .8);
description.setTextFill(Paint.valueOf("white"));
Button btn = new Button("Close");
btn.setAlignment(Pos.BOTTOM_CENTER);
BorderPane aboutUsPane = new BorderPane();
aboutUsPane.setMargin(btn, new Insets(8,8,8,8));
aboutUsPane.setAlignment(btn, Pos.CENTER);
aboutUsPane.setCenter(description);
aboutUsPane.setBottom(btn);
aboutUsPane.setStyle(BACKGROUND_STYLE_CSS);
final Scene aboutUsScene = new Scene(aboutUsPane, widthAppWindow, 250);
final Stage aboutUsStage = new Stage();
aboutUsStage.setTitle("About Us");
aboutUsStage.setScene(aboutUsScene);
aboutUsStage.centerOnScreen();
aboutUsStage.show();
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
aboutUsStage.hide();
}
});
}
}
|
package com.dmdirc.logger;
import com.dmdirc.DMDircMBassador;
import com.dmdirc.config.ConfigBinder;
import com.dmdirc.config.ConfigBinding;
import com.dmdirc.events.ProgramErrorEvent;
import com.dmdirc.interfaces.config.AggregateConfigProvider;
import java.util.Collection;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import net.engio.mbassy.listener.Handler;
/**
* Listens for {@link ProgramErrorEvent}s and reports these to Sentry.
*/
public class SentryLoggingErrorManager {
/** A list of exceptions which we don't consider bugs and thus don't report. */
private static final Class<?>[] BANNED_EXCEPTIONS = new Class<?>[]{
NoSuchMethodError.class, NoClassDefFoundError.class,
UnsatisfiedLinkError.class, AbstractMethodError.class,
IllegalAccessError.class, OutOfMemoryError.class,
NoSuchFieldError.class,};
/** The event bus to listen for errors on. */
private final DMDircMBassador eventBus;
/** The config binder to use for settings. */
private final ConfigBinder configBinder;
/** Sentry error reporter factory. */
private final SentryErrorReporter sentryErrorReporter;
/** Thread used for sending errors. */
private final ExecutorService executorService;
/** Whether to submit error reports. */
private boolean submitReports;
/** Temp no error reporting. */
private boolean tempNoErrors;
/** Whether or not to send error reports. */
private boolean sendReports;
/**
* Creates a new instance of this error manager.
*
* @param eventBus The event bus to listen to errors on
* @param config The config to read values from
*/
public SentryLoggingErrorManager(final DMDircMBassador eventBus,
final AggregateConfigProvider config, final SentryErrorReporter sentryErrorReporter,
final ExecutorService executorService) {
this.eventBus = eventBus;
this.sentryErrorReporter = sentryErrorReporter;
this.executorService = executorService;
configBinder = config.getBinder();
}
/**
* Initialises the error manager. Must be called before logging will start.
*/
public void initialise() {
configBinder.bind(this, SentryLoggingErrorManager.class);
eventBus.subscribe(this);
}
@Handler
void handleErrorEvent(final ProgramErrorEvent error) {
final boolean appError = error.getError().isAppError();
if (!isValidError(error.getError().getThrowable())
|| !isValidSource(error.getError().getTrace())
|| !appError) {
error.getError().setReportStatus(ErrorReportStatus.NOT_APPLICABLE);
} else if (sendReports) {
executorService.submit(new ErrorReportingRunnable(sentryErrorReporter, error.getError()));
}
}
@ConfigBinding(domain = "general", key = "submitErrors")
void handleSubmitErrors(final boolean value) {
submitReports = value;
sendReports = submitReports && !tempNoErrors;
}
@ConfigBinding(domain = "temp", key="noerrorreporting")
void handleNoErrorReporting(final boolean value) {
tempNoErrors = value;
sendReports = submitReports && !tempNoErrors;
}
/**
* Determines whether or not the stack trace associated with this error is from a valid source.
* A valid source is one that is within a DMDirc package (com.dmdirc), and is not the DMDirc
* event queue.
*
* @return True if the source is valid, false otherwise
*/
private boolean isValidSource(final Collection<String> trace) {
final String line = getSourceLine(trace).orElse("");
return line.startsWith("com.dmdirc")
&& !line.startsWith("com.dmdirc.addons.ui_swing.DMDircEventQueue");
}
/**
* Returns the "source line" of this error, which is defined as the first line starting with a
* DMDirc package name (com.dmdirc). If no such line is found, returns the first line of the
* message.
*
* @return This error's source line
*/
private Optional<String> getSourceLine(final Collection<String> trace) {
for (String line : trace) {
if (line.startsWith("com.dmdirc")) {
return Optional.of(line);
}
}
return trace.stream().findFirst();
}
/**
* Determines whether or not the specified exception is one that we are willing to report.
*
* @param exception The exception to test
*
* @since 0.6.3m1
* @return True if the exception may be reported, false otherwise
*/
private boolean isValidError(final Throwable exception) {
Throwable target = exception;
while (target != null) {
for (Class<?> bad : BANNED_EXCEPTIONS) {
if (bad.equals(target.getClass())) {
return false;
}
}
target = target.getCause();
}
return true;
}
}
|
package com.github.andlyticsproject;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.github.andlyticsproject.cache.AppIconInMemoryCache;
import com.github.andlyticsproject.db.AndlyticsDb;
import com.github.andlyticsproject.dialog.AddEditLinkDialog;
import com.github.andlyticsproject.dialog.LongTextDialog;
import com.github.andlyticsproject.model.AppInfo;
import com.github.andlyticsproject.model.Link;
import com.github.andlyticsproject.util.DetachableAsyncTask;
import com.github.andlyticsproject.util.Utils;
public class AppInfoActivity extends SherlockFragmentActivity implements
AddEditLinkDialog.OnFinishAddEditLinkDialogListener, OnItemLongClickListener {
public static final String TAG = Main.class.getSimpleName();
private LinksListAdapter linksListAdapter;
private LoadLinksDb loadLinksDb;
private AppInfo appInfo;
private List<Link> links;
private ListView list;
private View linksListEmpty;
private AndlyticsDb db;
private String packageName;
private String iconFilePath;
private ActionMode currentActionMode;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appinfo);
Bundle b = getIntent().getExtras();
if (b != null) {
packageName = b.getString(BaseActivity.EXTRA_PACKAGE_NAME);
iconFilePath = b.getString(BaseActivity.EXTRA_ICON_FILE);
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
String appName = getDbAdapter().getAppName(packageName);
if (appName != null) {
getSupportActionBar().setSubtitle(appName);
}
if (iconFilePath != null) {
Bitmap bm = BitmapFactory.decodeFile(iconFilePath);
BitmapDrawable icon = new BitmapDrawable(getResources(), bm);
getSupportActionBar().setIcon(icon);
}
LayoutInflater layoutInflater = getLayoutInflater();
list = (ListView) findViewById(R.id.appinfo_links_list);
list.addHeaderView(layoutInflater.inflate(R.layout.appinfo_header, null), null, false);
list.addFooterView(layoutInflater.inflate(R.layout.appinfo_links_list_empty, null), null,
false);
links = new ArrayList<Link>();
linksListAdapter = new LinksListAdapter(this);
list.setAdapter(linksListAdapter);
list.setOnItemLongClickListener(this);
linksListAdapter.setLinks(links);
linksListAdapter.notifyDataSetChanged();
View playStoreButton = findViewById(R.id.appinfo_playstore);
playStoreButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://play.google.com/store/apps/details?id="
+ packageName));
startActivity(intent);
}
});
View descriptionView = findViewById(R.id.appinfo_description);
descriptionView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showLongTextDialog(R.string.appinfo_description_label, ((TextView) v).getText()
.toString());
}
});
View changelogView = findViewById(R.id.appinfo_changelog);
changelogView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showLongTextDialog(R.string.appinfo_changelog_label, ((TextView) v).getText()
.toString());
}
});
db = AndlyticsDb.getInstance(this);
loadLinksDb = new LoadLinksDb(this);
Utils.execute(loadLinksDb);
registerForContextMenu(list);
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (currentActionMode != null) {
return false;
}
// skip header
if (position == 0) {
return false;
}
currentActionMode = startActionMode(new ContextCallback(position));
list.setItemChecked(position, true);
return true;
}
@SuppressLint("NewApi")
class ContextCallback implements ActionMode.Callback {
private int position;
ContextCallback(int position) {
this.position = position;
}
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.links_context_menu, menu);
return true;
}
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
if (menuItem.getItemId() == R.id.itemLinksmenuEdit) {
int pos = position - 1; // Subtract one for the header
Link link = links.get(pos);
showAddEditLinkDialog(link);
actionMode.finish();
return true;
} else if (menuItem.getItemId() == R.id.itemLinksmenuDelete) {
int pos = position - 1; // Subtract one for the header
Link link = links.get(pos);
db.deleteLink(link.getId().longValue());
loadLinksDb = new LoadLinksDb(AppInfoActivity.this);
Utils.execute(loadLinksDb);
actionMode.finish();
return true;
}
return false;
}
public void onDestroyActionMode(ActionMode actionMode) {
list.setItemChecked(position, false);
currentActionMode = null;
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.clear();
getSupportMenuInflater().inflate(R.menu.links_menu, menu);
return true;
}
/**
* Called if item in option menu is selected.
*
* @param item
* The chosen menu item
* @return boolean true/false
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
overridePendingTransition(R.anim.activity_prev_in, R.anim.activity_prev_out);
return true;
case R.id.itemLinksmenuAdd:
showAddEditLinkDialog(null);
return true;
default:
return (super.onOptionsItemSelected(item));
}
}
@Override
public void onBackPressed() {
finish();
overridePendingTransition(R.anim.activity_prev_in, R.anim.activity_prev_out);
}
public ContentAdapter getDbAdapter() {
return getAndlyticsApplication().getDbAdapter();
}
public AndlyticsApp getAndlyticsApplication() {
return (AndlyticsApp) getApplication();
}
private static class LoadLinksDb extends DetachableAsyncTask<Void, Void, Void, AppInfoActivity> {
LoadLinksDb(AppInfoActivity activity) {
super(activity);
}
@Override
protected Void doInBackground(Void... params) {
if (activity == null) {
return null;
}
activity.getLinksFromDb();
return null;
}
@Override
protected void onPostExecute(Void result) {
if (activity == null) {
return;
}
activity.refreshLinks();
}
}
private void getLinksFromDb() {
appInfo = db.findAppByPackageName(packageName);
links = appInfo == null ? new ArrayList<Link>() : appInfo.getDetails().getLinks();
}
private void refreshLinks() {
linksListAdapter.setLinks(links);
linksListAdapter.notifyDataSetChanged();
linksListEmpty = findViewById(R.id.appinfo_links_list_empty);
if (links.size() == 0) {
linksListEmpty.setVisibility(View.VISIBLE);
} else {
linksListEmpty.setVisibility(View.GONE);
}
ImageView iconView = (ImageView) findViewById(R.id.appinfo_app_icon);
String packageName = appInfo.getPackageName();
// XXX hack? should be cached on main screen, so don't bother trying to load
// if (inMemoryCache.contains(packageName)) {
iconView.setImageBitmap(AppIconInMemoryCache.getInstance().get(packageName));
iconView.clearAnimation();
TextView appNameView = (TextView) findViewById(R.id.appinfo_app_name);
appNameView.setText(appInfo.getName());
TextView packageNameView = (TextView) findViewById(R.id.appinfo_package_name);
packageNameView.setText(packageName);
TextView developerView = (TextView) findViewById(R.id.appinfo_developer);
developerView.setText(String.format("%s / %s", appInfo.getDeveloperName(),
appInfo.getDeveloperId()));
TextView versionNameView = (TextView) findViewById(R.id.appinfo_version_name);
versionNameView.setText(appInfo.getVersionName());
TextView lastStoreUpdateView = (TextView) findViewById(R.id.appinfo_last_store_update);
lastStoreUpdateView.setText(DateFormat.getDateInstance().format(
appInfo.getDetails().getLastStoreUpdate()));
TextView descriptionView = (TextView) findViewById(R.id.appinfo_description);
descriptionView.setText(Html.fromHtml(appInfo.getDetails().getDescription()));
TextView changelogView = (TextView) findViewById(R.id.appinfo_changelog);
changelogView.setText(Html.fromHtml(appInfo.getDetails().getChangelog()));
}
@Override
public void onFinishAddEditLink(String url, String name, Long id) {
if (id == null) {
db.addLink(appInfo.getDetails(), url, name);
} else {
db.editLink(id, url, name);
}
loadLinksDb = new LoadLinksDb(this);
Utils.execute(loadLinksDb);
}
private void showAddEditLinkDialog(Link link) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag("fragment_addedit_link");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
AddEditLinkDialog addEditLinkDialog = new AddEditLinkDialog();
Bundle arguments = new Bundle();
if (link != null) {
arguments.putLong("id", link.getId().longValue());
arguments.putString("name", link.getName());
arguments.putString("url", link.getURL());
}
addEditLinkDialog.setArguments(arguments);
addEditLinkDialog.setOnFinishAddEditLinkDialogListener(this);
addEditLinkDialog.show(ft, "fragment_addedit_link");
}
private void showLongTextDialog(int title, String longText) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag("fragment_longtext");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
LongTextDialog longTextDialog = new LongTextDialog();
Bundle arguments = new Bundle();
arguments.putInt("title", title);
arguments.putString("longText", longText);
longTextDialog.setArguments(arguments);
longTextDialog.show(ft, "fragment_longtext");
}
}
|
package com.lekebilen.quasseldroid.gui;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.lekebilen.quasseldroid.Buffer;
import com.lekebilen.quasseldroid.CoreConnService;
import com.lekebilen.quasseldroid.IrcMessage;
import com.lekebilen.quasseldroid.R;
public class ChatActivity extends Activity{
public static final int MESSAGE_RECEIVED = 0;
private BacklogAdapter adapter;
// IncomingHandler handler;
private static final String TAG = ChatActivity.class.getSimpleName();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.chat_layout);
adapter = new BacklogAdapter(this, null);
ListView backlogList = ((ListView)findViewById(R.id.chatBacklogList));
backlogList.setCacheColorHint(0xffffff);
backlogList.setAdapter(adapter);
backlogList.setDividerHeight(0);
backlogList.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
findViewById(R.id.ChatInputView).setOnKeyListener(inputfieldKeyListener);
((ListView) findViewById(R.id.chatBacklogList)).setCacheColorHint(0xffffff);
}
private OnKeyListener inputfieldKeyListener = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction()==0 ) { //On key down as well
EditText inputfield = (EditText)findViewById(R.id.ChatInputView);
String inputText = inputfield.getText().toString();
if ( ! "".equals(inputText) ) {
boundConnService.sendMessage(adapter.buffer.getInfo().id, inputText);
inputfield.setText("");
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_TAB && event.getAction() == 0) {
onSearchRequested(); // lawl
}
return false;
}
};
//Nick autocomplete when pressing the search-button
@Override
public boolean onSearchRequested() {
EditText inputfield = (EditText)findViewById(R.id.ChatInputView);
String inputNick = inputfield.getText().toString();
if ( "".equals(inputNick) ) {
if ( adapter.buffer.nicks().size() > 0 ) {
inputfield.setText(adapter.buffer.nicks().get(0)+ ": ");
inputfield.setSelection(adapter.buffer.nicks().get(0).length() + 2);
}
} else {
for (String nick : adapter.buffer.nicks()) {
if ( nick.matches("(?i)"+inputNick+".*") ) { //Matches the start of the string
inputfield.setText(nick+ ": ");
inputfield.setSelection(nick.length() + 2);
break;
}
}
}
return false; // don't go ahead and show the search box
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.standard_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_preferences:
Intent i = new Intent(ChatActivity.this, PreferenceView.class);
startActivity(i);
break;
case R.id.menu_disconnect:
this.boundConnService.disconnectFromCore();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onStart() {
doBindService();
super.onStart();
}
@Override
protected void onStop() {
boundConnService.markBufferAsRead(adapter.getBufferId());
doUnbindService();
super.onStop();
}
public class BacklogAdapter extends BaseAdapter implements Observer {
//private ArrayList<IrcMessage> backlog;
private LayoutInflater inflater;
private Buffer buffer;
public BacklogAdapter(Context context, ArrayList<IrcMessage> backlog) {
// if (backlog==null) {
// this.backlog = new ArrayList<IrcMessage>();
// }else {
// this.backlog = backlog;
inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// public void addItem(IrcMessage item) {
// Log.i(TAG, item.timestamp.toString());
// //this.backlog.add(item);
// notifyDataSetChanged();
public void setBuffer(Buffer buffer) {
this.buffer = buffer;
((TextView)findViewById(R.id.chatNameView)).setText(buffer.getInfo().name + ": " + buffer.topic());
notifyDataSetChanged();
}
@Override
public int getCount() {
if (this.buffer==null) return 0;
return buffer.getSize();
}
@Override
public IrcMessage getItem(int position) {
//TODO: QriorityQueue is fucked, we dont want to convert to array here, so change later
return (IrcMessage) buffer.getBacklogEntry(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView==null) {
convertView = inflater.inflate(R.layout.backlog_item, null);
holder = new ViewHolder();
holder.timeView = (TextView)convertView.findViewById(R.id.backlog_time_view);
holder.nickView = (TextView)convertView.findViewById(R.id.backlog_nick_view);
holder.msgView = (TextView)convertView.findViewById(R.id.backlog_msg_view);
holder.separatorView = (TextView)convertView.findViewById(R.id.backlog_list_separator);
holder.item_layout = (LinearLayout)convertView.findViewById(R.id.backlog_item_linearlayout);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
//Log.i(TAG, position + " "+ getCount());
if (buffer.getLastSeenMessage() == getItem(position).messageId && position != (getCount()-1)) { //Set separator line here
holder.separatorView.getLayoutParams().height = 1;
} else {
holder.separatorView.getLayoutParams().height = 0;
}
if (position <= 5 && buffer.getSize() > 0){ //The fifth or less item in the backlog is shown, get more backlog
boundConnService.getMoreBacklog(buffer.getInfo().id);
}
IrcMessage entry = this.getItem(position);
holder.timeView.setText(entry.getTime());
int hashcode = entry.getNick().hashCode() & 0x00FFFFFF;
holder.nickView.setTextColor(Color.rgb(hashcode & 0xFF0000, hashcode & 0xFF00, hashcode & 0xFF));
holder.msgView.setTextColor(0xff000000);
holder.msgView.setTypeface(Typeface.DEFAULT);
switch (entry.type) {
case Action:
holder.nickView.setText("*");
holder.msgView.setTypeface(Typeface.DEFAULT_BOLD);
holder.msgView.setText(entry.getNick() + " " + entry.content);
break;
case Join:
holder.nickView.setText("→");
holder.msgView.setText(entry.getNick() + " has joined " + entry.content);
break;
case Part:
holder.nickView.setText("←");
holder.msgView.setText(entry.getNick() + " has left (" + entry.content + ")");
break;
case Quit:
holder.nickView.setText("←");
holder.msgView.setText(entry.getNick() + " has quit (" + entry.content + ")");
break;
//TODO: implement the rest
case Plain:
default:
holder.nickView.setText("<" + entry.getNick() + ">");
holder.msgView.setText(entry.content);
break;
}
if (entry.isHighlighted()) {
holder.item_layout.setBackgroundResource(R.color.ircmessage_highlight_color);
}else {
holder.item_layout.setBackgroundResource(R.color.ircmessage_normal_color);
}
//Log.i(TAG, "CONTENT:" + entry.content);
return convertView;
}
@Override
public void update(Observable observable, Object data) {
Log.i(TAG, "BACKLOG CHANGED");
notifyDataSetChanged();
}
public void stopObserving() {
buffer.deleteObserver(this);
}
public void clearBuffer() {
buffer = null;
}
public int getBufferId() {
return buffer.getInfo().id;
}
}
public static class ViewHolder {
public TextView timeView;
public TextView nickView;
public TextView msgView;
public TextView separatorView;
public LinearLayout item_layout;
}
/**
* Handler of incoming messages from service.
*/
// class IncomingHandler extends Handler {
// @Override
// public void handleMessage(Message msg) {
// switch (msg.what) {
// case R.id.CHAT_MESSAGES_UPDATED:
// ChatActivity.this.adapter.addItem((IrcMessage)msg.obj);
// break;
// // case CoreConnection.MSG_CONNECT:
// // mCallbackText.setText("We have connection!");
// // break;
// // case CoreConnection.MSG_CONNECT_FAILED:
// // mCallbackText.setText("Connection failed!");
// // break;
// // case CoreConnection.MSG_NEW_BUFFER:
// // mCallbackText.setText("Got new buffer!");
// // Buffer buffer = (Buffer) msg.obj;
// //// break;
// // case CoreConnection.MSG_NEW_MESSAGE:
// // IrcMessage message = (IrcMessage) msg.obj;
// // if (message.bufferInfo.id == bufferId) // Check if the message belongs to the buffer we're displaying
// // adapter.addItem(new BacklogEntry(message.timestamp.toString(), message.sender, message.content));
// // break;
// //// case CoreConnection.MSG_NEW_NETWORK:
// //// mCallbackText.setText("Got new network!");
// //// Network network = (Network) msg.obj;
// //// break;
// // case CoreConnection.MSG_NEW_USER:
// // mCallbackText.setText("Got new user!");//TODO: handle me
// // IrcUser user = (IrcUser) msg.obj;
// // if (user.channels.contains(bufferName)) // Make sure the user is in this channel
// // nicks.add(user.nick);
// // break;
// // default:
// // super.handleMessage(msg);
/**
* Code for service binding:
*/
private CoreConnService boundConnService;
private Boolean isBound;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
Log.i(TAG, "BINDING ON SERVICE DONE");
boundConnService = ((CoreConnService.LocalBinder)service).getService();
Intent intent = getIntent();
//Testing to see if i can add item to adapter in service
adapter.setBuffer(boundConnService.getBuffer(intent.getIntExtra(BufferActivity.BUFFER_ID_EXTRA, 0), adapter));
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
boundConnService = null;
}
};
void doBindService() {
// Establish a connection with the service. We use an explicit
// class name because we want a specific service implementation that
// we know will be running in our own process (and thus won't be
// supporting component replacement by other applications).
bindService(new Intent(ChatActivity.this, CoreConnService.class), mConnection, Context.BIND_AUTO_CREATE);
isBound = true;
Log.i(TAG, "BINDING");
}
void doUnbindService() {
if (isBound) {
Log.i(TAG, "Unbinding service");
// Detach our existing connection.
if (adapter.buffer.getSize()!= 0){
adapter.buffer.setLastSeenMessage(adapter.buffer.getBacklogEntry(adapter.buffer.getSize()-1).messageId);
}
adapter.stopObserving();
unbindService(mConnection);
isBound = false;
adapter.clearBuffer();
}
}
}
|
package com.mamewo.podplayer0;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.io.File;
import com.mamewo.podplayer0.PlayerService.MusicInfo;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.Prediction;
import android.gesture.GestureOverlayView.OnGesturePerformedListener;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
//common activity + gesture
abstract public class BasePodplayerActivity
extends Activity
implements OnSharedPreferenceChangeListener,
OnGesturePerformedListener
{
final static
protected PodcastInfo[] DUMMY_INFO_LIST = new PodcastInfo[0];
protected PlayerService player_ = null;
protected GestureLibrary gestureLib_;
protected double gestureScoreThreshold_;
protected BaseGetPodcastTask loadTask_;
protected PodplayerState state_;
protected boolean finishServiceOnExit_;
protected ServiceConnection connection_;
protected boolean showPodcastIcon_;
private boolean uiSettingChanged_;
//TODO: add preference
// 10 Mbyteq
static final
private long HTTP_CACHE_SIZE = 10 * 1024 * 1024;
private File httpCacheDir_;
final static
public String TAG = "podplayer";
abstract protected void onPodcastListChanged(boolean start);
public void onCreate(Bundle savedInstanceState, ServiceConnection conn, Class<?> userClass) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, PlayerService.class);
startService(intent);
finishServiceOnExit_ = false;
state_ = null;
uiSettingChanged_ = false;
if(null != savedInstanceState){
state_ = (PodplayerState) savedInstanceState.get("state");
}
if(null == state_){
state_ = new PodplayerState();
}
connection_ = conn;
//TODO: handle error
bindService(intent, conn, Context.BIND_AUTO_CREATE);
loadTask_ = null;
SharedPreferences pref=
PreferenceManager.getDefaultSharedPreferences(this);
pref.registerOnSharedPreferenceChangeListener(this);
httpCacheDir_ = new File(getCacheDir(), "http");
boolean cacheSet = enableHttpResponseCache(httpCacheDir_);
Log.d(TAG, "cache set: " + cacheSet);
}
private boolean enableHttpResponseCache(File cacheDir) {
try {
Class.forName("android.net.http.HttpResponseCache")
.getMethod("install", File.class, long.class)
.invoke(null, cacheDir, HTTP_CACHE_SIZE);
return true;
} catch (Exception e) {
//nop
}
return false;
}
@Override
public void onDestroy() {
for (PodcastInfo info : state_.podcastList_) {
if (null != info.icon_) {
Bitmap bitmap = info.icon_.getBitmap();
bitmap.recycle();
}
}
SharedPreferences pref =
PreferenceManager.getDefaultSharedPreferences(this);
pref.unregisterOnSharedPreferenceChangeListener(this);
if (null != loadTask_) {
loadTask_.cancel(true);
}
boolean playing = player_.isPlaying();
if(finishServiceOnExit_ && playing) {
player_.stopMusic();
}
unbindService(connection_);
if (finishServiceOnExit_ || ! playing) {
Intent intent = new Intent(this, PlayerService.class);
stopService(intent);
}
super.onDestroy();
}
@Override
protected void onStart() {
super.onStart();
//TODO: check current activity and preference
if (uiSettingChanged_) {
Intent intent = new Intent(this, MainActivity.class);
//TODO: add flag of restart
startActivity(intent);
finish();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putSerializable("state", state_);
}
public void updatePlaylist() {
player_.setPlaylist(state_.loadedEpisode_);
}
public boolean isLoading() {
return (null != loadTask_ && loadTask_.getStatus() == AsyncTask.Status.RUNNING);
}
public void startLoading(BaseGetPodcastTask task) {
if (isLoading()) {
Log.d(TAG, "startLoading: already loading");
return;
}
state_.loadedEpisode_.clear();
loadTask_ = task;
loadTask_.execute(state_.podcastList_.toArray(DUMMY_INFO_LIST));
}
public void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean handled = false;
switch(item.getItemId()) {
case R.id.exit_menu:
finishServiceOnExit_ = true;
finish();
handled = true;
break;
case R.id.pref_menu:
startActivity(new Intent(this, PodplayerPreference.class));
handled = true;
break;
default:
break;
}
return handled;
}
@Override
public void onSharedPreferenceChanged(SharedPreferences pref, String key) {
Log.d(TAG, "onSharedPreferneceChanged: " + key);
syncPreference(pref, key);
}
protected void syncPreference(SharedPreferences pref, String key){
boolean updateAll = "ALL".equals(key);
if ("use_expandable_ui".equals(key)) {
uiSettingChanged_ = true;
}
if (updateAll || "enable_gesture".equals(key)) {
boolean useGesture = pref.getBoolean("enable_gesture", PodplayerPreference.DEFAULT_USE_GESTURE);
GestureOverlayView gestureView =
(GestureOverlayView)findViewById(R.id.gesture_view);
if(useGesture) {
gestureLib_ = GestureLibraries.fromRawResource(this, R.raw.gestures);
if(! gestureLib_.load()){
Log.i(TAG, "gesture load failed");
}
gestureView.addOnGesturePerformedListener(this);
}
else {
gestureView.removeOnGesturePerformedListener(this);
gestureLib_ = null;
}
gestureView.setEnabled(useGesture);
}
if (updateAll || "gesture_score_threshold".equals(key)) {
gestureScoreThreshold_ =
Double.valueOf(pref.getString("gesture_score_threshold", PodplayerPreference.DEFAULT_GESTURE_SCORE));
}
if (updateAll || "show_podcast_icon".equals(key)) {
showPodcastIcon_ = pref.getBoolean("show_podcast_icon", PodplayerPreference.DEFAULT_SHOW_ICON);
}
//following block should be last one of this function
if (updateAll || "podcastlist2".equals(key)) {
state_.podcastList_ = PodcastListPreference.loadSetting(this);
onPodcastListChanged(updateAll);
}
}
@Override
public void onGesturePerformed(GestureOverlayView view, Gesture gesture) {
ArrayList<Prediction> predictions = gestureLib_.recognize(gesture);
if(predictions.size() == 0){
showMessage("unknown gesture");
return;
}
//predictions is sorted by score
Prediction p = predictions.get(0);
if(p.score < gestureScoreThreshold_) {
showMessage(String.format("gesture with low score: %.2f", p.score));
return;
}
if("next".equals(p.name)) {
player_.playNext();
}
else if("play".equals(p.name)) {
updatePlaylist();
if(! player_.restartMusic()) {
player_.playMusic();
}
}
else if("pause".equals(p.name)) {
player_.pauseMusic();
}
else if("back".equals(p.name)) {
player_.stopMusic();
player_.playMusic();
}
showMessage(p.name);
}
final public static
class PodplayerState
implements Serializable
{
private static final long serialVersionUID = 1L;
protected List<MusicInfo> loadedEpisode_;
protected List<PodcastInfo> podcastList_;
protected String lastUpdated_;
private PodplayerState() {
loadedEpisode_ = new ArrayList<MusicInfo>();
podcastList_ = new ArrayList<PodcastInfo>();
lastUpdated_ = "";
}
}
}
|
package com.sun.pdfview.annotation;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.geom.Rectangle2D.Float;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.sun.pdfview.PDFCmd;
import com.sun.pdfview.PDFImage;
import com.sun.pdfview.PDFObject;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PDFParseException;
import com.sun.pdfview.PDFParser;
/**
* PDF annotation describing a widget.
* @since Aug 20, 2010
*/
public class WidgetAnnotation extends PDFAnnotation {
private String fieldValue;
private FieldType fieldType;
private String fieldName;
private PDFObject fieldValueRef;
private List<PDFCmd> cmd;
/**
* Type for PDF form elements
* @version $Id: WidgetAnnotation.java,v 1.2 2010-09-30 10:34:44 xphc Exp $
* @author xphc
* @since Aug 20, 2010
*/
public enum FieldType {
/** Button Field */
Button("Btn"),
/** Text Field */
Text("Tx"),
/** Choice Field */
Choice("Ch"),
/** Signature Field */
Signature("Sig");
private final String typeCode;
FieldType(String typeCode) {
this.typeCode = typeCode;
}
static FieldType getByCode(String typeCode) {
FieldType[] values = values();
for (FieldType value : values) {
if (value.typeCode.equals(typeCode))
return value;
}
return null;
}
}
public WidgetAnnotation(PDFObject annotObject) throws IOException {
super(annotObject, ANNOTATION_TYPE.WIDGET);
// The type of field that this dictionary describes. Field type is
// present for terminal fields but is inherited from parent if absent
// (see PDF Reference 1.7 table 8.69)
PDFObject fieldTypeRef = annotObject.getDictRef("FT");
if (fieldTypeRef != null) {
// terminal field
this.fieldType = FieldType.getByCode(fieldTypeRef.getStringValue());
}
else {
// must check parent since field type is inherited
PDFObject parent = annotObject.getDictRef("Parent");
while (parent != null && parent.isIndirect()) {
parent = parent.dereference();
}
if (parent != null) {
fieldTypeRef = parent.getDictRef("FT");
this.fieldType = FieldType.getByCode(fieldTypeRef.getStringValue());
}
}
// Name defined for the field
PDFObject fieldNameRef = annotObject.getDictRef("T");
if (fieldNameRef != null) {
this.fieldName = fieldNameRef.getTextStringValue();
}
this.fieldValueRef = annotObject.getDictRef("V");
if (this.fieldValueRef != null) {
this.fieldValue = this.fieldValueRef.getTextStringValue();
}
parseAP(annotObject.getDictRef("AP"));
}
private void parseAP(PDFObject dictRef) throws IOException {
if(dictRef == null) {
return;
}
PDFObject normalAP = dictRef.getDictRef("N");
if(normalAP == null) {
return;
}
cmd = parseCommand(normalAP);
}
private List<PDFCmd> parseCommand(PDFObject obj) throws IOException {
String type = obj.getDictRef("Subtype").getStringValue();
if (type == null) {
type = obj.getDictRef ("S").getStringValue ();
}
ArrayList<PDFCmd> result = new ArrayList<PDFCmd>();
result.add(PDFPage.createPushCmd());
result.add(PDFPage.createPushCmd());
if (type.equals("Image")) {
// stamp annotation transformation
AffineTransform rectAt = getPositionTransformation();
result.add(PDFPage.createXFormCmd(rectAt));
PDFImage img = PDFImage.createImage(obj, new HashMap<String, PDFObject>() , false);
result.add(PDFPage.createImageCmd(img));
} else if (type.equals("Form")) {
// rats. parse it.
PDFObject bobj = obj.getDictRef("BBox");
Float bbox = new Rectangle2D.Float(bobj.getAt(0).getFloatValue(),
bobj.getAt(1).getFloatValue(),
bobj.getAt(2).getFloatValue(),
bobj.getAt(3).getFloatValue());
PDFPage formCmds = new PDFPage(bbox, 0);
// stamp annotation transformation
AffineTransform rectAt = getPositionTransformation();
formCmds.addXform(rectAt);
// form transformation
AffineTransform at;
PDFObject matrix = obj.getDictRef("Matrix");
if (matrix == null) {
at = new AffineTransform();
} else {
float elts[] = new float[6];
for (int i = 0; i < elts.length; i++) {
elts[i] = (matrix.getAt(i)).getFloatValue();
}
at = new AffineTransform(elts);
}
formCmds.addXform(at);
HashMap<String,PDFObject> r = new HashMap<String,PDFObject>(new HashMap<String, PDFObject>());
PDFObject rsrc = obj.getDictRef("Resources");
if (rsrc != null) {
r.putAll(rsrc.getDictionary());
}
PDFParser form = new PDFParser(formCmds, obj.getStream(), r);
form.go(true);
result.addAll(formCmds.getCommands());
} else {
throw new PDFParseException("Unknown XObject subtype: " + type);
}
result.add(PDFPage.createPopCmd());
result.add(PDFPage.createPopCmd());
return result;
}
/**
* Transform to the position of the stamp annotation
* @return
*/
private AffineTransform getPositionTransformation() {
Float rect2 = getRect();
double[] f = new double[] {1,
0,
0,
1,
rect2.getMinX(),
rect2.getMinY()};
return new AffineTransform(f);
}
/**
* Returns the type of the field
* @return Field type
*/
public FieldType getFieldType() {
return this.fieldType;
}
/**
* The field's value as a string. Might be {@code null}.
* @return The field value or {@code null}.
*/
public String getFieldValue() {
return this.fieldValue;
}
/**
* Sets the field value for a text field. Note: this doesn't actually change
* the PDF file yet.
*
* @param fieldValue
* The new value for the text field
*/
public void setFieldValue(String fieldValue) {
this.fieldValue = fieldValue;
}
/**
* Name for this widget.
* @return Widget name
*/
public String getFieldName() {
return this.fieldName;
}
@Override
public List<PDFCmd> getPageCommandsForAnnotation() {
List<PDFCmd> pageCommandsForAnnotation = super.getPageCommandsForAnnotation();
// cmd might be null if there is no AP (appearance dictionary)
// AP is optional see PDF Reference 1.7 table 8.15
if (this.cmd != null) {
pageCommandsForAnnotation.addAll(this.cmd);
}
return pageCommandsForAnnotation;
}
}
|
package com.syncleus.dann.genetics.wavelets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
public class Nucleus implements Cloneable
{
private ArrayList<Chromosome> chromosomes;
public Nucleus(Nucleus copy)
{
this.chromosomes = new ArrayList<Chromosome>();
for(Chromosome chromosome : copy.chromosomes)
this.chromosomes.add(chromosome.clone());
}
protected List<Chromosome> getChromosomes()
{
return Collections.unmodifiableList(this.chromosomes);
}
public void tick(Set<SignalKeyConcentration> externalSignalConcentrations)
{
}
public boolean bind(SignalKeyConcentration concentration, boolean isExternal)
{
return false;
}
/*
public List<ExternalSignalGene> getExternalSignalGenes()
{
HashMap<SignalKey, Double> externalSignals = new HashMap<SignalKey, Double>();
for(Chromosome chromosome : this.chromosomes)
{
for(ExternalSignalGene gene : chromosome.getExternalSignalGenes())
{
Double currentConcentration = externalSignals.get(gene);
if(currentConcentration == null)
currentConcentration = 0D;
externalSignals.put(gene.getOutputSignal(), currentConcentration + gene.expressionActivity());
}
}
return Collections.unmodifiableMap(externalSignals);
}*/
@Override
public Nucleus clone()
{
return new Nucleus(this);
}
public void mutate()
{
for(Chromosome chromosome : this.chromosomes)
chromosome.mutate(null);
}
}
|
package org.apache.jmeter.threads;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import org.apache.jmeter.assertions.Assertion;
import org.apache.jmeter.config.ConfigTestElement;
import org.apache.jmeter.control.Controller;
import org.apache.jmeter.control.GenericController;
import org.apache.jmeter.engine.event.LoopIterationListener;
import org.apache.jmeter.processor.PostProcessor;
import org.apache.jmeter.processor.PreProcessor;
import org.apache.jmeter.samplers.AbstractSampler;
import org.apache.jmeter.samplers.SampleEvent;
import org.apache.jmeter.samplers.SampleListener;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;
import org.apache.jmeter.testelement.AbstractTestElement;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.timers.Timer;
import org.apache.jorphan.collections.HashTree;
import org.apache.jorphan.collections.HashTreeTraverser;
import org.apache.jorphan.collections.ListedHashTree;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
/**
* @author unascribed
* @version $Revision$
*/
public class TestCompiler implements HashTreeTraverser, SampleListener
{
transient private static Logger log = LoggingManager.getLoggerForClass();
LinkedList stack = new LinkedList();
Map samplerConfigMap = new HashMap();
Set objectsWithFunctions = new HashSet();
HashTree testTree;
SampleResult previousResult;
Sampler currentSampler;
JMeterVariables threadVars;
private static Set pairing = new HashSet();
//TODO: should pairing be static?
List loopIterListeners = new ArrayList();
public TestCompiler(HashTree testTree, JMeterVariables vars)
{
threadVars = vars;
this.testTree = testTree;
}
public static synchronized void initialize()
{
pairing.clear();
}
public void sampleOccurred(SampleEvent e)
{
previousResult = e.getResult();
}
public void sampleStarted(SampleEvent e)
{
}
public void sampleStopped(SampleEvent e)
{
}
public SamplePackage configureSampler(Sampler sampler)
{
currentSampler = sampler;
SamplePackage pack = (SamplePackage) samplerConfigMap.get(sampler);
pack.setSampler(sampler);
runPreProcessors(pack.getPreProcessors());
configureWithConfigElements(sampler, pack.getConfigs());
//replaceStatics(ret);
return pack;
}
private void runPreProcessors(List preProcessors)
{
Iterator iter = preProcessors.iterator();
while (iter.hasNext())
{
PreProcessor ex = (PreProcessor) iter.next();
log.debug(
"Running preprocessor: "
+ ((AbstractTestElement) ex).getName());
ex.process();
}
}
public void done(SamplePackage pack)
{
pack.recoverRunningVersion();
}
public void addNode(Object node, HashTree subTree)
{
stack.addLast(node);
}
public void subtractNode()
{
log.debug("Subtracting node, stack size = " + stack.size());
TestElement child = (TestElement) stack.getLast();
trackIterationListeners(stack);
if (child instanceof Sampler)
{
saveSamplerConfigs((Sampler) child);
}
stack.removeLast();
if (stack.size() > 0)
{
ObjectPair pair =
new ObjectPair(
(TestElement) child,
(TestElement) stack.getLast());
synchronized (this){
if (!pairing.contains(pair))
{
pair.addTestElements();
pairing.add(pair);
}
}
}
}
private void trackIterationListeners(LinkedList stack)
{
TestElement child = (TestElement) stack.getLast();
if (child instanceof LoopIterationListener)
{
ListIterator iter = stack.listIterator(stack.size());
while (iter.hasPrevious())
{
TestElement item = (TestElement) iter.previous();
if (item == child)
{
continue;
}
else
{
if (item instanceof Controller)
{
((Controller) item).addIterationListener(
(LoopIterationListener) child);
break;
}
}
}
}
}
public void processPath()
{
}
private void saveSamplerConfigs(Sampler sam)
{
List configs = new LinkedList();
List modifiers = new LinkedList();
List responseModifiers = new LinkedList();
List listeners = new LinkedList();
List timers = new LinkedList();
List assertions = new LinkedList();
LinkedList posts = new LinkedList();
LinkedList pres = new LinkedList();
for (int i = stack.size(); i > 0; i
{
Iterator iter = testTree.list(stack.subList(0, i)).iterator();
List tempPre = new LinkedList();
List tempPost = new LinkedList();
while (iter.hasNext())
{
TestElement item = (TestElement) iter.next();
if ((item instanceof ConfigTestElement))
{
configs.add(item);
}
if (item instanceof SampleListener)
{
listeners.add(item);
}
if (item instanceof Timer)
{
timers.add(item);
}
if (item instanceof Assertion)
{
assertions.add(item);
}
if (item instanceof PostProcessor)
{
tempPost.add(item);
}
if (item instanceof PreProcessor)
{
tempPre.add(item);
}
}
pres.addAll(0,tempPre);
posts.addAll(0,tempPost);
}
SamplePackage pack =
new SamplePackage(
configs,
modifiers,
responseModifiers,
listeners,
timers,
assertions,
posts,
pres);
pack.setSampler(sam);
pack.setRunningVersion(true);
samplerConfigMap.put(sam, pack);
}
/**
* @author $Author$
* @version $Revision$
*/
public static class Test extends junit.framework.TestCase
{
public Test(String name)
{
super(name);
}
public void testConfigGathering() throws Exception
{
ListedHashTree testing = new ListedHashTree();
GenericController controller = new GenericController();
ConfigTestElement config1 = new ConfigTestElement();
config1.setName("config1");
config1.setProperty("test.property", "A test value");
TestSampler sampler = new TestSampler();
sampler.setName("sampler");
testing.add(controller, config1);
testing.add(controller, sampler);
TestCompiler.initialize();
TestCompiler compiler =
new TestCompiler(testing, new JMeterVariables());
testing.traverse(compiler);
sampler =
(TestSampler) compiler.configureSampler(sampler).getSampler();
assertEquals(
"A test value",
sampler.getPropertyAsString("test.property"));
}
class TestSampler extends AbstractSampler
{
public SampleResult sample(org.apache.jmeter.samplers.Entry e)
{
return null;
}
public Object clone()
{
return new TestSampler();
}
}
}
/**
* @author $Author$
* @version $Revision$
*/
private class ObjectPair
{
TestElement child, parent;
public ObjectPair(TestElement one, TestElement two)
{
this.child = one;
this.parent = two;
}
public void addTestElements()
{
if (parent instanceof Controller
&& (child instanceof Sampler || child instanceof Controller))
{
parent.addTestElement(child);
}
}
public int hashCode()
{
return child.hashCode() + parent.hashCode();
}
public boolean equals(Object o)
{
if (o instanceof ObjectPair)
{
return child == ((ObjectPair) o).child
&& parent == ((ObjectPair) o).parent;
}
return false;
}
}
private void configureWithConfigElements(Sampler sam, List configs)
{
Iterator iter = configs.iterator();
while (iter.hasNext())
{
ConfigTestElement config = (ConfigTestElement)iter.next();
sam.addTestElement(config);
}
}
}
|
package demo.MeetingScheduler;
import java.util.Vector;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Date;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import jade.core.Agent;
import jade.core.AgentGroup;
import jade.lang.acl.ACLMessage;
import jade.domain.AgentManagementOntology;
/**
Javadoc documentation for the file
@author Fabio Bellifemine - CSELT S.p.A
@version $Date$ $Revision$
*/
public class MeetingSchedulerAgent extends Agent {
String user; // this is the name of the current user
Vector knownDF = new Vector(); // list of known DF with which the agent is registered
mainFrame mf; // pointer to the main frame of the GUI
Hashtable knownPersons = new Hashtable(10, 0.8f); // list of known persons: (String)name -> Person
Hashtable appointments = new Hashtable(10, 0.8f); // list of appointments: (String)date -> Appointment
final static String REPLYBY = "+00000000T000059000Z"; // 59 seconds
protected void setup() {
(new PasswordDialog(this, "Enter your name and password")).setVisible(true);
addBehaviour(new myFipaContractNetResponderBehaviour(this));
addBehaviour(new CancelAppointmentBehaviour(this));
}
protected void searchPerson(String dfname, String personName) {
addBehaviour(new SearchPersonBehaviour(this, dfname, personName));
}
protected void DFregistration(String dfname) {
AgentManagementOntology.ServiceDescriptor sd = new AgentManagementOntology.ServiceDescriptor();
sd.setName("AppointmentScheduling");
sd.setType("personal-agent");
sd.setOntology("pa-ontology");
sd.setFixedProps("(represents " + user + ")");
AgentManagementOntology.DFAgentDescriptor dfd = new AgentManagementOntology.DFAgentDescriptor();
dfd.setName(getName());
dfd.addAddress(getAddress());
dfd.addAgentService(sd);
dfd.setType("fipa-agent");
dfd.setOntology("pa-ontology");
dfd.addInteractionProtocol("fipa-request fipa-Contract-Net");
dfd.setDFState("active");
dfd.setOwnership(user);
try {
//dfd.toText(new BufferedWriter(new OutputStreamWriter(System.out)));
registerWithDF(dfname,dfd);
knownDF.addElement(dfname);
Person p = new Person(user,dfd,dfname);
addKnownPerson(p);
} catch (jade.domain.FIPAException fe) {
fe.printStackTrace();
mf.showErrorMessage(fe.getMessage());
}
}
/**
* This method returns an Enumeration of String.
* Each String is the name of a DF with which the agent has been registered
*/
protected Enumeration getKnownDF() {
return knownDF.elements();
}
/**
* This method returns an Enumeration of objects.
* The object type is Person
*/
protected Enumeration getKnownPersons() {
return knownPersons.elements();
}
protected void addKnownPerson(Person p) {
knownPersons.put(p.getName(),p);
mf.showErrorMessage("Known " + p.getName());
}
protected Person getPerson(String name) {
return (Person)knownPersons.get(name);
}
protected Person getPersonbyAgentName(String agentname) {
//System.err.println("getPersonbyAgentName: "+agentname);
Enumeration e = knownPersons.elements();
Person p;
while (e.hasMoreElements()) {
p = (Person)e.nextElement();
//System.err.println(p.toString());
if (p.getAgentName().startsWith(agentname))
return p;
}
return null;
}
protected void fixAppointment(Appointment a) {
System.err.println("fix Appointment" + a.toString());
ACLMessage cfp = new ACLMessage(ACLMessage.CFP);
//FIXME only for Seoul
// cfp.setContent(a.toString());
cfp.setSource(getName());
cfp.setReplyBy(REPLYBY);
AgentGroup ag = new AgentGroup();
Enumeration e = a.getInvitedPersons();
int numberOfInvited = 0;
String name;
String listOfNames = "";
while (e.hasMoreElements()) {
numberOfInvited++;
name = ((Person)e.nextElement()).getAgentName();
//if (name.endsWith(getAddress()))
/* it belongs to my platform. so remove platform name otherwise
fipacontractnetinitiatorbheaviour does not work */
//ag.addMember(name.substring(0,name.indexOf('@')));
//else
ag.addMember(name);
listOfNames = listOfNames + name + " ";
}
if (numberOfInvited == 0) { // ci sono solo io
// devo solo trovare un giorno libero
Date goodDate = findADate(a);
if (goodDate == null)
mf.showErrorMessage("No free date for "+a.toString());
else {
a.setFixedDate(goodDate);
addAppointment(a);
}
} else {
if (numberOfInvited > 1)
listOfNames = "(" + listOfNames + ")"; // becomes a list
String possibleAppList = possibleAppointments(a);
if (possibleAppList != null) {
cfp.setContent("( (action " + " * " + " (possible-appointments " + possibleAppList + ")) true )");
addBehaviour(new myFipaContractNetInitiatorBehaviour(this,cfp,ag));
} else mf.showErrorMessage("No free date for "+a.toString());
}
}
/**
* This function returns a string representing the list of available days for this
* appointment
* @param a the Appointment
* @return a String representing the list of valid dates, e.g. (list 21 22),
* returns null if no date is available
*/
//FIXME it is using FIPA Seoul syntax. May need changes
String possibleAppointments(Appointment a) {
String str = "(list ";
boolean nodatepossible = true;
Date ds = a.getStartingOn();
Date de = a.getEndingWith();
while (! ds.after(de)) {
if (! appointments.containsKey(key(ds))) {
nodatepossible = false;
str = str+ds.getDate() + " "; // mette solo il giorno tra 1 e 31
}
ds.setTime(ds.getTime()+(24*60*60*1000)); // + 1 day
}
if (nodatepossible) return null;
else return str + ")";
}
/**
* @param a an Appointment
* @return a good Date for that Appointment
*/
Date findADate(Appointment a) {
Date ds = a.getStartingOn();
if (appointments.containsKey(key(ds))) {
ds.setTime(ds.getTime()+(24*60*60*1000)); // + 1 day
Date de = a.getEndingWith();
while (! ds.after(de)) {
if (appointments.containsKey(key(ds))) {
ds.setTime(ds.getTime()+(24*60*60*1000)); // + 1 day
} else return ds;
} // end of while
return null;
}
return ds;
}
protected void cancelAppointment(Date date) {
Appointment a = (Appointment)appointments.get(key(date));
//System.err.println("Cancel Appointment: " + a.toString());
Enumeration e = a.getInvitedPersons();
int numberOfInvited = 0;
String name;
ACLMessage cancel = new ACLMessage(ACLMessage.CANCEL);
cancel.setSource(getName());
while (e.hasMoreElements()) {
name = ((Person)e.nextElement()).getAgentName();
cancel.addDest(name);
//FIXME only for Seoul
// cfp.setContent(a.toString());
cancel.setContent("(action " + name + " (possible-appointments (list " + (a.getDate()).getDate() + ")))");
System.out.println(cancel.toString());
send(cancel);
}
removeAppointment(date);
}
public void removeAppointment(Date date) {
Appointment a = getAppointment(date);
if (a == null) {
mf.showErrorMessage("Someone has requested to cancel an appointment for " + date.toString()+" but there was no appointment actually");
} else {
appointments.remove(key(date));
mf.calendar1_Action(null);
mf.showErrorMessage("Cancelled Appointment: "+ a.toString());
}
}
protected void addAppointment(Appointment a) {
//System.err.println("addAppointment: "+a.toString());
appointments.put(key(a.getDate()),a);
mf.calendar1_Action(null);
mf.showErrorMessage(a.toString());
}
/**
* This function return the key to be used in the Hashtable
*/
private String key(Date d) {
return ""+d.getYear()+d.getMonth()+d.getDate();
}
protected Appointment getAppointment(Date date) {
return (Appointment)appointments.get(key(date));
}
protected void setUser(String username) {
addBehaviour(new DFRegistrationBehaviour(this,username));
}
protected String getUser() {
return user;
}
class DFRegistrationBehaviour extends jade.core.behaviours.OneShotBehaviour {
DFRegistrationBehaviour(Agent a, String username){
super(a);
user = username;
mf = new mainFrame((MeetingSchedulerAgent)a,user + " - Appointment Scheduler" );
}
public void action(){
DFregistration("df"); // register with the default DF
mf.setVisible(true);
}
}
class SearchPersonBehaviour extends jade.core.behaviours.OneShotBehaviour {
String dfname, personName;
SearchPersonBehaviour(Agent a, String dfName, String personname) {
super(a);
this.dfname=dfName;
this.personName=personname;
}
public void action(){
AgentManagementOntology.ServiceDescriptor sd = new AgentManagementOntology.ServiceDescriptor();
sd.setType("personal-agent");
if (personName != null)
sd.setFixedProps("(represents " + personName + ")");
AgentManagementOntology.DFAgentDescriptor dfd = new AgentManagementOntology.DFAgentDescriptor();
dfd.setOntology("pa-ontology");
//dfd.addAgentService(sd);
//dfd.setDFState("active");
//dfd.setOwnership(user);
try {
//dfd.toText(new BufferedWriter(new OutputStreamWriter(System.out)));
AgentManagementOntology.DFSearchResult result;
Vector vc = new Vector(1);
AgentManagementOntology.Constraint c = new AgentManagementOntology.Constraint();
c.setName(AgentManagementOntology.Constraint.DFDEPTH);
c.setFn(AgentManagementOntology.Constraint.MAX); // MIN
c.setArg(3);
vc.addElement(c);
result = searchDF(dfname,dfd,vc);
//System.err.println("\nSearch DF results:");
//result.toText(new BufferedWriter(new OutputStreamWriter(System.out)));
// add values to knownPersons
Enumeration e = result.elements();
while (e.hasMoreElements()) {
dfd = (AgentManagementOntology.DFAgentDescriptor)e.nextElement();
Person p = new Person(dfd.getOwnership(),dfd,dfname);
addKnownPerson(p);
}
} catch (jade.domain.FIPAException fe) {
fe.printStackTrace();
mf.showErrorMessage(fe.getMessage());
}
}
}
} // end Agent.java
|
package org.myrobotlab.framework;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.concurrent.BlockingQueue;
import org.junit.BeforeClass;
import org.junit.Test;
import org.myrobotlab.logging.Appender;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.Runtime;
import org.myrobotlab.service.TestCatcher;
import org.myrobotlab.service.TestThrower;
import org.myrobotlab.service.interfaces.CommunicationInterface;
import org.slf4j.Logger;
public class MessageTest {
public final static Logger log = LoggerFactory.getLogger(MessageTest.class);
static TestCatcher catcher;
static TestThrower thrower;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
LoggingFactory.getInstance().configure();
LoggingFactory.getInstance().setLevel(Level.INFO);
catcher = (TestCatcher)Runtime.start("catcher", "TestCatcher");
thrower = (TestThrower)Runtime.start("thrower", "TestThrower");
}
@Test
public void simpleSubscribeAndThrow() throws Exception {
catcher.clear();
catcher.subscribe("thrower", "pitch", "onPitch");
// ROUTE MUST STABALIZE - BEFORE MSGS - otherwise they will be missed
Service.sleep(100);
thrower.pitchInt(8000);
BlockingQueue<Message> balls = catcher.waitForMsgs(1000);
log.warn(String.format("caught %d balls", balls.size()));
log.warn(String.format("left balls %d ", catcher.msgs.size()));
}
@Test
public void broadcastMessage() throws Exception {
catcher.clear();
catcher.subscribe("thrower", "pitch", "onPitch");
Message msg = thrower.createMessage(null, "getServiceNames", null);
CommunicationInterface comm = thrower.getComm();
comm.send(msg);
String[] ret = (String[])thrower.invoke(msg);
log.info(String.format("got %s", Arrays.toString(ret)));
assertNotNull(ret);
}
@Test
public void clearRoutes() throws Exception {
catcher.clear();
catcher.subscribe("thrower", "pitch", "onPitch");
Service.sleep(100);
thrower.pitchInt(8000);
BlockingQueue<Message> balls = catcher.waitForMsgs(1000);
log.warn(String.format("caught %d balls", balls.size()));
log.warn(String.format("left balls %d ", catcher.msgs.size()));
Runtime.removeAllSubscriptions();
Message msg = thrower.createMessage(null, "getServiceNames", null);
CommunicationInterface comm = thrower.getComm();
comm.send(msg);
String[] ret = (String[])thrower.invoke(msg);
log.info(String.format("got %s", Arrays.toString(ret)));
assertNotNull(ret);
}
@Test
public void invokeStringNotation() throws Exception {
catcher.clear();
catcher.subscribe("thrower/pitch", "onPitch");
Runtime runtime = Runtime.getInstance();
Message msg = thrower.createMessage(null, "getServiceNames", null);
CommunicationInterface comm = thrower.getComm();
comm.send(msg);
String[] ret = (String[])thrower.invoke(msg);
log.info(String.format("got %s", Arrays.toString(ret)));
assertNotNull(ret);
}
public static void main(String[] args) {
try {
LoggingFactory.getInstance().configure();
LoggingFactory.getInstance().setLevel(Level.DEBUG);
Logging logging = LoggingFactory.getInstance();
logging.addAppender(Appender.FILE);
setUpBeforeClass();
} catch(Exception e){
Logging.logError(e);
}
System.exit(0);
}
}
|
package org.sagebionetworks.bridge;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.RandomStringUtils;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.springframework.validation.Validator;
import play.mvc.Http;
import play.mvc.Result;
import play.test.Helpers;
import org.sagebionetworks.bridge.config.BridgeConfigFactory;
import org.sagebionetworks.bridge.dao.ParticipantOption.SharingScope;
import org.sagebionetworks.bridge.dynamodb.DynamoCriteria;
import org.sagebionetworks.bridge.dynamodb.DynamoSchedulePlan;
import org.sagebionetworks.bridge.dynamodb.DynamoStudy;
import org.sagebionetworks.bridge.exceptions.InvalidEntityException;
import org.sagebionetworks.bridge.json.BridgeObjectMapper;
import org.sagebionetworks.bridge.json.DateUtils;
import org.sagebionetworks.bridge.models.Criteria;
import org.sagebionetworks.bridge.models.OperatingSystem;
import org.sagebionetworks.bridge.models.accounts.ConsentStatus;
import org.sagebionetworks.bridge.models.accounts.StudyParticipant;
import org.sagebionetworks.bridge.models.itp.IntentToParticipate;
import org.sagebionetworks.bridge.models.notifications.NotificationMessage;
import org.sagebionetworks.bridge.models.notifications.NotificationRegistration;
import org.sagebionetworks.bridge.models.notifications.NotificationTopic;
import org.sagebionetworks.bridge.models.notifications.SubscriptionRequest;
import org.sagebionetworks.bridge.models.schedules.ABTestScheduleStrategy;
import org.sagebionetworks.bridge.models.schedules.Activity;
import org.sagebionetworks.bridge.models.schedules.CriteriaScheduleStrategy;
import org.sagebionetworks.bridge.models.schedules.Schedule;
import org.sagebionetworks.bridge.models.schedules.ScheduleContext;
import org.sagebionetworks.bridge.models.schedules.ScheduleCriteria;
import org.sagebionetworks.bridge.models.schedules.SchedulePlan;
import org.sagebionetworks.bridge.models.schedules.ScheduleStrategy;
import org.sagebionetworks.bridge.models.schedules.ScheduleType;
import org.sagebionetworks.bridge.models.schedules.ScheduledActivity;
import org.sagebionetworks.bridge.models.schedules.SimpleScheduleStrategy;
import org.sagebionetworks.bridge.models.studies.EmailTemplate;
import org.sagebionetworks.bridge.models.studies.MimeType;
import org.sagebionetworks.bridge.models.studies.PasswordPolicy;
import org.sagebionetworks.bridge.models.studies.StudyIdentifier;
import org.sagebionetworks.bridge.models.subpopulations.ConsentSignature;
import org.sagebionetworks.bridge.models.subpopulations.SubpopulationGuid;
import org.sagebionetworks.bridge.models.upload.UploadValidationStrictness;
import org.sagebionetworks.bridge.validators.Validate;
public class TestUtils {
private static final DateTime TEST_CREATED_ON = DateTime.parse("2015-01-27T00:38:32.486Z");
public static void assertDatesWithTimeZoneEqual(DateTime date1, DateTime date2) {
// I don't know of a one line test for this... maybe just comparing ISO string formats of the date.
assertTrue(date1.isEqual(date2));
// This ensures that zones such as "America/Los_Angeles" and "-07:00" are equal
assertEquals( date1.getZone().getOffset(date1), date2.getZone().getOffset(date2) );
}
public static <E> void assertListIsImmutable(List<E> list, E sampleElement) {
try {
list.add(sampleElement);
fail("expected exception");
} catch (RuntimeException ex) {
// expected exception
}
}
public static <K, V> void assertMapIsImmutable(Map<K, V> map, K sampleKey, V sampleValue) {
try {
map.put(sampleKey, sampleValue);
fail("expected exception");
} catch (RuntimeException ex) {
// expected exception
}
}
public static <E> void assertSetIsImmutable(Set<E> set, E sampleElement) {
try {
set.add(sampleElement);
fail("expected exception");
} catch (RuntimeException ex) {
// expected exception
}
}
/**
* Asserts that on validation, InvalidEntityException has been thrown with an error key that is the nested path to
* the object value that is invalid, and the correct error message.
*/
public static void assertValidatorMessage(Validator validator, Object object, String fieldName, String error) {
String fieldNameAsLabel = fieldName;
if (!error.startsWith(" ")) {
error = " " + error;
}
try {
Validate.entityThrowingException(validator, object);
fail("Should have thrown exception");
} catch(InvalidEntityException e) {
if (e.getErrors().get(fieldName).contains(fieldNameAsLabel+error)) {
return;
}
fail("Did not find error message in errors object");
}
}
public static void assertResult(Result result, int statusCode, String message) throws Exception {
assertResult(result, statusCode);
JsonNode node = BridgeObjectMapper.get().readTree(Helpers.contentAsString(result));
String resultMessage = node.get("message").asText();
assertEquals(message, resultMessage);
}
public static void assertResult(Result result, int statusCode) throws Exception {
assertEquals(BridgeConstants.JSON_MIME_TYPE, result.header("Content-Type"));
assertEquals(statusCode, result.status());
}
public static Map<SubpopulationGuid,ConsentStatus> toMap(ConsentStatus... statuses) {
return TestUtils.toMap(Lists.newArrayList(statuses));
}
public static Map<SubpopulationGuid,ConsentStatus> toMap(Collection<ConsentStatus> statuses) {
ImmutableMap.Builder<SubpopulationGuid, ConsentStatus> builder = new ImmutableMap.Builder<SubpopulationGuid, ConsentStatus>();
if (statuses != null) {
for (ConsentStatus status : statuses) {
builder.put(SubpopulationGuid.create(status.getSubpopulationGuid()), status);
}
}
return builder.build();
}
public static Http.Response mockPlayContextWithJson(String json, Map<String,String[]> headers) throws Exception {
JsonNode node = new ObjectMapper().readTree(json);
Http.RequestBody body = mock(Http.RequestBody.class);
when(body.asJson()).thenReturn(node);
Http.Request request = mock(Http.Request.class);
Http.Response response = mock(Http.Response.class);
when(request.getHeader(anyString())).thenAnswer(invocation -> {
Object[] args = invocation.getArguments();
String[] values = headers.get(args[0]);
return (values == null || values.length == 0) ? null : values[0];
});
when(request.headers()).thenReturn(headers);
when(request.body()).thenReturn(body);
Http.Context context = mock(Http.Context.class);
when(context.request()).thenReturn(request);
when(context.response()).thenReturn(response);
Http.Context.current.set(context);
return response;
}
/**
* In the rare case where you need the context, you can use <code>Http.Context.current.get()</code>;
*/
public static Http.Response mockPlayContextWithJson(String json) throws Exception {
return mockPlayContextWithJson(json, Maps.newHashMap());
}
public static Http.Response mockPlayContextWithJson(Object object) throws Exception {
String json = BridgeObjectMapper.get().writeValueAsString(object);
return mockPlayContextWithJson(json, Maps.newHashMap());
}
public static Http.Response mockPlayContextWithJson(Object object, Map<String, String[]> headers) throws Exception {
String json = BridgeObjectMapper.get().writeValueAsString(object);
return mockPlayContextWithJson(json, headers);
}
/**
* In the rare case where you need the context, you can use <code>Http.Context.current.get()</code>;
*/
public static Http.Response mockPlayContext(Http.Request mockRequest) {
Http.Context context = mock(Http.Context.class);
when(context.request()).thenReturn(mockRequest);
Http.Response mockResponse = mock(Http.Response.class);
when(context.response()).thenReturn(mockResponse);
Http.Context.current.set(context);
return mockResponse;
}
/**
* In the rare case where you need the context, you can use <code>Http.Context.current.get()</code>;
*/
public static Http.Response mockPlayContext() throws Exception {
Http.RequestBody body = mock(Http.RequestBody.class);
when(body.asJson()).thenReturn(null);
Http.Request request = mock(Http.Request.class);
when(request.body()).thenReturn(body);
return mockPlayContext(request);
}
public static String randomName(Class<?> clazz) {
return "test-" + clazz.getSimpleName().toLowerCase() + "-" + RandomStringUtils.randomAlphabetic(5).toLowerCase();
}
public static final NotificationMessage getNotificationMessage() {
return new NotificationMessage.Builder()
.withSubject("a subject").withMessage("a message").build();
}
public static final SubscriptionRequest getSubscriptionRequest() {
return new SubscriptionRequest(Sets.newHashSet("topicA", "topicB"));
}
public static final NotificationTopic getNotificationTopic() {
NotificationTopic topic = NotificationTopic.create();
topic.setGuid("topicGuid");
topic.setName("Test Topic Name");
topic.setDescription("Test Description");
topic.setStudyId(TestConstants.TEST_STUDY_IDENTIFIER);
topic.setTopicARN("atopicArn");
return topic;
}
public static final IntentToParticipate getIntentToParticipate(long timestamp) {
ConsentSignature consentSignature = new ConsentSignature.Builder()
.withName("Gladlight Stonewell")
.withBirthdate("1980-10-10")
.withConsentCreatedOn(timestamp)
.withImageData("image-data")
.withImageMimeType("image/png").build();
IntentToParticipate itp = new IntentToParticipate.Builder()
.withStudyId("studyId")
.withScope(SharingScope.SPONSORS_AND_PARTNERS)
.withPhone(TestConstants.PHONE)
.withSubpopGuid("subpopGuid")
.withConsentSignature(consentSignature)
.build();
return itp;
}
public static final NotificationRegistration getNotificationRegistration() {
NotificationRegistration registration = NotificationRegistration.create();
registration.setDeviceId("deviceId");
registration.setEndpointARN("endpointARN");
registration.setGuid("registrationGuid");
registration.setHealthCode("healthCode");
registration.setOsName("osName");
registration.setCreatedOn(1484173675648L);
return registration;
}
public static final StudyParticipant getStudyParticipant(Class<?> clazz) {
String randomName = TestUtils.randomName(clazz);
return new StudyParticipant.Builder()
.withFirstName("FirstName")
.withLastName("LastName")
.withExternalId("externalId")
.withEmail("bridge-testing+"+randomName+"@sagebase.org")
.withPassword("password")
.withSharingScope(SharingScope.ALL_QUALIFIED_RESEARCHERS)
.withNotifyByEmail(true)
.withDataGroups(Sets.newHashSet("group1"))
.withAttributes(new ImmutableMap.Builder<String,String>().put("can_be_recontacted","true").build())
.withLanguages(TestUtils.newLinkedHashSet("fr")).build();
}
public static List<ScheduledActivity> runSchedulerForActivities(List<SchedulePlan> plans, ScheduleContext context) {
List<ScheduledActivity> scheduledActivities = Lists.newArrayList();
for (SchedulePlan plan : plans) {
Schedule schedule = plan.getStrategy().getScheduleForUser(plan, context);
// It's become possible for a user to match no schedule
if (schedule != null) {
scheduledActivities.addAll(schedule.getScheduler().getScheduledActivities(plan, context));
}
}
Collections.sort(scheduledActivities, ScheduledActivity.SCHEDULED_ACTIVITY_COMPARATOR);
return scheduledActivities;
}
public static List<ScheduledActivity> runSchedulerForActivities(ScheduleContext context) {
return runSchedulerForActivities(getSchedulePlans(context.getCriteriaContext().getStudyIdentifier()), context);
}
public static List<SchedulePlan> getSchedulePlans(StudyIdentifier studyId) {
List<SchedulePlan> plans = Lists.newArrayListWithCapacity(3);
SchedulePlan plan = new DynamoSchedulePlan();
plan.setGuid("DDD");
plan.setStrategy(getStrategy("P3D", getActivity1()));
plan.setStudyKey(studyId.getIdentifier());
plans.add(plan);
plan = new DynamoSchedulePlan();
plan.setGuid("BBB");
plan.setStrategy(getStrategy("P1D", getActivity2()));
plan.setStudyKey(studyId.getIdentifier());
plans.add(plan);
plan = new DynamoSchedulePlan();
plan.setGuid("CCC");
plan.setStrategy(getStrategy("P2D", getActivity3()));
plan.setStudyKey(studyId.getIdentifier());
plans.add(plan);
return plans;
}
public static Activity getActivity1() {
return new Activity.Builder().withGuid("activity1guid").withLabel("Activity1")
.withPublishedSurvey("identifier1", "AAA").build();
}
public static Activity getActivity2() {
return new Activity.Builder().withGuid("activity2guid").withLabel("Activity2")
.withPublishedSurvey("identifier2", "BBB").build();
}
public static Activity getActivity3() {
return new Activity.Builder().withLabel("Activity3").withGuid("AAA").withTask("tapTest").build();
}
public static SchedulePlan getSimpleSchedulePlan(StudyIdentifier studyId) {
Schedule schedule = new Schedule();
schedule.setScheduleType(ScheduleType.RECURRING);
schedule.setCronTrigger("0 0 8 ? * TUE *");
schedule.addActivity(new Activity.Builder().withGuid(BridgeUtils.generateGuid()).withLabel("Do task CCC")
.withTask("CCC").build());
schedule.setExpires(Period.parse("PT1H"));
schedule.setLabel("Test label for the user");
SimpleScheduleStrategy strategy = new SimpleScheduleStrategy();
strategy.setSchedule(schedule);
DynamoSchedulePlan plan = new DynamoSchedulePlan();
plan.setGuid("GGG");
plan.setModifiedOn(DateUtils.getCurrentMillisFromEpoch());
plan.setStudyKey(studyId.getIdentifier());
plan.setStrategy(strategy);
return plan;
}
public static SchedulePlan getCriteriaSchedulePlan(StudyIdentifier studyId) {
Schedule schedule = new Schedule();
schedule.setScheduleType(ScheduleType.RECURRING);
schedule.setCronTrigger("0 0 8 ? * TUE *");
schedule.addActivity(new Activity.Builder().withGuid(BridgeUtils.generateGuid()).withLabel("Do task CCC")
.withTask("CCC").build());
schedule.setExpires(Period.parse("PT60S"));
schedule.setLabel("Test label for the user");
Criteria criteria = createCriteria(0, 1, Sets.newHashSet("task1"), null);
ScheduleCriteria scheduleCriteria = new ScheduleCriteria(schedule, criteria);
CriteriaScheduleStrategy strategy = new CriteriaScheduleStrategy();
strategy.getScheduleCriteria().add(scheduleCriteria);
DynamoSchedulePlan plan = new DynamoSchedulePlan();
plan.setGuid("GGG");
plan.setModifiedOn(DateUtils.getCurrentMillisFromEpoch());
plan.setStudyKey(studyId.getIdentifier());
plan.setStrategy(strategy);
return plan;
}
public static ScheduleStrategy getStrategy(String interval, Activity activity) {
Schedule schedule = new Schedule();
schedule.setLabel("Schedule " + activity.getLabel());
schedule.setInterval(interval);
schedule.setDelay("P1D");
schedule.addTimes("13:00");
schedule.setExpires("PT10H");
schedule.addActivity(activity);
SimpleScheduleStrategy strategy = new SimpleScheduleStrategy();
strategy.setSchedule(schedule);
return strategy;
}
public static DynamoStudy getValidStudy(Class<?> clazz) {
String id = TestUtils.randomName(clazz);
Map<String,String> pushNotificationARNs = Maps.newHashMap();
pushNotificationARNs.put(OperatingSystem.IOS, "arn:ios:"+id);
pushNotificationARNs.put(OperatingSystem.ANDROID, "arn:android:"+id);
// This study will save without further modification.
DynamoStudy study = new DynamoStudy();
study.setName("Test Study ["+clazz.getSimpleName()+"]");
study.setShortName("ShortName");
study.setAutoVerificationEmailSuppressed(true);
study.setPasswordPolicy(PasswordPolicy.DEFAULT_PASSWORD_POLICY);
study.setStudyIdExcludedInExport(true);
study.setVerifyEmailTemplate(new EmailTemplate("verifyEmail subject", "body with ${url}", MimeType.TEXT));
study.setResetPasswordTemplate(new EmailTemplate("resetPassword subject", "body with ${url}", MimeType.TEXT));
study.setEmailSignInTemplate(new EmailTemplate("${studyName} link", "Follow link ${token}", MimeType.TEXT));
study.setAccountExistsTemplate(new EmailTemplate("accountExists subject", "body with ${url}", MimeType.TEXT));
study.setIdentifier(id);
study.setMinAgeOfConsent(18);
study.setSponsorName("The Council on Test Studies");
study.setConsentNotificationEmail("bridge-testing+consent@sagebase.org");
study.setSynapseDataAccessTeamId(1234L);
study.setSynapseProjectId("test-synapse-project-id");
study.setTechnicalEmail("bridge-testing+technical@sagebase.org");
study.setUploadValidationStrictness(UploadValidationStrictness.REPORT);
study.setUsesCustomExportSchedule(true);
study.setSupportEmail("bridge-testing+support@sagebase.org");
study.setUserProfileAttributes(Sets.newHashSet("a", "b"));
study.setTaskIdentifiers(Sets.newHashSet("task1", "task2"));
study.setActivityEventKeys(Sets.newHashSet("event1", "event2"));
study.setDataGroups(Sets.newHashSet("beta_users", "production_users"));
study.setStrictUploadValidationEnabled(true);
study.setHealthCodeExportEnabled(true);
study.setEmailVerificationEnabled(true);
study.setExternalIdValidationEnabled(true);
study.setEmailSignInEnabled(true);
study.setExternalIdRequiredOnSignup(true);
study.setActive(true);
study.setDisableExport(false);
study.setAccountLimit(0);
study.setPushNotificationARNs(pushNotificationARNs);
return study;
}
public static SchedulePlan getABTestSchedulePlan(StudyIdentifier studyId) {
Schedule schedule1 = new Schedule();
schedule1.setScheduleType(ScheduleType.RECURRING);
schedule1.setCronTrigger("0 0 8 ? * TUE *");
schedule1.addActivity(new Activity.Builder().withGuid(BridgeUtils.generateGuid()).withLabel("Do AAA task")
.withTask("AAA").build());
schedule1.setExpires(Period.parse("PT1H"));
schedule1.setLabel("Schedule 1");
Schedule schedule2 = new Schedule();
schedule2.setScheduleType(ScheduleType.RECURRING);
schedule2.setCronTrigger("0 0 8 ? * TUE *");
schedule2.addActivity(new Activity.Builder().withGuid(BridgeUtils.generateGuid()).withLabel("Do BBB task")
.withTask("BBB").build());
schedule2.setExpires(Period.parse("PT1H"));
schedule2.setLabel("Schedule 2");
Schedule schedule3 = new Schedule();
schedule3.setScheduleType(ScheduleType.RECURRING);
schedule3.setCronTrigger("0 0 8 ? * TUE *");
schedule3.addActivity(new Activity.Builder().withGuid(BridgeUtils.generateGuid()).withLabel("Do CCC task")
.withTask("CCC").build());
schedule3.setExpires(Period.parse("PT1H"));
schedule3.setLabel("Schedule 3");
DynamoSchedulePlan plan = new DynamoSchedulePlan();
plan.setGuid("AAA");
plan.setLabel("Test A/B Schedule");
plan.setModifiedOn(DateUtils.getCurrentMillisFromEpoch());
plan.setStudyKey(studyId.getIdentifier());
ABTestScheduleStrategy strategy = new ABTestScheduleStrategy();
strategy.addGroup(40, schedule1);
strategy.addGroup(40, schedule2);
strategy.addGroup(20, schedule3);
plan.setStrategy(strategy);
return plan;
}
public static Schedule getSchedule(String label) {
Activity activity = new Activity.Builder().withGuid(BridgeUtils.generateGuid()).withLabel("Test survey")
.withSurvey("identifier", "ABC", TEST_CREATED_ON).build();
Schedule schedule = new Schedule();
schedule.setLabel(label);
schedule.addActivity(activity);
schedule.setScheduleType(ScheduleType.RECURRING);
schedule.setCronTrigger("0 0 8 ? * TUE *");
return schedule;
}
public static JsonNode getClientData() {
try {
String json = TestUtils.createJson("{'booleanFlag':true,'stringValue':'testString','intValue':4}");
return BridgeObjectMapper.get().readTree(json);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static JsonNode getOtherClientData() {
JsonNode clientData = TestUtils.getClientData();
((ObjectNode)clientData).put("newField", "newValue");
return clientData;
}
public static Set<String> getFieldNamesSet(JsonNode node) {
HashSet<String> set = new HashSet<>();
for (Iterator<String> i = node.fieldNames(); i.hasNext(); ) {
set.add(i.next());
}
return set;
}
/**
* Converts single quote marks to double quote marks to convert JSON using single quotes to valid JSON.
* Useful to create more readable inline JSON in tests, because double quotes must be escaped in Java.
*/
public static String createJson(String json) {
return json.replaceAll("'", "\"");
}
public static JsonNode getJson(Result result) throws Exception {
return BridgeObjectMapper.get().readTree(Helpers.contentAsString(result));
}
public static <T> T getResponsePayload(Result result, Class<T> clazz) throws Exception {
return BridgeObjectMapper.get().readValue(Helpers.contentAsString(result), clazz);
}
public static <T> T getResponsePayload(Result result, TypeReference<T> ref) throws Exception {
return BridgeObjectMapper.get().readValue(Helpers.contentAsString(result), ref);
}
public static Criteria createCriteria(Integer minAppVersion, Integer maxAppVersion, Set<String> allOfGroups, Set<String> noneOfGroups) {
DynamoCriteria crit = new DynamoCriteria();
crit.setMinAppVersion(OperatingSystem.IOS, minAppVersion);
crit.setMaxAppVersion(OperatingSystem.IOS, maxAppVersion);
crit.setAllOfGroups(allOfGroups);
crit.setNoneOfGroups(noneOfGroups);
return crit;
}
public static Criteria copyCriteria(Criteria criteria) {
DynamoCriteria crit = new DynamoCriteria();
if (criteria != null) {
crit.setKey(criteria.getKey());
crit.setLanguage(criteria.getLanguage());
for (String osName : criteria.getAppVersionOperatingSystems()) {
crit.setMinAppVersion(osName, criteria.getMinAppVersion(osName));
crit.setMaxAppVersion(osName, criteria.getMaxAppVersion(osName));
}
crit.setNoneOfGroups(criteria.getNoneOfGroups());
crit.setAllOfGroups(criteria.getAllOfGroups());
}
return crit;
}
/**
* Guava does not have a version of this method that also lets you add items.
*/
@SuppressWarnings("unchecked")
public static <T> LinkedHashSet<T> newLinkedHashSet(T... items) {
LinkedHashSet<T> set = new LinkedHashSet<T>();
for (T item : items) {
set.add(item);
}
return set;
}
public static String makeRandomTestEmail(Class<?> cls) {
String devPart = BridgeConfigFactory.getConfig().getUser();
String rndPart = TestUtils.randomName(cls);
return String.format("bridge-testing+%s-%s@sagebase.org", devPart, rndPart);
}
}
|
package org.voltdb.processtools;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import org.voltcore.logging.VoltLogger;
public abstract class ShellTools {
private static VoltLogger log = new VoltLogger("HOST");
private static Process createProcess(String dir, String command[], String passwordScript) {
ProcessBuilder pb = new ProcessBuilder(command);
if (dir != null) {
File wd = new File(dir);
pb.directory(wd);
}
pb.redirectErrorStream(true);
if (passwordScript != null) {
pb.environment().put("SSH_ASKPASS", passwordScript);
}
Process p = null;
try {
p = pb.start();
} catch (IOException e) {
StringBuilder sb = new StringBuilder();
if (command != null) {
for (String c : command) {
sb.append(c).append(" ");
}
}
log.error("Failed to run command " + sb.toString() + ". Error is " + e.getMessage());
return null;
}
return p;
}
public static String cmd(String command) {
return cmd(null, command, null);
}
public static String cmd(String dir, String command) {
return cmd(dir, command, null);
}
public static String cmd(String dir, String command, String input) {
String[] command2 = command.split(" ");
return cmd(dir, command2, input);
}
public static String cmd(String dir, String[] command, String passwordScript) {
StringBuilder retval = new StringBuilder();
Process p = createProcess(dir, command, passwordScript);
if (p == null) {
return null;
}
BufferedInputStream in = new BufferedInputStream(p.getInputStream());
int c;
try {
while((c = in.read()) != -1) {
retval.append((char)c);
}
}
catch (Exception e) {
p.destroy();
}
try {
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
p.destroy();
return retval.toString();
}
public static ProcessData command(String dir, String command[], String passwordScript,
String processName, OutputHandler handler) {
Process p = createProcess(dir, command, passwordScript);
if (p == null) {
return null;
}
return new ProcessData(processName, handler, p);
}
public static boolean cmdToStdOut(String[] command, String passwordScript) {
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
if (passwordScript != null) {
pb.environment().put("SSH_ASKPASS", passwordScript);
}
Process p = null;
try {
p = pb.start();
} catch (IOException e) {
e.printStackTrace();
return false;
}
BufferedInputStream in = new BufferedInputStream(p.getInputStream());
int c;
try {
while((c = in.read()) != -1) {
System.out.print((char)c);
}
}
catch (Exception e) {
p.destroy();
}
try {
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
p.destroy();
return p.exitValue() == 0;
}
public static boolean cmdToStdOut(String command[]) {
return cmdToStdOut( command, null);
}
public static boolean cmdToStdOut(String command, String input) {
String[] command2 = command.split(" ");
return cmdToStdOut(command2, input);
}
public static boolean cmdToStdOut(String command) {
return cmdToStdOut(command, null);
}
public static void main(String[] args) {
System.out.println(cmd("cat build.py"));
}
}
|
package gov.nih.nci.calab.ui.core;
/**
* This class initializes session data to prepopulate the drop-down lists required
* in different view pages.
*
* @author pansu
*/
/* CVS $Id: InitSessionAction.java,v 1.15 2006-04-17 21:41:02 zengje Exp $ */
import gov.nih.nci.calab.dto.administration.AliquotBean;
import gov.nih.nci.calab.dto.administration.ContainerInfoBean;
import gov.nih.nci.calab.dto.security.SecurityBean;
import gov.nih.nci.calab.dto.workflow.ExecuteWorkflowBean;
import gov.nih.nci.calab.service.administration.ManageAliquotService;
import gov.nih.nci.calab.service.administration.ManageSampleService;
import gov.nih.nci.calab.service.common.LookupService;
import gov.nih.nci.calab.service.search.SearchSampleService;
import gov.nih.nci.calab.service.search.SearchWorkflowService;
import gov.nih.nci.calab.service.util.CalabConstants;
import gov.nih.nci.calab.service.util.StringUtils;
import gov.nih.nci.calab.service.workflow.ExecuteWorkflowService;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
public class InitSessionAction extends AbstractBaseAction {
private static Logger logger = Logger.getLogger(InitSessionAction.class);
public ActionForward executeTask(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
ActionForward forward = null;
String forwardPage = null;
String urlPrefix = request.getContextPath();
try {
DynaActionForm theForm = (DynaActionForm) form;
forwardPage = (String) theForm.get("forwardPage");
// retrieve from sesssion first if available assuming these values
// are not likely to change within the same session. If changed, the
// session should be updated.
LookupService lookupService = new LookupService();
if (forwardPage.equals("useAliquot")) {
String runId = (String) request.getParameter("runId");
session.setAttribute("runId", runId);
setUseAliquotSession(session, lookupService);
} else if (forwardPage.equals("createSample")) {
setCreateSampleSession(session, lookupService);
} else if (forwardPage.equals("createAliquot")) {
setCreateAliquotSession(session, lookupService, urlPrefix);
} else if (forwardPage.equals("searchWorkflow")) {
setSearchWorkflowSession(session, lookupService);
} else if (forwardPage.equals("searchSample")) {
setSearchSampleSession(session, lookupService);
} else if (forwardPage.equals("createRun")) {
setCreateRunSession(session, lookupService);
// setUseAliquotSession(session, lookupService);
} else if (forwardPage.equals("workflowMessage")) {
setWorkflowMessageSession(session);
}
// get user and date information
String creator = "";
if (session.getAttribute("user") != null) {
SecurityBean user = (SecurityBean) session.getAttribute("user");
creator = user.getLoginId();
}
String creationDate = StringUtils.convertDateToString(new Date(),
CalabConstants.DATE_FORMAT);
session.setAttribute("creator", creator);
session.setAttribute("creationDate", creationDate);
forward = mapping.findForward(forwardPage);
} catch (Exception e) {
ActionMessages errors = new ActionMessages();
ActionMessage error = new ActionMessage("error.initSession",
forwardPage);
errors.add("error", error);
saveMessages(request, errors);
logger.error(
"Caught exception loading initial drop-down lists data", e);
forward = mapping.getInputForward();
}
return forward;
}
public boolean loginRequired() {
return true;
}
/**
* Set up session attributes for use aliquot page
*
* @param session
* @param lookupService
*/
private void setUseAliquotSession(HttpSession session,
LookupService lookupService) throws Exception {
if (session.getAttribute("allUnmaskedAliquots") == null
|| session.getAttribute("newAliquotCreated") != null) {
List<AliquotBean> allAliquots = lookupService.getUnmaskedAliquots();
session.setAttribute("allUnmaskedAliquots", allAliquots);
}
ExecuteWorkflowService executeWorkflowService = new ExecuteWorkflowService();
if (session.getAttribute("workflow") == null
|| session.getAttribute("newWorkflowCreated") != null) {
ExecuteWorkflowBean workflowBean = executeWorkflowService.getExecuteWorkflowBean();
session.setAttribute("workflow", workflowBean);
}
}
/**
* Set up session attributes for create sample page
*
* @param session
* @param lookupService
*/
private void setCreateSampleSession(HttpSession session,
LookupService lookupService) {
ManageSampleService mangeSampleService = new ManageSampleService();
// if values don't exist in the database or if no new samples created.
// call the service
if (session.getAttribute("allSampleTypes") == null
|| session.getAttribute("newSampleCreated") != null) {
List sampleTypes = lookupService.getAllSampleTypes();
session.setAttribute("allSampleTypes", sampleTypes);
}
if (session.getAttribute("allSampleSOPs") == null
|| session.getAttribute("newSampleCreated") != null) {
List sampleSOPs = mangeSampleService.getAllSampleSOPs();
session.setAttribute("allSampleSOPs", sampleSOPs);
}
if (session.getAttribute("sampleContainerInfo") == null
|| session.getAttribute("newSampleCreated") != null) {
ContainerInfoBean containerInfo = lookupService
.getSampleContainerInfo();
session.setAttribute("sampleContainerInfo", containerInfo);
}
// clear the form in the session
if (session.getAttribute("createSampleForm") != null
|| session.getAttribute("newSampleCreated") != null) {
session.removeAttribute("createSampleForm");
}
// clear the new sample created flag
session.removeAttribute("newSampleCreated");
}
/**
* Set up session attributes for create aliquot page
*
* @param session
* @param lookupService
*/
private void setCreateAliquotSession(HttpSession session,
LookupService lookupService, String urlPrefix) {
ManageAliquotService manageAliquotService = new ManageAliquotService();
if (session.getAttribute("allSamples") == null
|| session.getAttribute("newSampleCreated") != null) {
List samples = lookupService.getAllSamples();
session.setAttribute("allSamples", samples);
}
if (session.getAttribute("allUnmaskedAliquots") == null
|| session.getAttribute("newAliquotCreated") != null) {
List aliquots = lookupService.getUnmaskedAliquots();
session.setAttribute("allUnmaskedAliquots", aliquots);
}
if (session.getAttribute("aliquotContainerInfo") == null
|| session.getAttribute("newAliquotCreated") != null) {
ContainerInfoBean containerInfo = lookupService
.getAliquotContainerInfo();
session.setAttribute("aliquotContainerInfo", containerInfo);
}
if (session.getAttribute("aliquotCreateMethods") == null) {
List methods = manageAliquotService
.getAliquotCreateMethods(urlPrefix);
session.setAttribute("aliquotCreateMethods", methods);
}
// clear the form in the session
if (session.getAttribute("createAliquotForm") != null) {
session.removeAttribute("createAliquotForm");
}
if (session.getAttribute("aliquotMatrix") != null) {
session.removeAttribute("aliquotMatrix");
}
// clear new aliquot created flag and new sample created flag
session.removeAttribute("newAliquotCreated");
session.removeAttribute("newSampleCreated");
}
/**
* Set up session attributes for search workflow page
*
* @param session
* @param lookupService
*/
private void setSearchWorkflowSession(HttpSession session,
LookupService lookupService) {
SearchWorkflowService searchWorkflowService = new SearchWorkflowService();
if (session.getAttribute("allUnmaskedAliquots") == null) {
List<AliquotBean> allAliquots = lookupService.getUnmaskedAliquots();
session.setAttribute("allUnmaskedAliquots", allAliquots);
}
if (session.getAttribute("allAssayTypes") == null) {
List assayTypes = lookupService.getAllAssayTypes();
session.setAttribute("allAssayTypes", assayTypes);
}
if (session.getAttribute("allFileSubmitters") == null) {
List submitters = searchWorkflowService.getAllFileSubmitters();
session.setAttribute("allFileSubmitters", submitters);
}
}
/**
* Set up session attributes for search sample page
*
* @param session
* @param lookupService
*/
private void setSearchSampleSession(HttpSession session,
LookupService lookupService) {
SearchSampleService searchSampleService = new SearchSampleService();
if (session.getAttribute("allSamples") == null
|| session.getAttribute("newSampleCreated") != null) {
List samples = lookupService.getAllSamples();
session.setAttribute("allSamples", samples);
}
if (session.getAttribute("allAliquots") == null
|| session.getAttribute("newAliquotCreated") != null) {
List aliquots = lookupService.getAliquots();
session.setAttribute("allAliquots", aliquots);
}
if (session.getAttribute("allSampleTypes") == null
|| session.getAttribute("newSampleCreated") != null) {
List sampleTypes = lookupService.getAllSampleTypes();
session.setAttribute("allSampleTypes", sampleTypes);
}
if (session.getAttribute("allSampleSources") == null
|| session.getAttribute("newSampleCreated") != null) {
List sampleSources = searchSampleService.getAllSampleSources();
session.setAttribute("allSampleSources", sampleSources);
}
if (session.getAttribute("allSourceSampleIds") == null
|| session.getAttribute("newSampleCreated") != null) {
List sourceSampleIds = searchSampleService.getAllSourceSampleIds();
session.setAttribute("allSourceSampleIds", sourceSampleIds);
}
if (session.getAttribute("allSampleSubmitters") == null
|| session.getAttribute("newSampleCreated") != null) {
List submitters = searchSampleService.getAllSampleSubmitters();
session.setAttribute("allSampleSubmitters", submitters);
}
if (session.getAttribute("sampleContainerInfo") == null
|| session.getAttribute("newSampleCreated") != null) {
ContainerInfoBean containerInfo = lookupService
.getSampleContainerInfo();
session.setAttribute("sampleContainerInfo", containerInfo);
}
if (session.getAttribute("aliquotContainerInfo") == null
|| session.getAttribute("newAliquotCreated") != null) {
ContainerInfoBean containerInfo = lookupService
.getAliquotContainerInfo();
session.setAttribute("aliquotContainerInfo", containerInfo);
}
// clear new aliquot created flag and new sample created flag
session.removeAttribute("newAliquotCreated");
session.removeAttribute("newSampleCreated");
// clear session attributes created during search sample
session.removeAttribute("samples");
session.removeAttribute("aliquots");
}
/**
* Set up session attributes for create Run
*
* @param session
* @param lookupService
*/
private void setCreateRunSession(HttpSession session,
LookupService lookupService) throws Exception {
ExecuteWorkflowService executeWorkflowService = new ExecuteWorkflowService();
if (session.getAttribute("allAssayTypes") == null) {
List assayTypes = lookupService.getAllAssayTypes();
session.setAttribute("allAssayTypes", assayTypes);
}
if (session.getAttribute("workflow") == null
|| session.getAttribute("newWorkflowCreated") != null) {
ExecuteWorkflowBean workflowBean = executeWorkflowService.getExecuteWorkflowBean();
session.setAttribute("workflow", workflowBean);
}
if (session.getAttribute("allUnmaskedAliquots") == null
|| session.getAttribute("newAliquotCreated") != null) {
List aliquots = lookupService.getUnmaskedAliquots();
session.setAttribute("allUnmaskedAliquots", aliquots);
}
if (session.getAttribute("allAvailableAliquots") == null) {
List<AliquotBean> allAvailableAliquots = lookupService.getUnmaskedAliquots();
session.setAttribute("allAvailableAliquots", allAvailableAliquots);
}
if (session.getAttribute("allAssignedAliquots") == null) {
List allAssignedAliquots = lookupService.getAllAssignedAliquots();
session.setAttribute("allAssignedAliquots", allAssignedAliquots);
}
if (session.getAttribute("allInFiles") == null) {
List allInFiles = lookupService.getAllInFiles();
session.setAttribute("allInFiles", allInFiles);
}
if (session.getAttribute("allOutFiles") == null) {
List allOutFiles = lookupService.getAllOutFiles();
session.setAttribute("allOutFiles", allOutFiles);
}
if (session.getAttribute("allAssayBeans") == null) {
List allAssayBeans = lookupService.getAllAssayBeans();
session.setAttribute("allAssayBeans", allAssayBeans);
}
session.removeAttribute("newWorkflowCreated");
session.removeAttribute("newAliquotCreated");
}
private void setWorkflowMessageSession(HttpSession session) throws Exception{
ExecuteWorkflowService executeWorkflowService = new ExecuteWorkflowService();
if (session.getAttribute("workflow") == null
|| session.getAttribute("newWorkflowCreated") != null) {
ExecuteWorkflowBean workflowBean = executeWorkflowService.getExecuteWorkflowBean();
session.setAttribute("workflow", workflowBean);
}
session.removeAttribute("newWorkflowCreated");
}
}
|
package org.lockss.plugin;
import java.io.*;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.*;
import java.lang.reflect.*;
import java.util.zip.*;
import org.apache.commons.lang3.arch.Processor;
import org.lockss.test.*;
import org.lockss.daemon.*;
import org.lockss.plugin.simulated.*;
import org.lockss.util.*;
import org.lockss.app.*;
import org.lockss.config.*;
/**
* Utilities for manipulating plugins and their components in tests
*/
public class PluginTestUtil {
static Logger log = Logger.getLogger("PluginTestUtil");
static List aulist = new LinkedList();
public static void registerArchivalUnit(Plugin plug, ArchivalUnit au) {
PluginManager mgr = getPluginManager();
log.debug3(mgr.toString());
String plugid = au.getPluginId();
log.debug("registerArchivalUnit plugin = " + plug +
"au = " + au);
if (plug != mgr.getPlugin(plugid)) {
try {
PrivilegedAccessor.invokeMethod(mgr, "setPlugin",
ListUtil.list(plugid, plug).toArray());
} catch (Exception e) {
log.error("Couldn't register AU", e);
throw new RuntimeException(e.toString());
}
}
PluginTestable tp = (PluginTestable)plug;
tp.registerArchivalUnit(au);
try {
PrivilegedAccessor.invokeMethod(mgr, "putAuInMap",
ListUtil.list(au).toArray());
} catch (InvocationTargetException e) {
log.error("Couldn't register AU", e);
log.error("Nested", e.getTargetException());
throw new RuntimeException(e.toString());
} catch (Exception e) {
log.error("Couldn't register AU", e);
throw new RuntimeException(e.toString());
}
aulist.add(au);
}
public static void registerArchivalUnit(ArchivalUnit au) {
PluginManager mgr = getPluginManager();
String plugid = au.getPluginId();
Plugin plug = mgr.getPlugin(plugid);
log.debug("registerArchivalUnit id = " + au.getAuId() +
", pluginid = " + plugid + ", plugin = " + plug);
if (plug == null) {
MockPlugin mp = new MockPlugin();
mp.setPluginId(plugid);
plug = mp;
}
registerArchivalUnit(plug, au);
}
/*
public static void registerArchivalUnit(ArchivalUnit au) {
PluginManager mgr = getPluginManager();
log.debug(mgr.toString());
String plugid = au.getPluginId();
Plugin plug = mgr.getPlugin(plugid);
log.debug("registerArchivalUnit id = " + au.getAuId() +
", pluginid = " + plugid + ", plugin = " + plug);
if (plug == null) {
MockPlugin mp = new MockPlugin();
mp.setPluginId(plugid);
plug = mp;
try {
PrivilegedAccessor.invokeMethod(mgr, "setPlugin",
ListUtil.list(plugid, mp).toArray());
} catch (Exception e) {
log.error("Couldn't register AU", e);
throw new RuntimeException(e.toString());
}
}
PluginTestable tp = (PluginTestable)plug;
tp.registerArchivalUnit(au);
try {
PrivilegedAccessor.invokeMethod(mgr, "putAuMap",
ListUtil.list(plug, au).toArray());
} catch (Exception e) {
log.error("Couldn't register AU", e);
throw new RuntimeException(e.toString());
}
aulist.add(au);
}
*/
public static void unregisterArchivalUnit(ArchivalUnit au) {
PluginManager mgr = getPluginManager();
String plugid = au.getPluginId();
Plugin plug = mgr.getPlugin(plugid);
if (plug != null) {
PluginTestable tp = (PluginTestable)plug;
tp.unregisterArchivalUnit(au);
aulist.remove(au);
}
mgr.stopAu(au, new AuEvent(AuEvent.Type.Delete, false));
}
public static void unregisterAllArchivalUnits() {
log.debug("unregisterAllArchivalUnits()");
List aus = new ArrayList(aulist);
for (Iterator iter = aus.iterator(); iter.hasNext(); ) {
unregisterArchivalUnit((ArchivalUnit)iter.next());
}
}
public static Plugin findPlugin(String pluginName) {
PluginManager pluginMgr = getPluginManager();
String key = pluginMgr.pluginKeyFromName(pluginName);
pluginMgr.ensurePluginLoaded(key);
return pluginMgr.getPlugin(key);
}
public static Plugin findPlugin(Class pluginClass) {
return findPlugin(pluginClass.getName());
}
public static ArchivalUnit createAu(Plugin plugin,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return getPluginManager().createAu(plugin, auConfig,
new AuEvent(AuEvent.Type.Create, false));
}
public static ArchivalUnit createAndStartAu(Plugin plugin,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return startAu(createAu(plugin, auConfig));
}
static ArchivalUnit startAu(ArchivalUnit au) {
LockssDaemon daemon = au.getPlugin().getDaemon();
daemon.getHistoryRepository(au).startService();
daemon.getLockssRepository(au).startService();
daemon.getNodeManager(au).startService();
return au;
}
public static ArchivalUnit createAu(String pluginName,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return createAu(findPlugin(pluginName), auConfig);
}
public static ArchivalUnit createAndStartAu(String pluginName,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return createAndStartAu(findPlugin(pluginName), auConfig);
}
public static ArchivalUnit createAu(Class pluginClass,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return createAu(findPlugin(pluginClass.getName()), auConfig);
}
public static ArchivalUnit createAndStartAu(Class pluginClass,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return createAndStartAu(findPlugin(pluginClass.getName()), auConfig);
}
public static SimulatedArchivalUnit createSimAu(Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return (SimulatedArchivalUnit)createAu(findPlugin(SimulatedPlugin.class),
auConfig);
}
static Configuration getAuConfig(TdbAu tau) {
PluginManager mgr = getPluginManager();
Plugin plugin = tau.getPlugin(mgr);
TitleConfig tc = new TitleConfig(tau, plugin);
return tc.getConfig();
}
public static ArchivalUnit createAu(TdbAu tau)
throws ArchivalUnit.ConfigurationException {
PluginManager mgr = getPluginManager();
Plugin plugin = findPlugin(tau.getPluginId());
return createAu(plugin, getAuConfig(tau));
}
public static ArchivalUnit createAu(Plugin plugin, TdbAu tau)
throws ArchivalUnit.ConfigurationException {
return createAu(plugin, getAuConfig(tau));
}
public static ArchivalUnit createAndStartAu(TdbAu tau)
throws ArchivalUnit.ConfigurationException {
return startAu(createAu(tau));
}
public static ArchivalUnit createAndStartAu(Plugin plugin, TdbAu tau)
throws ArchivalUnit.ConfigurationException {
return startAu(createAu(plugin, tau));
}
public static SimulatedArchivalUnit
createAndStartSimAu(Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return createAndStartSimAu(SimulatedPlugin.class, auConfig);
}
public static SimulatedArchivalUnit
createAndStartSimAu(Class pluginClass, Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return (SimulatedArchivalUnit)createAndStartAu(pluginClass, auConfig);
}
public static void crawlSimAu(SimulatedArchivalUnit sau) {
if (!sau.hasContentTree()) {
// log.debug("Creating simulated content tree: " + sau.getParamMap());
sau.generateContentTree();
}
log.debug("Crawling simulated content");
NoCrawlEndActionsFollowLinkCrawler crawler =
new NoCrawlEndActionsFollowLinkCrawler(sau, new MockAuState());
//crawler.setCrawlManager(crawlMgr);
crawler.doCrawl();
}
/**
* {@code ifMatch, patRepPairs} defaults to {null}.
* {@code fromAu} defaults to {fromAu.getCachedUrlSet()}.
*
* @see PluginTestUtil#copyCus(CachedUrlSet, ArchivalUnit, String, List)
*/
public static boolean copyAu(ArchivalUnit fromAu, ArchivalUnit toAu) throws MalformedURLException {
return copyAu(fromAu, toAu, null, null, null);
}
/**
* {@code patRepPairs} defaults to {null}.
* {@code fromAu} defaults to {fromAu.getCachedUrlSet()}.
*
* @see PluginTestUtil#copyCus(CachedUrlSet, ArchivalUnit, String, List)
*/
public static boolean copyAu(ArchivalUnit fromAu, ArchivalUnit toAu, String ifMatch) throws MalformedURLException {
return copyAu(fromAu, toAu, ifMatch, null, null);
}
/**
* {@code pat, rep} converted to {PatternReplacements}.
* {@code fromAu} defaults to {fromAu.getCachedUrlSet()}.
*
* @see PluginTestUtil#copyCus(CachedUrlSet, ArchivalUnit, String, List)
*/
public static boolean copyAu(ArchivalUnit fromAu, ArchivalUnit toAu,
String ifMatch, String pat, String rep) throws MalformedURLException {
return copyCus(fromAu.getAuCachedUrlSet(), toAu, ifMatch, pat, rep);
}
/**
* {@code fromAu} defaults to {fromAu.getCachedUrlSet()}.
*
* @see PluginTestUtil#copyCus(CachedUrlSet, ArchivalUnit, String, List)
*/
public static boolean copyAu(ArchivalUnit fromAu,
ArchivalUnit toAu,
String ifMatch,
List<PatternReplacements> patRepPairs) throws MalformedURLException {
return copyCus(fromAu.getAuCachedUrlSet(), toAu, ifMatch, patRepPairs);
}
/**
* {@code ifMatch, patRepPairs} defaults to {null}.
*
* @see PluginTestUtil#copyCus(CachedUrlSet, ArchivalUnit, String, List)
*/
public static boolean copyCus(CachedUrlSet fromCus, ArchivalUnit toAu) {
return copyCus(fromCus, toAu, null, null, null);
}
/**
* {@code pat, rep} converted to {PatternReplacements}.
*
* @param pat a regex used to match files in the simulated crawl
* @param rep regex replacement pattern(s) to rename the original file.
* @see PluginTestUtil#copyCus(CachedUrlSet, ArchivalUnit, String, List)
*/
public static boolean copyCus(CachedUrlSet fromCus, ArchivalUnit toAu,
String ifMatch, String pat, String rep) {
List<PatternReplacements> patRepPairs;
if (pat == null) {
patRepPairs = null;
} else {
patRepPairs = Collections.singletonList(new PatternReplacements(pat, rep));
}
return copyCus(fromCus, toAu, ifMatch, patRepPairs);
}
/**
* Utility to copy files from a simulated crawl to a mock archival unit.
* For each file matched by ifMatch, the first Pattern matched will be copied for as many
* replacements as are associated with it.
* If only fromAu and toAu are provided, all files are copied without modification.
*
* @param fromCus the CachedUrlSet which has been crawled
* @param toAu the Archival Unit to copy content to
* @param ifMatch String, a regex to check on the url before pattern replacement transforming. e.g. .zip
* @param patRepPairs A List of PatternReplacements to rename files from matched patterns to replacements.
* @return true, if all copies attempted succeeded, false otherwise
*/
public static boolean copyCus(CachedUrlSet fromCus, ArchivalUnit toAu,
String ifMatch, List<PatternReplacements> patRepPairs) {
boolean res = true;
Pattern ifMatchPat = null;
if (ifMatch != null) {
ifMatchPat = Pattern.compile(ifMatch);
}
ArchiveFileTypes aft = toAu.getArchiveFileTypes();
for (CachedUrl cu : fromCus.getCuIterable()) {
try {
String fromUrl = cu.getUrl();
String toUrl = fromUrl;
if (ifMatchPat != null) {
Matcher mat = ifMatchPat.matcher(fromUrl);
if (!mat.find()) {
log.debug3("no match: " + fromUrl + ", " + ifMatchPat);
continue;
}
}
String isArchive = null;
if (aft != null) {
isArchive = aft.getFromCu(cu);
}
if (isArchive == null) {
if (patRepPairs != null) {
for (PatternReplacements prp : patRepPairs) {
Matcher mat = prp.pat.matcher(fromUrl);
if (mat.find()) {
for (String rep : prp.rep) {
toUrl = mat.replaceAll(rep);
doCopyCu(cu, toAu, fromUrl, toUrl);
}
break;
}
}
} else {
doCopyCu(cu, toAu, fromUrl, toUrl);
}
} else {
switch (isArchive) {
case ".zip":
copyZip(cu, toAu, patRepPairs);
break;
case ".tar":
//TODO
// com.ice.tar.TarInputStream
log.info("support for .tar coming");
throw new Exception("support for .tar coming");
//break;
case ".tar.gz":
case ".tgz":
//TODO
// double wrap - unwrap gzip, then TarInputStream
log.info("support for .tgz coming");
throw new Exception("support for .tgz coming");
//break;
default:
throw new Exception("Unexpected Archive file type: '" + isArchive + "'");
}
}
} catch (Exception e) {
log.error("Couldn't copy " + cu.getUrl(), e);
res = false;
} finally {
cu.release();
}
}
return res;
}
private static void doCopyCu(CachedUrl cu,
ArchivalUnit toAu,
String fromUrl,
String toUrl
) throws IOException {
doCopyCu(cu.getUnfilteredInputStream(), cu.getProperties(), toAu, fromUrl, toUrl);
}
private static void doCopyCu(InputStream is,
CIProperties props,
ArchivalUnit toAu,
String fromUrl,
String toUrl
) throws IOException {
if (props == null) {
log.debug3("in copyCus() props was null for url: " + fromUrl);
}
UrlCacher uc = toAu.makeUrlCacher(
new UrlData(is, props, toUrl));
uc.storeContent();
if (!toUrl.equals(fromUrl)) {
log.info("Copied " + fromUrl + " to " + toUrl);
} else {
log.debug2("Copied " + fromUrl);
}
}
/**
* Opens a single CachedUrl zip file, iterates over its contents and copies the contents if they pass
* given pattern(s) and replacements.
*
* Note: replacement(s) can rename the zip file, but all zip files should be the same in the replacement string(s)
*
* @param cu A CachedUrl of compressed content.
* @param toAu The ArchivalUnit to copy the cu into.
* @param patRepPairs A List of PatternReplacementss to selectively copy zipped content and rename it in the new zip.
* @throws IOException When I/O zip files encounter any number of problems.
*/
private static void copyZip(CachedUrl cu, ArchivalUnit toAu, List<PatternReplacements> patRepPairs)
throws IOException {
boolean doCache = false;
String tempZipName = "temp.zip";
ArchiveMemberSpec zipSpec = ArchiveMemberSpec.fromCu(cu, null);
String outZip = null;
ZipInputStream zis = null;
try {
InputStream cuis = new ReaderInputStream(cu.openForReading());
zis = new ZipInputStream(cuis);
ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(
Paths.get(cu.getArchivalUnit().getProperties().getString("root") + tempZipName)));
zos.setMethod(ZipOutputStream.DEFLATED);
zos.setLevel(Deflater.BEST_COMPRESSION);
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (entry.isDirectory()) {
continue;
} else if (entry.getName().endsWith(".zip") ) {
// TODO recurse through nested
// zipCopy(cu, toAu, zipUrl + );
}
ArchiveMemberSpec fromZipped = ArchiveMemberSpec.fromCu(cu, entry.getName());
if (patRepPairs == null) {
doCache = true;
doCopyZipEntry(zos, zis, fromZipped.toUrl());
outZip = fromZipped.getName();
} else {
for (PatternReplacements prp : patRepPairs) {
Matcher mat = prp.pat.matcher(fromZipped.toUrl());
if (mat.find()) {
for (String rep : prp.rep) {
ArchiveMemberSpec toZipped = ArchiveMemberSpec.fromUrl(toAu, mat.replaceAll(rep));
assert toZipped != null;
if (!toZipped.toUrl().equals(fromZipped.toUrl())) {
log.debug("Found a zipped file match: " + fromZipped.toUrl() + " -> " + toZipped.toUrl());
doCache = true;
doCopyZipEntry(zos, zis, toZipped.toUrl());
outZip = toZipped.getUrl();
}
}
break;
}
}
}
}
zos.close();
// any copied file triggers saving the new zip stream
// the output file name is parsed from the matched file
// it will be the last matched-replaced file.
if (doCache) {
FileInputStream is = new FileInputStream(
new File(cu.getArchivalUnit().getProperties().getString("root"), tempZipName));
// save all the copied zip entries to a new zip on the toAu
doCopyCu(is, cu.getProperties(), toAu, zipSpec.getUrl(), outZip);
is.close();
}
} finally {
IOUtil.safeClose(zis);
}
}
private static void doCopyZipEntry(ZipOutputStream zos, ZipInputStream zis, String toUrl) throws IOException {
String toFile = toUrl.split("!/")[1];
ZipEntry outEntry = new ZipEntry(toFile);
zos.putNextEntry(outEntry);
StreamUtil.copy(zis, zos);
zos.closeEntry();
}
public static List<String> urlsOf(final Iterable<CachedUrl> cus) {
return new ArrayList<String>() {{
for (CachedUrl cu : cus) {
add(cu.getUrl());
}
}};
}
private static PluginManager getPluginManager() {
return
(PluginManager)LockssDaemon.getManager(LockssDaemon.PLUGIN_MANAGER);
}
public static PatternReplacements makePatRep(String pat, String... rep) {
return new PatternReplacements(pat , rep);
}
public static class PatternReplacements {
public Pattern pat;
public String[] rep;
/**
* Simple Container class for Regex pattern -> Replacement associations.
* @param pat String regex, gets compiled to a Pattern
* @param rep Replacement string
*/
PatternReplacements(String pat, String... rep) {
this.pat = Pattern.compile(pat, Pattern.CASE_INSENSITIVE);
this.rep = rep;
}
}
}
|
/*
* $Id: TestMetadataUtil.java,v 1.13 2014-08-29 20:56:22 pgust Exp $
*/
package org.lockss.util;
import java.util.*;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import org.apache.commons.lang.LocaleUtils;
import org.lockss.test.*;
public class TestMetadataUtil extends LockssTestCase {
void assertLocale(String lang, Locale l) {
assertEquals("Language", lang, l.getLanguage());
}
void assertLocale(String lang, String country, Locale l) {
assertEquals("Language", lang, l.getLanguage());
assertEquals("Country", country, l.getCountry());
}
void assertLocale(String lang, String country, String variant, Locale l) {
assertEquals("Language", lang, l.getLanguage());
assertEquals("Country", country, l.getCountry());
assertEquals("Variant", variant, l.getVariant());
}
static Set<Locale> testLocales =
SetUtil.set(
new Locale("aa"),
new Locale("bb"),
new Locale("bb", "XX"),
new Locale("cc"),
new Locale("cc", "XX"),
new Locale("cc", "YY"),
new Locale("cc", "XX", "V1"),
new Locale("dd", "WW"),
new Locale("ee", "WW", "V3")
);
String findClosestLocale(String str) {
Locale l = MetadataUtil.findClosestLocale(LocaleUtils.toLocale(str),
testLocales);
return l != null ? l.toString() : null;
}
String findClosestAvailableLocale(String str) {
Locale l =
MetadataUtil.findClosestAvailableLocale(LocaleUtils.toLocale(str));
return l != null ? l.toString() : null;
}
public void testFindClosestLocale() {
assertEquals("aa", findClosestLocale("aa"));
assertEquals("aa", findClosestLocale("aa_XX"));
assertEquals("aa", findClosestLocale("aa_XX_V1"));
assertEquals("bb", findClosestLocale("bb"));
assertEquals("bb_XX", findClosestLocale("bb_XX"));
assertEquals("bb_XX", findClosestLocale("bb_XX_V1"));
assertEquals("bb", findClosestLocale("bb_YY"));
assertEquals("bb", findClosestLocale("bb_YY_V1"));
assertEquals("cc", findClosestLocale("cc"));
assertEquals("cc_XX", findClosestLocale("cc_XX"));
assertEquals("cc_XX_V1", findClosestLocale("cc_XX_V1"));
assertEquals("cc_XX", findClosestLocale("cc_XX_V2"));
assertEquals("cc", findClosestLocale("cc_ZZ"));
assertEquals("cc_YY", findClosestLocale("cc_YY"));
assertEquals("cc_YY", findClosestLocale("cc_YY_V1"));
assertEquals("cc_YY", findClosestLocale("cc_YY_V2"));
assertEquals(null, findClosestLocale("xx"));
assertEquals(null, findClosestLocale("xx_XX"));
assertEquals(null, findClosestLocale("xx_XX_V1"));
assertEquals("dd_WW", findClosestLocale("dd_WW"));
assertEquals(null, findClosestLocale("dd_VV"));
assertEquals("ee_WW_V3", findClosestLocale("ee_WW_V3"));
assertEquals(null, findClosestLocale("ee_WW_V4"));
assertEquals(null, findClosestLocale("ee_VV"));
}
// Java spec says Locale.US must exist; still not sure this will succeed
// in all environments
public void testFindClosestAvailableLocale() {
assertEquals("en", findClosestAvailableLocale("en"));
assertEquals("en", findClosestAvailableLocale("en_ZF"));
assertEquals("en_US", findClosestAvailableLocale("en_US"));
}
static Locale DEF_LOC = MetadataUtil.DEFAULT_DEFAULT_LOCALE;
public void testConfigDefaultLocale() {
assertEquals(DEF_LOC, MetadataUtil.getDefaultLocale());
ConfigurationUtil.setFromArgs(MetadataUtil.PARAM_DEFAULT_LOCALE, "fr_CA");
assertLocale("fr", "CA", MetadataUtil.getDefaultLocale());
ConfigurationUtil.setFromArgs(MetadataUtil.PARAM_DEFAULT_LOCALE, "");
assertEquals(DEF_LOC, MetadataUtil.getDefaultLocale());
}
private String validISBN10s [] = {
"99921-58-10-7",
"9971-5-0210-0",
"80-902734-1-6",
"85-359-0277-5",
"1-84356-028-3",
"0-684-84328-5",
"0-8044-2957-X",
"0-85131-041-9",
"0-943396-04-2"
};
private String invalidISBN10s[] = {
"99921-48-10-7",
"9971-5-0110-0",
"80-902735-1-6",
"85-359-0278-5",
"1-84356-028-2",
"0-684-83328-5",
"0-8044-2757-X",
"0-85131-042-9",
"0-943396-14-2"
};
private String validISBN13s [] = {
"978-99921-58-10-4",
"978-9971-5-0210-2",
"978-80-902734-1-2",
"978-85-359-0277-8",
"978-1-84356-028-9",
"978-0-684-84328-5",
"978-0-8044-2957-3",
"978-0-85131-041-1",
"978-0-943396-04-0"
};
private String invalidISBN13s[] = {
"978-99931-58-10-4",
"978-9971-5-0200-2",
"978-80-901734-1-2",
"978-85-359-1277-8",
"978-1-84356-128-9",
"978-0-682-84328-5",
"978-0-8043-2957-3",
"978-0-85130-041-1",
"978-0-942396-04-0"
};
private String malformedISBNs[] = {
"X78-99931-58-10-4",
"X9921-48-10-7",
"0-8044-2957-Z",
"1234-5678",
};
private String validISSNS [] = {
"1144-875X",
"1543-8120",
"1508-1109",
"1733-5329",
"0740-2783",
"0097-4463",
"1402-2001",
"1523-0430",
"1938-4246",
"0006-3363"
};
private String invalidISSNS [] = {
"1144-175X",
"1144-8753",
"1543-8122",
"1541-8120",
"1508-1409",
"2740-2783"
};
private String malformedISSNS [] = {
"140-42001",
"15236-430",
"1402-200",
"1938/4246",
"1402",
"1402-",
"-4246"
};
private String validDOIS [] = {
"10.1095/biolreprod.106.054056",
"10.2992/007.078.0301",
"10.1206/606.1",
"10.1640/0002-8444-99.2.61",
"10.1663/0006-8101(2007)73[267:TPOSRI]2.0.CO;2",
"10.1663/0006-8101(2007)73[267%3ATPOSRI]2.0.CO%3B2",
"10.1640/0002-8444/99.2.61",
"10.1635a/006-8101",
"10.166356/006-8101"
};
private String invalidDOIS [] = {
"12.1095/biolreprod.106.054056",
"10.2992-007.078.0301",
"10.1206",
"/0002-8444-99.2.61",
"-0002-8444-99.2.61",
"10.2992007/078.0301",
null
};
public void testISBN() {
// valid with checksum calculations
for(int i=0; i<validISBN10s.length;i++) {
assertTrue(MetadataUtil.isIsbn(validISBN10s[i], true));
}
// malformed ISBN
for(int i=0; i<malformedISBNs.length;i++){
assertFalse(MetadataUtil.isIsbn(malformedISBNs[i], false));
}
// invalid with checksum calculations
for(int i=0; i<invalidISBN10s.length;i++){
assertFalse(MetadataUtil.isIsbn(invalidISBN10s[i], true));
}
// valid ignoring checksum calculations
for(int i=0; i<invalidISBN10s.length;i++){
assertTrue(MetadataUtil.isIsbn(invalidISBN10s[i], false));
}
// valid with checksum calculations
for(int i=0; i<validISBN13s.length;i++){
assertTrue(MetadataUtil.isIsbn(validISBN13s[i], true));
}
// invalid with checksum calculations
for(int i=0; i<invalidISBN13s.length;i++){
assertFalse(MetadataUtil.isIsbn(invalidISBN13s[i], true));
}
// valid ignoring checksum calculation
for(int i=0; i<invalidISBN13s.length;i++){
assertTrue(MetadataUtil.isIsbn(invalidISBN13s[i], false));
}
// Knuth vol 4A 1st edition
// test ISBN conversions with correct check digit
assertEquals("0201038048", MetadataUtil.toUnpunctuatedIsbn10("978-0-201-03804-0"));
assertEquals("0201038048", MetadataUtil.toUnpunctuatedIsbn10("9780201038040"));
assertEquals("0201038048", MetadataUtil.toUnpunctuatedIsbn10("0-201-03804-8"));
assertEquals("0201038048", MetadataUtil.toUnpunctuatedIsbn10("0201038048"));
assertEquals("9780201038040", MetadataUtil.toUnpunctuatedIsbn13("978-0-201-03804-0"));
assertEquals("9780201038040", MetadataUtil.toUnpunctuatedIsbn13("9780201038040"));
assertEquals("9780201038040", MetadataUtil.toUnpunctuatedIsbn13("0-201-03804-8"));
assertEquals("9780201038040", MetadataUtil.toUnpunctuatedIsbn13("0201038048"));
// test ISBN conversions with incorrect check digit
assertEquals("0201038048", MetadataUtil.toUnpunctuatedIsbn10("978-0-201-03804-7"));
assertEquals("0201038048", MetadataUtil.toUnpunctuatedIsbn10("9780201038047"));
assertEquals("020103804X", MetadataUtil.toUnpunctuatedIsbn10("0-201-03804-X"));
assertEquals("020103804X", MetadataUtil.toUnpunctuatedIsbn10("020103804X"));
assertEquals("9780201038040", MetadataUtil.toUnpunctuatedIsbn13("978-0-201-03804-0"));
assertEquals("9780201038040", MetadataUtil.toUnpunctuatedIsbn13("9780201038040"));
assertEquals("9780201038040", MetadataUtil.toUnpunctuatedIsbn13("0-201-03804-X"));
assertEquals("9780201038040", MetadataUtil.toUnpunctuatedIsbn13("020103804X"));
// test ISBN-10 conversions with invalid input ISBN-13
assertNull(MetadataUtil.toUnpunctuatedIsbn10("978-X-201-03804-0"));
assertNull(MetadataUtil.toUnpunctuatedIsbn10("9780X01038040"));
assertNull(MetadataUtil.toUnpunctuatedIsbn10("xyzzy"));
// test ISBN-13 conversions with invalid input ISBN-10
assertNull(MetadataUtil.toUnpunctuatedIsbn13("0-2X1-03804-8"));
assertNull(MetadataUtil.toUnpunctuatedIsbn13("02X1038048"));
assertNull(MetadataUtil.toUnpunctuatedIsbn13("xyzzy"));
// test ISBN formatting
assertEquals("978-0-201-03804-0", MetadataUtil.formatIsbn("9780201038040"));
assertEquals("0-201-03804-8", MetadataUtil.formatIsbn("0201038048"));
assertEquals("xyzzy", MetadataUtil.formatIsbn("xyzzy"));
}
public void testISSN() {
for(int i=0; i<validISSNS.length;i++){
String validIssn = validISSNS[i];
assertTrue(MetadataUtil.isIssn(validIssn));
assertEquals(validIssn, MetadataUtil.validateIssn(validIssn));
}
for(int j=0; j<malformedISSNS.length;j++){
String malformedIssn = malformedISSNS[j];
assertFalse(MetadataUtil.isIssn(malformedIssn));
assertEquals(null, MetadataUtil.validateIssn(malformedIssn));
}
// invalid with checksum calculations
for(int j=0; j<invalidISSNS.length;j++){
String invalidIssn = invalidISSNS[j];
assertFalse(MetadataUtil.isIssn(invalidISSNS[j], true));
assertEquals(null, MetadataUtil.validateIssn(invalidIssn, true));
}
// valid ignoring checksum calculations
for(int j=0; j<invalidISSNS.length;j++){
String invalidIssn = invalidISSNS[j];
assertTrue(MetadataUtil.isIssn(invalidIssn, false));
assertEquals(invalidIssn, MetadataUtil.validateIssn(invalidIssn, false));
}
// test ISSN formatting functions
assertEquals("1234-5678", MetadataUtil.formatIssn("12345678"));
assertEquals("xyzzy", MetadataUtil.formatIssn("xyzzy"));
}
public void testDOI() throws UnsupportedEncodingException {
for(int i=0; i<validDOIS.length;i++){
assertTrue(MetadataUtil.isDoi(URLDecoder.decode(validDOIS[i], Constants.ENCODING_UTF_8)));
}
for(int j=0; j<invalidDOIS.length;j++){
assertFalse(MetadataUtil.isDoi(invalidDOIS[j]));
}
}
}
|
// $Id: DSetEditor.java,v 1.10 2004/11/06 01:59:24 ray Exp $
// Narya library - tools for developing networked games
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.admin.client;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Field;
import java.util.BitSet;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import com.samskivert.swing.ObjectEditorTable;
import com.samskivert.swing.event.CommandEvent;
import com.samskivert.util.ClassUtil;
import com.samskivert.util.ListUtil;
import com.samskivert.util.SortableArrayList;
import com.threerings.media.SafeScrollPane;
import com.threerings.presents.Log;
import com.threerings.presents.dobj.AttributeChangeListener;
import com.threerings.presents.dobj.AttributeChangedEvent;
import com.threerings.presents.dobj.DObject;
import com.threerings.presents.dobj.DSet;
import com.threerings.presents.dobj.EntryAddedEvent;
import com.threerings.presents.dobj.EntryRemovedEvent;
import com.threerings.presents.dobj.EntryUpdatedEvent;
import com.threerings.presents.dobj.SetListener;
/**
* Allows simple editing of DSets within a distributed object.
*/
public class DSetEditor extends JPanel
implements AttributeChangeListener, SetListener, ActionListener
{
/**
* Construct a DSet editor to merely display the specified set.
*
* @param setter The object that contains the set.
* @param setName The name of the set in the object.
* @param entryClass the Class of the DSet.Entry elements contained in the
* set.
*/
public DSetEditor (DObject setter, String setName, Class entryClass)
{
this(setter, setName, entryClass, null);
}
/**
* Construct a DSetEditor, allowing the specified fields to be edited.
*
* @param setter The object that contains the set.
* @param setName The name of the set in the object.
* @param entryClass the Class of the DSet.Entry elements contained in the
* set.
* @param editableFields the names of the fields in the entryClass that
* should be editable.
*/
public DSetEditor (DObject setter, String setName, Class entryClass,
String[] editableFields)
{
this(setter, setName, entryClass, editableFields, null);
}
/**
* Construct a DSetEditor with a custom FieldInterpreter.
*
* @param setter The object that contains the set.
* @param setName The name of the set in the object.
* @param entryClass the Class of the DSet.Entry elements contained in the
* set.
* @param editableFields the names of the fields in the entryClass that
* should be editable.
* @param interp The FieldInterpreter to use.
*/
public DSetEditor (DObject setter, String setName, Class entryClass,
String[] editableFields,
ObjectEditorTable.FieldInterpreter interp)
{
super(new BorderLayout());
_setter = setter;
_setName = setName;
_set = _setter.getSet(setName);
_table = new ObjectEditorTable(entryClass, editableFields, interp);
add(new SafeScrollPane(_table), BorderLayout.CENTER);
}
/**
* Get the table being used to display the set.
*/
public JTable getTable ()
{
return _table;
}
/**
* Get the currently selected entry.
*/
public DSet.Entry getSelectedEntry ()
{
return (DSet.Entry) _table.getSelectedObject();
}
// documentation inherited
public Dimension getPreferredSize ()
{
Dimension d = super.getPreferredSize();
d.height = Math.min(d.height, 200);
return d;
}
// documentation inherited
public void addNotify ()
{
super.addNotify();
_setter.addListener(this);
_table.addActionListener(this);
// populate the table
refreshData();
}
// documentation inherited
public void removeNotify ()
{
_setter.removeListener(this);
_table.removeActionListener(this);
super.removeNotify();
}
// documentation inherited from interface SetListener
public void entryAdded (EntryAddedEvent event)
{
if (event.getName().equals(_setName)) {
DSet.Entry entry = event.getEntry();
int index = _keys.insertSorted(entry.getKey());
_table.insertDatum(entry, index);
}
}
// documentation inherited from interface SetListener
public void entryRemoved (EntryRemovedEvent event)
{
if (event.getName().equals(_setName)) {
Comparable key = event.getKey();
int index = _keys.indexOf(key);
_keys.remove(index);
_table.removeDatum(index);
}
}
// documentation inherited from interface SetListener
public void entryUpdated (EntryUpdatedEvent event)
{
if (event.getName().equals(_setName)) {
DSet.Entry entry = event.getEntry();
int index = _keys.indexOf(entry.getKey());
_table.updateDatum(entry, index);
}
}
// documentation inherited from interface SetListener
public void attributeChanged (AttributeChangedEvent event)
{
if (event.getName().equals(_setName)) {
// the whole set changed so we need to refetch it from the object
_set = _setter.getSet(_setName);
refreshData();
}
}
// documentation inherited from interface ActionListener
public void actionPerformed (ActionEvent event)
{
CommandEvent ce = (CommandEvent) event;
_setter.updateSet(_setName, (DSet.Entry) ce.getArgument());
}
protected void refreshData ()
{
_keys = new SortableArrayList();
DSet.Entry[] entries = new DSet.Entry[_set.size()];
_set.toArray(entries);
for (int ii=0; ii < entries.length; ii++) {
_keys.insertSorted(entries[ii].getKey());
}
_table.setData(entries); // this works because DSet itself is sorted
}
/** The object that contains the set we're displaying. */
protected DObject _setter;
/** The name of the set in that object. */
protected String _setName;
/** The set itself. */
protected DSet _set;
/** An array we use to track our entries' positions by key. */
protected SortableArrayList _keys;
/** The table used to edit. */
protected ObjectEditorTable _table;
}
|
// $Id: SceneObject.java,v 1.10 2004/01/11 08:24:16 mdb Exp $
package com.threerings.miso.client;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.Rectangle;
import com.samskivert.util.RuntimeAdjust;
import com.samskivert.util.StringUtil;
import com.threerings.media.tile.NoSuchTileException;
import com.threerings.media.tile.NoSuchTileSetException;
import com.threerings.media.tile.ObjectTile;
import com.threerings.media.tile.TileUtil;
import com.threerings.miso.Log;
import com.threerings.miso.MisoPrefs;
import com.threerings.miso.data.ObjectInfo;
import com.threerings.miso.util.MisoSceneMetrics;
import com.threerings.miso.util.MisoUtil;
/**
* Contains resolved information on an object in a scene.
*/
public class SceneObject
{
/** The object's info record. */
public ObjectInfo info;
/** The object tile used to display this object. */
public ObjectTile tile;
/** The screen coordinate bounds of our object tile given its position
* in the scene. */
public Rectangle bounds;
/**
* Creates a scene object for display by the specified panel. The
* appropriate object tile is resolved and the object's in-situ bounds
* are computed.
*/
public SceneObject (MisoScenePanel panel, ObjectInfo info)
{
this.info = info;
// resolve our object tile
refreshObjectTile(panel);
}
/**
* Creates a scene object for display by the specified panel.
*/
public SceneObject (MisoScenePanel panel, ObjectInfo info, ObjectTile tile)
{
this(panel.getSceneMetrics(), info, tile);
}
/**
* Creates a scene object for display according to the supplied metrics.
*/
public SceneObject (
MisoSceneMetrics metrics, ObjectInfo info, ObjectTile tile)
{
this.info = info;
this.tile = tile;
computeInfo(metrics);
}
/**
* Used to flag overlapping scene objects that have no resolving
* object priorities.
*/
public void setWarning (boolean warning)
{
_warning = warning;
}
/**
* Requests that this scene object render itself.
*/
public void paint (Graphics2D gfx)
{
if (_hideObjects.getValue()) {
return;
}
// if we're rendering footprints, paint that
boolean footpaint = _fprintDebug.getValue();
if (footpaint) {
gfx.setColor(Color.black);
gfx.draw(_footprint);
}
// if we have a warning, render an alpha'd red rectangle over our
// bounds
if (_warning) {
Composite ocomp = gfx.getComposite();
gfx.setComposite(ALPHA_WARN);
gfx.fill(bounds);
gfx.setComposite(ocomp);
}
// paint our tile
tile.paint(gfx, bounds.x, bounds.y);
// and possibly paint the object's spot
if (footpaint && _sspot != null) {
// translate the origin to center on the portal
gfx.translate(_sspot.x, _sspot.y);
// rotate to reflect the spot orientation
double rot = (Math.PI / 4.0f) * tile.getSpotOrient();
gfx.rotate(rot);
// draw the spot triangle
gfx.setColor(Color.green);
gfx.fill(_spotTri);
// outline the triangle in black
gfx.setColor(Color.black);
gfx.draw(_spotTri);
// restore the original transform
gfx.rotate(-rot);
gfx.translate(-_sspot.x, -_sspot.y);
}
}
/**
* Returns the location associated with this object's "spot" in fine
* coordinates or null if it has no spot.
*/
public Point getObjectSpot ()
{
return _fspot;
}
/**
* Returns the location associated with this object's "spot" in screen
* coordinates or null if it has no spot.
*/
public Point getObjectScreenSpot ()
{
return _sspot;
}
/**
* Returns true if this object's footprint overlaps that of the
* specified other object.
*/
public boolean objectFootprintOverlaps (SceneObject so)
{
return _frect.intersects(so._frect);
}
/**
* Returns true if this object's footprint overlaps the supplied tile
* coordinate rectangle.
*/
public boolean objectFootprintOverlaps (Rectangle rect)
{
return _frect.intersects(rect);
}
/**
* Returns a polygon bounding all footprint tiles of this scene
* object.
*
* @return the bounding polygon.
*/
public Polygon getObjectFootprint ()
{
return _footprint;
}
/**
* Returns the render priority of this scene object.
*/
public int getPriority ()
{
// if we have no overridden priority, return our object tile's
// default priority
return (info.priority == 0 && tile != null) ?
tile.getPriority() : info.priority;
}
/**
* Overrides the render priority of this object.
*/
public void setPriority (byte priority)
{
info.priority = (byte)Math.max(
Byte.MIN_VALUE, Math.min(Byte.MAX_VALUE, priority));
}
/**
* Informs this scene object that the mouse is now hovering over it.
* Custom objects may wish to adjust some internal state and return
* true from this method indicating that they should be repainted.
*/
public boolean setHovered (boolean hovered)
{
return false;
}
/**
* Updates this object's origin tile coordinate. It's bounds and other
* cached screen coordinate information are updated.
*/
public void relocateObject (MisoSceneMetrics metrics, int tx, int ty)
{
// Log.info("Relocating object " + this + " to " +
// StringUtil.coordsToString(tx, ty));
info.x = tx;
info.y = ty;
computeInfo(metrics);
}
/**
* Reloads and recolorizes our object tile. It is not intended for the
* actual object tile used by a scene object to change in its
* lifetime, only attributes of that object like its colorizations. So
* don't do anything crazy like change our {@link ObjectInfo}'s
* <code>tileId</code> and call this method or things might break.
*/
public void refreshObjectTile (MisoScenePanel panel)
{
int tsid = TileUtil.getTileSetId(info.tileId);
int tidx = TileUtil.getTileIndex(info.tileId);
try {
tile = (ObjectTile)panel.getTileManager().getTile(
tsid, tidx, panel.getColorizer(info));
computeInfo(panel.getSceneMetrics());
} catch (NoSuchTileException nste) {
Log.warning("Scene contains non-existent object tile " +
"[info=" + info + "].");
} catch (NoSuchTileSetException te) {
Log.warning("Scene contains non-existent object tileset " +
"[info=" + info + "].");
}
}
/**
* Computes our screen bounds, tile footprint and other useful cached
* metrics.
*/
protected void computeInfo (MisoSceneMetrics metrics)
{
// start with the screen coordinates of our origin tile
Point tpos = MisoUtil.tileToScreen(
metrics, info.x, info.y, new Point());
// if the tile has an origin coordinate, use that, otherwise
// compute it from the tile footprint
int tox = tile.getOriginX(), toy = tile.getOriginY();
if (tox == Integer.MIN_VALUE) {
tox = tile.getBaseWidth() * metrics.tilehwid;
}
if (toy == Integer.MIN_VALUE) {
toy = tile.getHeight();
}
bounds = new Rectangle(tpos.x + metrics.tilehwid - tox,
tpos.y + metrics.tilehei - toy,
tile.getWidth(), tile.getHeight());
// compute our object footprint as well
_frect = new Rectangle(info.x - tile.getBaseWidth() + 1,
info.y - tile.getBaseHeight() + 1,
tile.getBaseWidth(), tile.getBaseHeight());
_footprint = MisoUtil.getFootprintPolygon(
metrics, _frect.x, _frect.y, _frect.width, _frect.height);
// compute our object spot if we've got one
if (tile.hasSpot()) {
_fspot = MisoUtil.tilePlusFineToFull(
metrics, info.x, info.y, tile.getSpotX(), tile.getSpotY(),
new Point());
_sspot = MisoUtil.fullToScreen(
metrics, _fspot.x, _fspot.y, new Point());
}
// Log.info("Computed object metrics " +
// "[tpos=" + StringUtil.coordsToString(tx, ty) +
// ", info=" + info +
// ", sbounds=" + StringUtil.toString(bounds) + "].");
}
/**
* Returns a string representation of this instance.
*/
public String toString ()
{
return info + "[" + StringUtil.toString(bounds) + "]";
}
/** Our object as a tile coordinate rectangle. */
protected Rectangle _frect;
/** Our object footprint as a polygon. */
protected Polygon _footprint;
/** The full-coordinates of our object spot; or null if we have none. */
protected Point _fspot;
/** The screen-coordinates of our object spot; or null if we have none. */
protected Point _sspot;
/** Used to mark objects with errors. */
protected boolean _warning;
/** A debug hook that toggles rendering of objects. */
protected static RuntimeAdjust.BooleanAdjust _hideObjects =
new RuntimeAdjust.BooleanAdjust(
"Toggles rendering of objects in the scene view.",
"narya.miso.hide_objects", MisoPrefs.config, false);
/** A debug hook that toggles rendering of object footprints. */
protected static RuntimeAdjust.BooleanAdjust _fprintDebug =
new RuntimeAdjust.BooleanAdjust(
"Toggles rendering of object footprints in the scene view.",
"narya.miso.iso_fprint_debug_render", MisoPrefs.config, false);
/** The triangle used to render an object's spot. */
protected static Polygon _spotTri;
static {
_spotTri = new Polygon();
_spotTri.addPoint(-3, -3);
_spotTri.addPoint(3, -3);
_spotTri.addPoint(0, 3);
};
/** The alpha used to fill our bounds for warning purposes. */
protected static final Composite ALPHA_WARN =
AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f);
}
|
// $Id: GameManager.java,v 1.5 2001/10/09 18:18:07 mdb Exp $
package com.threerings.parlor.server;
import com.threerings.cocktail.party.data.BodyObject;
import com.threerings.cocktail.party.server.PlaceManager;
import com.threerings.cocktail.party.server.PartyServer;
import com.threerings.parlor.Log;
import com.threerings.parlor.client.ParlorCodes;
import com.threerings.parlor.data.GameConfig;
import com.threerings.parlor.data.GameObject;
/**
* The game manager handles the server side management of a game. It
* manipulates the game state in accordance with the logic of the game
* flow and generally manages the whole game playing process.
*
* <p> The game manager extends the place manager because games are
* implicitly played in a location, the players of the game implicitly
* bodies in that location.
*/
public class GameManager
extends PlaceManager implements ParlorCodes
{
// documentation inherited
protected Class getPlaceObjectClass ()
{
return GameObject.class;
}
// documentation inherited
protected void didInit ()
{
super.didInit();
// cast our configuration object (do we need to do this?)
_gconfig = (GameConfig)_config;
}
/**
* Initializes the game manager with the supplied game configuration
* object. This happens before startup and before the game object has
* been created.
*
* @param players the usernames of all of the players in this game or
* null if the game has no specific set of players.
*/
public void setPlayers (String[] players)
{
// keep this info for later
_players = players;
}
// documentation inherited
protected void didStartup ()
{
// obtain a casted reference to our game object
_gameobj = (GameObject)_plobj;
// let the players of this game know that we're ready to roll (if
// we have a specific set of players)
if (_players != null) {
Object[] args = new Object[] {
new Integer(_gameobj.getOid()) };
for (int i = 0; i < _players.length; i++) {
BodyObject bobj = PartyServer.lookupBody(_players[i]);
// deliver a game ready notification to the player
PartyServer.invmgr.sendNotification(
bobj.getOid(), MODULE_NAME, GAME_READY_NOTIFICATION, args);
}
}
}
// documentation inherited
protected void bodyEntered (int bodyOid)
{
}
// documentation inherited
protected void bodyLeft (int bodyOid)
{
}
/** A reference to our game configuration. */
protected GameConfig _gconfig;
/** The usernames of the players of this game. */
protected String[] _players;
/** A reference to our game object. */
protected GameObject _gameobj;
}
|
package esg.common.security;
import esg.common.generated.security.*;
import esg.common.util.ESGFProperties;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Date;
import java.util.Properties;
import java.util.Set;
import java.util.HashSet;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.*;
/**
Description:
Object used to load policy xml descriptor files, manipulate policy
information and save the policy information back to descriptor
file.
**/
public class PolicyGleaner {
private static final Log log = LogFactory.getLog(PolicyGleaner.class);
private static final String policyFile = "esgf_policies_local.xml";
private String policyPath = null;
private Properties props = null;
private String stringOutput = "<oops>";
private Set<PolicyWrapper> policySet = null;
private Policies myPolicy = null;
private boolean dirty = true;
public PolicyGleaner() { this(null); }
public PolicyGleaner(Properties props) {
this.props = props;
this.init();
}
public void init() {
try {
if(props == null) this.props = new ESGFProperties();
} catch(Exception e) {
log.error(e);
}
// /usr/local/tomcat/webapps/esgf-security/WEB-INF/classes/esg/security/config/
//policyPath = props.getProperty("security.app.home",".")+File.separator+"WEB-INF"+File.separator+"classes"+File.separator+"esg"+File.separator+"security"+File.separator+"config"+File.separator;
// /esg/config
policyPath = System.getProperty("ESGF_HOME","/esg")+File.separator+"config";
policySet = new HashSet<PolicyWrapper>();
myPolicy = new Policies();
}
public Policies getMyPolicy() { return myPolicy; }
public synchronized PolicyGleaner loadMyPolicy() { return this.loadMyPolicy(policyPath+policyFile); }
public synchronized PolicyGleaner loadMyPolicy(String... filenames) {
for(String filename : filenames) {
log.info("Loading my policy info from "+filename);
try{
JAXBContext jc = JAXBContext.newInstance(Policies.class);
Unmarshaller u = jc.createUnmarshaller();
JAXBElement<Policies> root = u.unmarshal(new StreamSource(new File(filename)),Policies.class);
myPolicy = root.getValue();
int count = 0;
for(Policy policy : myPolicy.getPolicy()) { policySet.add(new PolicyWrapper(policy)); count++; } //dedup
log.trace("Unmarshalled ["+myPolicy.getPolicy().size()+"] policies - Inspected ["+count+"] polices - resulted in ["+policySet.size()+"] policies");
dirty=true;
}catch(Exception e) {
throw new ESGFPolicyException("Unable to properly load policies from ["+filename+"]", e);
}
}
return this;
}
public synchronized boolean savePolicy() { return savePolicyAs(myPolicy,policyPath+policyFile); }
public synchronized boolean savePolicy(Policies policy) { return savePolicyAs(policy, policyPath+policyFile); }
public synchronized boolean savePolicyAs(String location) { return savePolicyAs(myPolicy, location); }
public synchronized boolean savePolicyAs(Policies policy, String policyFileLocation) {
boolean success = false;
if (policy == null) {
log.error("Sorry internal policy representation is null ? ["+policy+"] perhaps you need to load policy file first?");
return success;
}
log.info("Saving policy information to "+policyFileLocation);
try{
JAXBContext jc = JAXBContext.newInstance(Policies.class);
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(policy, new FileOutputStream(policyFileLocation));
success = true;
}catch(Exception e) {
log.error(e);
}
return success;
}
//Policy manipulation methods
public PolicyGleaner addPolicy(String resource, String groupName, String roleName, String action) {
dirty=true;
Policy p = new Policy();
p.setResource(resource);
p.setAttributeType(groupName);
p.setAttributeValue(roleName);
p.setAction(action);
policySet.add(new PolicyWrapper(p));
return this;
}
public PolicyGleaner removePolicy(String resource, String groupName, String roleName, String action) {
dirty=true;
Policy p = new Policy();
p.setResource(resource);
p.setAttributeType(groupName);
p.setAttributeValue(roleName);
p.setAction(action);
policySet.remove(new PolicyWrapper(p));
return this;
}
public PolicyGleaner removeAllForGroup(String groupName) {
dirty=true;
log.trace("Removing all policies with group = "+groupName);
Set<PolicyWrapper> delSet = new HashSet<PolicyWrapper>();
for(PolicyWrapper policyWrapper : policySet) {
if(policyWrapper.getPolicy().getAttributeType().equals(groupName)) {
delSet.add(policyWrapper);
log.trace("Removing policy: "+policyWrapper);
}
}
if(policySet.removeAll(delSet)) { log.trace("ok"); } else { log.trace("nope"); }
return this;
}
public PolicyGleaner removeAllForRole(String roleName) {
dirty=true;
log.trace("Removing all policies with role = "+roleName);
Set<PolicyWrapper> delSet = new HashSet<PolicyWrapper>();
for(PolicyWrapper policyWrapper : policySet) {
if(policyWrapper.getPolicy().getAttributeValue().equals(roleName)) {
delSet.add(policyWrapper);
log.trace("Removing policy: "+policyWrapper);
}
}
if(policySet.removeAll(delSet)) { log.trace("ok"); } else { log.trace("nope"); }
return this;
}
public PolicyGleaner removeAllForAction(String action) {
dirty=true;
log.trace("Removing all policies with action = "+action);
Set<PolicyWrapper> delSet = new HashSet<PolicyWrapper>();
for(PolicyWrapper policyWrapper : policySet) {
if(policyWrapper.getPolicy().getAction().equals(action)) {
delSet.add(policyWrapper);
log.trace("Removing policy: "+policyWrapper);
}
}
if(policySet.removeAll(delSet)) { log.trace("ok"); } else { log.trace("nope"); }
return this;
}
public PolicyGleaner commit() {
dirty=true;
myPolicy.getPolicy().clear();
for(PolicyWrapper policyWrapper : policySet) {
log.trace("preparing to commit: \n"+policyWrapper);
myPolicy.getPolicy().add(policyWrapper.getPolicy());
}
log.trace("commit done");
return this;
}
public int size() { return policySet.size(); }
public PolicyGleaner clear() { policySet.clear(); myPolicy.getPolicy().clear(); return this; }
public String toString() { return this.toString(false); }
public String toString(boolean force) {
log.info("dirty = "+dirty);
log.info("force = "+force);
if(dirty || force) {
StringBuffer sb = new StringBuffer("Policies:\n");
for(PolicyWrapper policyWrapper : policySet) {
sb.append(policyWrapper.toString());
}
stringOutput = sb.toString();
}
dirty=false;
return stringOutput;
}
class PolicyWrapper {
Policy policy = null;
final String outputString;
PolicyWrapper(Policy policy) {
this.policy = policy;
StringBuffer sb = new StringBuffer("policy: ");
sb.append("["+policy.getResource()+"] ");
sb.append("g["+policy.getAttributeType()+"] ");
sb.append("r["+policy.getAttributeValue()+"] ");
sb.append("a["+policy.getAction()+"]\n");
outputString = sb.toString();
}
Policy getPolicy() { return policy; }
public boolean equals(Object o) {
if(!(o instanceof PolicyWrapper)) return false;
return outputString.equals(o.toString());
}
public int hashCode() {
return outputString.hashCode();
}
public String toString() {
return outputString;
}
}
//Main: For quick testing...
public static void main(String[] args) {
PolicyGleaner pGleaner = null;
pGleaner = new PolicyGleaner(new Properties());
pGleaner.loadMyPolicy();
pGleaner.addPolicy(".*test.*", "superGroup", "boss", "Write");
pGleaner.addPolicy(".*cmip5.*", "otherGroup", "user", "Read");
try{
pGleaner.commit().savePolicyAs("/tmp/"+File.createTempFile("policy_test_","out").getName());
}catch (java.io.IOException e) {
System.out.println(e.getMessage());
}
System.out.println(pGleaner);
//if(args.length > 0) {
// if(args[0].equals("load")) {
// System.out.println(args[0]+"ing...");
// pGleaner = new PolicyGleaner();
// if(args.length == 2) {
// if(args[1].equals("default")) {
// System.out.println(pGleaner.loadMyPolicy());
// }else {
// System.out.println(pGleaner.loadMyPolicy(args[1]));
// //Do some manipulation here...
// //And show it...
// if(args.length == 3) {
// pGleaner.savePolicyAs(args[2]);
// }else{
// pGleaner.savePolicy();
// }else {
}
}
|
package org.apache.commons.collections;
import java.util.Map;
public interface BidiMap extends Map {
public Object put(Object key, Object value);
/**
* Gets the key that is currently mapped to the specified value.
* <p>
* If the value is not contained in the map, <code>null</code> is returned.
* <p>
* Implementations should seek to make this method perform equally as well
* as <code>get(Object)</code>.
*
* @param value the value to find the key for
* @return the mapped key, or <code>null</code> if not found
*
* @throws ClassCastException (optional) if the map limits the type of the
* value and the specifed value is inappropriate
* @throws NullPointerException (optional) if the map limits the values to
* non-null and null was specified
*/
public Object getKey(Object value);
/**
* Removes the key-value pair that is currently mapped to the specified
* value (optional operation).
* <p>
* If the value is not contained in the map, <code>null</code> is returned.
* <p>
* Implementations should seek to make this method perform equally as well
* as <code>remove(Object)</code>.
*
* @param value the value to find the key-value pair for
* @return the key that was removed, <code>null</code> if nothing removed
*
* @throws ClassCastException (optional) if the map limits the type of the
* value and the specifed value is inappropriate
* @throws NullPointerException (optional) if the map limits the values to
* non-null and null was specified
* @throws UnsupportedOperationException if this method is not supported
* by the implementation
*/
public Object removeKey(Object value);
/**
* Gets a view of this map where the keys and values are reversed.
* <p>
* Changes to one map will be visible in the other and vice versa.
* This enables both directions of the map to be accessed as a <code>Map</code>.
* <p>
* Implementations should seek to avoid creating a new object every time this
* method is called. See <code>AbstractMap.values()</code> etc. Calling this
* method on the inverse map should return the original.
*
* @return an inverted bidirectional map
*/
public BidiMap inverseBidiMap();
}
|
package org.apache.commons.math.stat;
/**
* StatUtils provides easy static implementations of common double[] based
* statistical methods. These return a single result value or in some cases, as
* identified in the javadoc for each method, Double.NaN.
*
* @author <a href="mailto:mdiggory@apache.org">Mark Diggory</a>
*/
public class StatUtils {
/**
* The sum of the values that have been added to Univariate.
* @param values Is a double[] containing the values
* @return the sum of the values or Double.NaN if the array is empty
*/
public static double sum(double[] values) {
double accum = 0.0;
for (int i = 0; i < values.length; i++) {
accum += values[i];
}
return accum;
}
/**
* Returns the sum of the squares of the available values.
* @param values Is a double[] containing the values
* @return the sum of the squared values or Double.NaN if the array is empty
*/
public static double sumSq(double[] values) {
double accum = 0.0;
for (int i = 0; i < values.length; i++) {
accum += Math.pow(values[i], 2.0);
}
return accum;
}
/**
* Returns the product for this collection of values
* @param values Is a double[] containing the values
* @return the product values or Double.NaN if the array is empty
*/
public static double product(double[] values) {
double product = Double.NaN;
if( values.length > 0 ) {
product = 1.0;
for( int i = 0; i < values.length; i++) {
product *= values[i];
}
}
return product;
}
/**
* Returns the geometric mean for this collection of values
* @param values Is a double[] containing the values
* @return the geometric mean or Double.NaN if the array is empty or
* any of the values are <= 0.
*/
public static double geometricMean(double[] values) {
return Math.pow(product(values),(1.0/values.length));
}
public static double mean(double[] values) {
return sum(values) / values.length;
}
/**
*
* @param values Is a double[] containing the values
* @return the result, Double.NaN if no values for an empty array
* or 0.0 for a single value set.
*/
public static double standardDeviation(double[] values) {
double stdDev = Double.NaN;
if (values.length != 0) {
stdDev = Math.sqrt(variance(values));
}
return (stdDev);
}
/**
* Returns the variance of the available values.
* @param values Is a double[] containing the values
* @return the result, Double.NaN if no values for an empty array
* or 0.0 for a single value set.
*/
public static double variance(double[] values) {
double variance = Double.NaN;
if (values.length == 1) {
variance = 0;
} else if (values.length > 1) {
double mean = mean(values);
double accum = 0.0;
for (int i = 0; i < values.length; i++) {
accum += Math.pow((values[i] - mean), 2.0);
}
variance = accum / (values.length - 1);
}
return variance;
}
/**
* Returns the skewness of a collection of values. Skewness is a
* measure of the assymetry of a given distribution.
* @param values Is a double[] containing the values
* @return the skewness of the values or Double.NaN if the array is empty
*/
public static double skewness(double[] values) {
// Initialize the skewness
double skewness = Double.NaN;
// Get the mean and the standard deviation
double mean = mean(values);
double stdDev = standardDeviation(values);
// Sum the cubes of the distance from the mean divided by the
// standard deviation
double accum = 0.0;
for (int i = 0; i < values.length; i++) {
accum += Math.pow((values[i] - mean) / stdDev, 3.0);
}
// Get N
double n = values.length;
// Calculate skewness
skewness = (n / ((n - 1) * (n - 2))) * accum;
return skewness;
}
/**
* Returns the kurtosis for this collection of values. Kurtosis is a
* measure of the "peakedness" of a distribution.
* @param values Is a double[] containing the values
* @return the kurtosis of the values or Double.NaN if the array is empty
*/
public static double kurtosis(double[] values) {
// Initialize the kurtosis
double kurtosis = Double.NaN;
// Get the mean and the standard deviation
double mean = mean(values);
double stdDev = standardDeviation(values);
// Sum the ^4 of the distance from the mean divided by the
// standard deviation
double accum = 0.0;
for (int i = 0; i < values.length; i++) {
accum += Math.pow((values[i] - mean) / stdDev, 4.0);
}
// Get N
double n = values.length;
double coefficientOne = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3));
double termTwo = ((3 * Math.pow(n - 1, 2.0))
/ ((n - 2) * (n - 3)));
// Calculate kurtosis
kurtosis = (coefficientOne * accum) - termTwo;
return kurtosis;
}
/**
* Returns the maximum of the available values
* @param values Is a double[] containing the values
* @return the maximum of the values or Double.NaN if the array is empty
*/
public static double max(double[] values) {
double max = Double.NaN;
for (int i = 0; i < values.length; i++) {
if (i == 0) {
max = values[i];
} else {
max = Math.max(max, values[i]);
}
}
return max;
}
/**
* Returns the minimum of the available values
* @param values Is a double[] containing the values
* @return the minimum of the values or Double.NaN if the array is empty
*/
public static double min(double[] values) {
double min = Double.NaN;
for (int i = 0; i < values.length; i++) {
if (i == 0) {
min = values[i];
} else {
min = Math.min(min, values[i]);
}
}
return min;
}
/**
* Returns the mode of the values that have been added. The mode is
* the element which occurs with the most frequency
* @return the mode
*/
public static double mode(){
// Mode depends on a refactor Freq class
String msg = "mode() is not yet implemented";
throw new UnsupportedOperationException(msg);
}
/**
* Returns the mode of the values that have been added. The mode is
* the element which occurs with the most frequency
* @return the mode
*/
public static double median(double[] values){
// Mode depends on a refactor Freq class
String msg = "median() is not yet implemented";
throw new UnsupportedOperationException(msg);
}
}
|
package org.jcoderz.commons;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
/**
* This abstract class implements the interface
* {@link org.jcoderz.commons.LogMessageInfo}.
* <p>
* All parameters are stored as immutable fields.
* Besides the parameters from the interface, an (unique) error
* id must be supplied during construction.
*
* @author Michael Griffel
*/
public abstract class LogMessageInfoImpl
implements LogMessageInfo
{
/** use this serialVersionUID for serialization. */
static final long serialVersionUID = 1L;
private final String mErrorSymbol;
private final int mErrorId;
private final Level mLogLevel;
private final String mMessagePattern;
private final String mSolution;
private final List mParameters;
private final BusinessImpact mBusinessImpact;
private final Category mCategory;
private final String mApplicationName;
private final String mApplicationNameAbbreviation;
private final String mGroupName;
private final String mGroupNameAbbreviation;
protected LogMessageInfoImpl (String symbol, int id, Level level,
String text, String solution, BusinessImpact businessImpact,
Category category, String[] params, String appName,
String appNameAbbr, String groupName, String groupNameAbbr)
{
mErrorSymbol = symbol;
mErrorId = id;
mLogLevel = level;
mMessagePattern = text;
mSolution = solution;
mBusinessImpact = businessImpact;
mCategory = category;
mParameters = Collections.unmodifiableList(Arrays.asList(params));
mApplicationName = appName;
mApplicationNameAbbreviation = appNameAbbr;
mGroupName = groupName;
mGroupNameAbbreviation = groupNameAbbr;
}
public final int toInt ()
{
return mErrorId;
}
/**
* Returns the string representation of the log message info. This is the
* symbolic string representation as defined in the parameter
* <code>symbol</code> during construction.
* @see java.lang.Object#toString()
* @return the string representation of the log message info.
*/
public final String toString ()
{
return mErrorSymbol;
}
// LogMessageInfo interface
/** {@inheritDoc} */
public final String getSymbol ()
{
return mErrorSymbol;
}
/** {@inheritDoc} */
public final Level getLogLevel ()
{
return mLogLevel;
}
/** {@inheritDoc} */
public final String getMessagePattern ()
{
return mMessagePattern;
}
/** {@inheritDoc} */
public final StringBuffer formatMessage (Map parameters, StringBuffer buffer)
{
final StringBuffer result
= buffer != null ? buffer : new StringBuffer();
try
{
final MessageFormat formatter = new MessageFormat(getMessagePattern());
final List parameter = new ArrayList();
if (parameters != null && !getParameterList().isEmpty())
{
final Iterator i = getParameterList().iterator();
while (i.hasNext())
{
final String parameterName = (String) i.next();
final List parameterValues = (List) parameters.get(parameterName);
if (parameterValues == null || parameterValues.isEmpty())
{
parameter.add(null);
}
else
{
parameter.add(parameterValues.get(0));
}
}
}
formatter.format(parameter.toArray(), result, null);
}
// could be caused by invalid message format!
catch (Exception ex)
{
result.append(parameters);
result.append(' ');
result.append(getMessagePattern());
}
return result;
}
/** {@inheritDoc} */
public final String getSolution ()
{
return mSolution;
}
/** {@inheritDoc} */
public final BusinessImpact getBusinessImpact ()
{
return mBusinessImpact;
}
/** {@inheritDoc} */
public final Category getCategory ()
{
return mCategory;
}
/** {@inheritDoc} */
public final List getParameterList ()
{
return mParameters;
}
/** {@inheritDoc} */
public String getAppName ()
{
return mApplicationName;
}
/** {@inheritDoc} */
public String getAppNameAbbreviation ()
{
return mApplicationNameAbbreviation;
}
/** {@inheritDoc} */
public String getGroupName ()
{
return mGroupName;
}
/** {@inheritDoc} */
public String getGroupNameAbbreviation ()
{
return mGroupNameAbbreviation;
}
}
|
package org.jivesoftware.spark.ui;
import org.jivesoftware.resource.Res;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.spark.PresenceManager;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.component.VerticalFlowLayout;
import org.jivesoftware.spark.component.panes.CollapsiblePane;
import org.jivesoftware.spark.component.renderer.JPanelRenderer;
import org.jivesoftware.spark.util.GraphicUtils;
import org.jivesoftware.spark.util.ModelUtil;
import org.jivesoftware.spark.util.log.Log;
import org.jivesoftware.sparkimpl.settings.local.LocalPreferences;
import org.jivesoftware.sparkimpl.settings.local.SettingsManager;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.Timer;
/**
* Container representing a RosterGroup within the Contact List.
*/
public class ContactGroup extends CollapsiblePane implements MouseListener {
private List<ContactItem> contactItems = new ArrayList<ContactItem>();
private List<ContactGroup> contactGroups = new ArrayList<ContactGroup>();
private List<ContactGroupListener> listeners = new ArrayList<ContactGroupListener>();
private List<ContactItem> offlineContacts = new ArrayList<ContactItem>();
private String groupName;
private DefaultListModel model;
private JList contactItemList;
private boolean sharedGroup;
private JPanel listPanel;
// Used to display no contacts in list.
private final ContactItem noContacts = new ContactItem("There are no online contacts in this group.", null);
private final ListMotionListener motionListener = new ListMotionListener();
private boolean canShowPopup;
private MouseEvent mouseEvent;
private LocalPreferences preferences;
/**
* Create a new ContactGroup.
*
* @param groupName the name of the new ContactGroup.
*/
public ContactGroup(String groupName) {
// Initialize Model and UI
model = new DefaultListModel();
contactItemList = new JList(model);
preferences = SettingsManager.getLocalPreferences();
setTitle(getGroupTitle(groupName));
// Use JPanel Renderer
contactItemList.setCellRenderer(new JPanelRenderer());
this.groupName = groupName;
listPanel = new JPanel(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 0, true, false));
listPanel.add(contactItemList, listPanel);
this.setContentPane(listPanel);
if (!isOfflineGroup()) {
contactItemList.setDragEnabled(true);
contactItemList.setTransferHandler(new ContactGroupTransferHandler());
}
// Allow for mouse events to take place on the title bar
getTitlePane().addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
checkPopup(e);
}
public void mouseReleased(MouseEvent e) {
checkPopup(e);
}
public void checkPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
e.consume();
fireContactGroupPopupEvent(e);
}
}
});
// Items should have selection listener
contactItemList.addMouseListener(this);
contactItemList.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent keyEvent) {
}
public void keyPressed(KeyEvent keyEvent) {
if (keyEvent.getKeyChar() == KeyEvent.VK_ENTER) {
ContactItem item = (ContactItem)contactItemList.getSelectedValue();
fireContactItemDoubleClicked(item);
}
ContactList.activeKeyEvent = keyEvent;
}
public void keyReleased(KeyEvent keyEvent) {
ContactList.activeKeyEvent = null;
}
});
noContacts.getNicknameLabel().setFont(new Font("Dialog", Font.PLAIN, 11));
noContacts.getNicknameLabel().setForeground(Color.GRAY);
model.addElement(noContacts);
// Add Popup Window
addPopupWindow();
}
/**
* Adds a new offline contact.
*
* @param nickname the nickname of the offline contact.
* @param jid the jid of the offline contact.
*/
public void addOfflineContactItem(String nickname, String jid, String status) {
// Build new ContactItem
final ContactItem offlineItem = new ContactItem(nickname, jid);
offlineItem.setGroupName(getGroupName());
final Presence offlinePresence = PresenceManager.getPresence(jid);
offlineItem.setPresence(offlinePresence);
// set offline icon
offlineItem.setIcon(PresenceManager.getIconFromPresence(offlinePresence));
// Set status if applicable.
if (ModelUtil.hasLength(status)) {
offlineItem.setStatusText(status);
}
// Add to offlien contacts.
offlineContacts.add(offlineItem);
insertOfflineContactItem(offlineItem);
}
/**
* Inserts a new offline <code>ContactItem</code> into the ui model.
*
* @param offlineItem the ContactItem to add.
*/
public void insertOfflineContactItem(ContactItem offlineItem) {
if (model.contains(offlineItem)) {
return;
}
if (!preferences.isOfflineGroupVisible()) {
Collections.sort(offlineContacts, itemComparator);
int index = offlineContacts.indexOf(offlineItem);
int totalListSize = contactItems.size();
int newPos = totalListSize + index;
if (newPos > model.size()) {
newPos = model.size();
}
model.insertElementAt(offlineItem, newPos);
if (model.contains(noContacts)) {
model.removeElement(noContacts);
}
}
}
/**
* Removes an offline <code>ContactItem</code> from the Offline contact
* model and ui.
*
* @param item the offline contact item to remove.
*/
public void removeOfflineContactItem(ContactItem item) {
offlineContacts.remove(item);
removeContactItem(item);
}
/**
* Removes an offline <code>ContactItem</code> from the offline contact model and ui.
*
* @param jid the offline contact item to remove.
*/
public void removeOfflineContactItem(String jid) {
final List<ContactItem> items = new ArrayList<ContactItem>(offlineContacts);
for (ContactItem item : items) {
if (item.getJID().equals(jid)) {
removeOfflineContactItem(item);
}
}
}
/**
* Toggles the visibility of Offline Contacts.
*
* @param show true if offline contacts should be shown, otherwise false.
*/
public void toggleOfflineVisibility(boolean show) {
final List<ContactItem> items = new ArrayList<ContactItem>(offlineContacts);
for (ContactItem item : items) {
if (show) {
insertOfflineContactItem(item);
}
else {
model.removeElement(item);
}
}
}
/**
* Adds a <code>ContactItem</code> to the ContactGroup.
*
* @param item the ContactItem.
*/
public void addContactItem(ContactItem item) {
// Remove from offline group if it exists
removeOfflineContactItem(item.getJID());
if (model.contains(noContacts)) {
model.remove(0);
}
if ("Offline Group".equals(groupName)) {
item.getNicknameLabel().setFont(new Font("Dialog", Font.PLAIN, 11));
item.getNicknameLabel().setForeground(Color.GRAY);
}
item.setGroupName(getGroupName());
contactItems.add(item);
List<ContactItem> tempItems = getContactItems();
Collections.sort(tempItems, itemComparator);
int index = tempItems.indexOf(item);
Object[] objs = contactItemList.getSelectedValues();
model.insertElementAt(item, index);
int[] intList = new int[objs.length];
for (int i = 0; i < objs.length; i++) {
ContactItem contact = (ContactItem)objs[i];
intList[i] = model.indexOf(contact);
}
if (intList.length > 0) {
contactItemList.setSelectedIndices(intList);
}
fireContactItemAdded(item);
}
/**
* Call whenever the UI needs to be updated.
*/
public void fireContactGroupUpdated() {
contactItemList.validate();
contactItemList.repaint();
updateTitle();
}
public void addContactGroup(ContactGroup contactGroup) {
final JPanel panel = new JPanel(new GridBagLayout());
panel.add(contactGroup, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(2, 15, 0, 0), 0, 0));
panel.setBackground(Color.white);
contactGroup.setSubPane(true);
// contactGroup.setStyle(CollapsiblePane.TREE_STYLE);
listPanel.add(panel);
contactGroups.add(contactGroup);
}
/**
* Removes a child ContactGroup.
*
* @param contactGroup the contact group to remove.
*/
public void removeContactGroup(ContactGroup contactGroup) {
Component[] comps = listPanel.getComponents();
for (int i = 0; i < comps.length; i++) {
Component comp = comps[i];
if (comp instanceof JPanel) {
JPanel panel = (JPanel)comp;
ContactGroup group = (ContactGroup)panel.getComponent(0);
if (group == contactGroup) {
listPanel.remove(panel);
break;
}
}
}
contactGroups.remove(contactGroup);
}
public void setPanelBackground(Color color) {
Component[] comps = listPanel.getComponents();
for (int i = 0; i < comps.length; i++) {
Component comp = comps[i];
if (comp instanceof JPanel) {
JPanel panel = (JPanel)comp;
panel.setBackground(color);
}
}
}
/**
* Returns a ContactGroup based on it's name.
*
* @param groupName the name of the group.
* @return the ContactGroup.
*/
public ContactGroup getContactGroup(String groupName) {
final Iterator groups = new ArrayList(contactGroups).iterator();
while (groups.hasNext()) {
ContactGroup group = (ContactGroup)groups.next();
if (group.getGroupName().equals(groupName)) {
return group;
}
}
return null;
}
/**
* Removes a <code>ContactItem</code>.
*
* @param item the ContactItem to remove.
*/
public void removeContactItem(ContactItem item) {
contactItems.remove(item);
model.removeElement(item);
updateTitle();
fireContactItemRemoved(item);
}
/**
* Returns a <code>ContactItem</code> by the nickname the user has been assigned.
*
* @param nickname the nickname of the user.
* @return the ContactItem.
*/
public ContactItem getContactItemByNickname(String nickname) {
final Iterator iter = new ArrayList(contactItems).iterator();
while (iter.hasNext()) {
ContactItem item = (ContactItem)iter.next();
if (item.getNickname().equals(nickname)) {
return item;
}
}
return null;
}
/**
* Returns a <code>ContactItem</code> by the users bare bareJID.
*
* @param bareJID the bareJID of the user.
* @return the ContactItem.
*/
public ContactItem getContactItemByJID(String bareJID) {
final Iterator iter = new ArrayList(contactItems).iterator();
while (iter.hasNext()) {
ContactItem item = (ContactItem)iter.next();
if (item.getJID().equals(bareJID)) {
return item;
}
}
return null;
}
/**
* Returns all <code>ContactItem</cod>s in the ContactGroup.
*
* @return all ContactItems.
*/
public List<ContactItem> getContactItems() {
final List<ContactItem> list = new ArrayList<ContactItem>(contactItems);
Collections.sort(list, itemComparator);
return list;
}
/**
* Returns the name of the ContactGroup.
*
* @return the name of the ContactGroup.
*/
public String getGroupName() {
return groupName;
}
public void mouseClicked(MouseEvent e) {
Object o = contactItemList.getSelectedValue();
if (!(o instanceof ContactItem)) {
return;
}
// Iterator through rest
ContactItem item = (ContactItem)o;
if (e.getClickCount() == 2) {
fireContactItemDoubleClicked(item);
}
else if (e.getClickCount() == 1) {
fireContactItemClicked(item);
}
}
public void mouseEntered(MouseEvent e) {
int loc = contactItemList.locationToIndex(e.getPoint());
Object o = model.getElementAt(loc);
if (!(o instanceof ContactItem)) {
return;
}
ContactItem item = (ContactItem)o;
if (item == null) {
return;
}
contactItemList.setCursor(GraphicUtils.HAND_CURSOR);
}
public void mouseExited(MouseEvent e) {
Object o = null;
try {
int loc = contactItemList.locationToIndex(e.getPoint());
if (loc == -1) {
return;
}
o = model.getElementAt(loc);
if (!(o instanceof ContactItem)) {
ContactInfoWindow.getInstance().dispose();
return;
}
}
catch (Exception e1) {
Log.error(e1);
return;
}
ContactItem item = (ContactItem)o;
if (item == null) {
return;
}
contactItemList.setCursor(GraphicUtils.DEFAULT_CURSOR);
}
public void mousePressed(MouseEvent e) {
checkPopup(e);
}
public void mouseReleased(MouseEvent e) {
checkPopup(e);
}
private void checkPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
// Otherwise, handle single selection
int index = contactItemList.locationToIndex(e.getPoint());
if (index != -1) {
int[] indexes = contactItemList.getSelectedIndices();
boolean selected = false;
for (int i = 0; i < indexes.length; i++) {
int o = indexes[i];
if (index == o) {
selected = true;
}
}
if (!selected) {
contactItemList.setSelectedIndex(index);
fireContactItemClicked((ContactItem)contactItemList.getSelectedValue());
}
}
final Collection selectedItems = SparkManager.getChatManager().getSelectedContactItems();
if (selectedItems.size() > 1) {
firePopupEvent(e, selectedItems);
return;
}
else if (selectedItems.size() == 1) {
final ContactItem contactItem = (ContactItem)selectedItems.iterator().next();
firePopupEvent(e, contactItem);
}
}
}
/**
* Add a <code>ContactGroupListener</code>.
*
* @param listener the ContactGroupListener.
*/
public void addContactGroupListener(ContactGroupListener listener) {
listeners.add(listener);
}
/**
* Removes a <code>ContactGroupListener</code>.
*
* @param listener the ContactGroupListener.
*/
public void removeContactGroupListener(ContactGroupListener listener) {
listeners.remove(listener);
}
private void fireContactItemClicked(ContactItem item) {
final Iterator iter = new ArrayList(listeners).iterator();
while (iter.hasNext()) {
((ContactGroupListener)iter.next()).contactItemClicked(item);
}
}
private void fireContactItemDoubleClicked(ContactItem item) {
final Iterator iter = new ArrayList(listeners).iterator();
while (iter.hasNext()) {
((ContactGroupListener)iter.next()).contactItemDoubleClicked(item);
}
}
private void firePopupEvent(MouseEvent e, ContactItem item) {
final Iterator iter = new ArrayList(listeners).iterator();
while (iter.hasNext()) {
((ContactGroupListener)iter.next()).showPopup(e, item);
}
}
private void firePopupEvent(MouseEvent e, Collection items) {
final Iterator iter = new ArrayList(listeners).iterator();
while (iter.hasNext()) {
((ContactGroupListener)iter.next()).showPopup(e, items);
}
}
private void fireContactGroupPopupEvent(MouseEvent e) {
final Iterator iter = new ArrayList(listeners).iterator();
while (iter.hasNext()) {
((ContactGroupListener)iter.next()).contactGroupPopup(e, this);
}
}
private void fireContactItemAdded(ContactItem item) {
final Iterator iter = new ArrayList(listeners).iterator();
while (iter.hasNext()) {
((ContactGroupListener)iter.next()).contactItemAdded(item);
}
}
private void fireContactItemRemoved(ContactItem item) {
final Iterator iter = new ArrayList(listeners).iterator();
while (iter.hasNext()) {
((ContactGroupListener)iter.next()).contactItemRemoved(item);
}
}
private void updateTitle() {
if ("Offline Group".equals(groupName)) {
setTitle("Offline Group");
return;
}
int count = 0;
List list = new ArrayList(getContactItems());
int size = list.size();
for (int i = 0; i < size; i++) {
ContactItem it = (ContactItem)list.get(i);
if (it.isAvailable()) {
count++;
}
}
setTitle(getGroupTitle(groupName) + " (" + count + " online)");
if (model.getSize() == 0) {
model.addElement(noContacts);
}
}
/**
* Returns the containing <code>JList</code> of the ContactGroup.
*
* @return the JList.
*/
public JList getList() {
return contactItemList;
}
/**
* Clears all selections within this group.
*/
public void clearSelection() {
contactItemList.clearSelection();
}
public void removeAllContacts() {
// Remove all users from online group.
Iterator contactItems = new ArrayList(getContactItems()).iterator();
while (contactItems.hasNext()) {
ContactItem item = (ContactItem)contactItems.next();
removeContactItem(item);
}
// Remove all users from offline group.
for (ContactItem item : getOfflineContacts()) {
removeOfflineContactItem(item);
}
}
/**
* Returns true if the ContactGroup contains available users.
*
* @return true if the ContactGroup contains available users.
*/
public boolean hasAvailableContacts() {
final Iterator iter = contactGroups.iterator();
while (iter.hasNext()) {
ContactGroup group = (ContactGroup)iter.next();
if (group.hasAvailableContacts()) {
return true;
}
}
Iterator contacts = getContactItems().iterator();
while (contacts.hasNext()) {
ContactItem item = (ContactItem)contacts.next();
if (item.getPresence() != null) {
return true;
}
}
return false;
}
public Collection<ContactItem> getOfflineContacts() {
return new ArrayList<ContactItem>(offlineContacts);
}
/**
* Sorts ContactItems.
*/
final Comparator<ContactItem> itemComparator = new Comparator() {
public int compare(Object contactItemOne, Object contactItemTwo) {
final ContactItem item1 = (ContactItem)contactItemOne;
final ContactItem item2 = (ContactItem)contactItemTwo;
return item1.getNickname().toLowerCase().compareTo(item2.getNickname().toLowerCase());
}
};
/**
* Returns true if this ContactGroup is the Offline Group.
*
* @return true if OfflineGroup.
*/
public boolean isOfflineGroup() {
return "Offline Group".equals(getGroupName());
}
/**
* Returns true if this ContactGroup is the Unfiled Group.
*
* @return true if UnfiledGroup.
*/
public boolean isUnfiledGroup() {
return "Unfiled".equals(getGroupName());
}
public String toString() {
return getGroupName();
}
/**
* Returns true if ContactGroup is a Shared Group.
*
* @return true if Shared Group.
*/
public boolean isSharedGroup() {
return sharedGroup;
}
/**
* Set to true if this ContactGroup is a shared Group.
*
* @param sharedGroup true if shared group.
*/
protected void setSharedGroup(boolean sharedGroup) {
this.sharedGroup = sharedGroup;
if (sharedGroup) {
setToolTipText(Res.getString("message.is.shared.group", getGroupName()));
}
}
/**
* Returns all Selected Contacts within the ContactGroup.
*
* @return all selected ContactItems.
*/
public List getSelectedContacts() {
final List items = new ArrayList();
Object[] selections = contactItemList.getSelectedValues();
final int no = selections != null ? selections.length : 0;
for (int i = 0; i < no; i++) {
ContactItem item = (ContactItem)selections[i];
items.add(item);
}
return items;
}
public JPanel getContainerPanel() {
return listPanel;
}
public Collection getContactGroups() {
return contactGroups;
}
/**
* Lets make sure that the panel doesn't stretch past the
* scrollpane view pane.
*
* @return the preferred dimension
*/
public Dimension getPreferredSize() {
final Dimension size = super.getPreferredSize();
size.width = 0;
return size;
}
/**
* Sets the name of group.
*
* @param groupName the contact group name.
*/
public void setGroupName(String groupName) {
this.groupName = groupName;
}
/**
* Returns the "pretty" title of the ContactGroup.
*
* @param title the title.
* @return the new title.
*/
public String getGroupTitle(String title) {
int lastIndex = title.lastIndexOf("::");
if (lastIndex != -1) {
title = title.substring(lastIndex + 2);
}
return title;
}
/**
* Returns true if the group is nested.
*
* @param groupName the name of the group.
* @return true if the group is nested.
*/
public boolean isSubGroup(String groupName) {
return groupName.indexOf("::") != -1;
}
/**
* Returns true if this group is nested.
*
* @return true if nested.
*/
public boolean isSubGroup() {
return isSubGroup(getGroupName());
}
/**
* Returns the underlying container for the JList.
*
* @return the underlying container of the JList.
*/
public JPanel getListPanel() {
return listPanel;
}
/**
* Adds an internal popup listesner.
*/
private void addPopupWindow() {
final Timer timer = new Timer(500, new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
canShowPopup = true;
}
});
contactItemList.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent mouseEvent) {
timer.start();
}
public void mouseExited(MouseEvent mouseEvent) {
timer.stop();
canShowPopup = false;
ContactInfoWindow.getInstance().dispose();
}
});
contactItemList.addMouseMotionListener(motionListener);
}
private class ListMotionListener extends MouseMotionAdapter {
public void mouseMoved(MouseEvent e) {
if (e != null) {
mouseEvent = e;
}
if (!canShowPopup) {
return;
}
if (e == null) {
return;
}
displayWindow(e);
}
}
/**
* Displays the <code>ContactInfoWindow</code>.
*
* @param e the mouseEvent that triggered this event.
*/
private void displayWindow(MouseEvent e) {
ContactInfoWindow.getInstance().display(this, e);
}
}
|
// Unless required by applicable law or agreed to in writing, software /
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /
package br.shura.venus.compiler;
import br.shura.venus.compiler.Token.Type;
import br.shura.venus.component.ArrayAttribution;
import br.shura.venus.component.AsyncContainer;
import br.shura.venus.component.Attribution;
import br.shura.venus.component.Component;
import br.shura.venus.component.Container;
import br.shura.venus.component.FunctionCall;
import br.shura.venus.component.Script;
import br.shura.venus.component.SimpleContainer;
import br.shura.venus.component.branch.Break;
import br.shura.venus.component.branch.Breakable;
import br.shura.venus.component.branch.Continue;
import br.shura.venus.component.branch.DoWhileContainer;
import br.shura.venus.component.branch.ElseContainer;
import br.shura.venus.component.branch.ElseIfContainer;
import br.shura.venus.component.branch.ForEachContainer;
import br.shura.venus.component.branch.ForRangeContainer;
import br.shura.venus.component.branch.IfContainer;
import br.shura.venus.component.branch.Return;
import br.shura.venus.component.branch.WhileContainer;
import br.shura.venus.exception.compile.ScriptCompileException;
import br.shura.venus.exception.compile.UnexpectedTokenException;
import br.shura.venus.function.Argument;
import br.shura.venus.function.Definition;
import br.shura.venus.library.VenusLibrary;
import br.shura.venus.operator.BinaryOperator;
import br.shura.venus.operator.Operator;
import br.shura.venus.operator.OperatorList;
import br.shura.venus.resultor.ArrayAccess;
import br.shura.venus.resultor.ArrayDefine;
import br.shura.venus.resultor.BinaryOperation;
import br.shura.venus.resultor.Constant;
import br.shura.venus.resultor.FunctionRef;
import br.shura.venus.resultor.Resultor;
import br.shura.venus.resultor.Variable;
import br.shura.venus.value.BoolValue;
import br.shura.venus.value.DecimalValue;
import br.shura.venus.value.IntegerValue;
import br.shura.venus.value.StringValue;
import br.shura.venus.value.TypeValue;
import br.shura.venus.value.Value;
import br.shura.venus.value.ValueType;
import br.shura.venus.value.VariableRefValue;
import br.shura.x.charset.build.TextBuilder;
import br.shura.x.collection.list.List;
import br.shura.x.collection.list.impl.ArrayList;
import br.shura.x.math.number.BaseConverter;
import br.shura.x.util.Pool;
import br.shura.x.worker.ParseWorker;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class VenusParser {
private Container container;
private VenusLexer lexer;
private boolean nextAsyncable;
private boolean nextDaemon;
private final Script script;
public VenusParser(Script script) {
this.script = script;
}
public void parse(VenusLexer lexer, Container c) throws ScriptCompileException {
this.container = c;
this.lexer = lexer;
Token token;
boolean justExitedIfContainer = false;
while ((token = lexer.nextToken()) != null) {
if (token.getType() == Type.DOLLAR_SIGN) {
Token next = requireToken(Type.NAME_DEFINITION, "expected a variable name");
parseAttributionOrFunctionCall('$' + next.getValue(), false);
}
else if (token.getType() == Type.NAME_DEFINITION) {
if (token.getValue().equals(KeywordDefinitions.ASYNC)) {
if (nextAsyncable) {
bye(token, "duplicated 'async' keyword");
}
this.nextAsyncable = true;
}
else if (token.getValue().equals(KeywordDefinitions.BREAK) || token.getValue().equals(KeywordDefinitions.CONTINUE)) {
requireToken(Type.NEW_LINE, "expected a new line");
Container lookup = container;
boolean foundContinuable = false;
while (lookup != null) {
if (lookup instanceof Breakable) {
foundContinuable = true;
break;
}
// If there is a definition, at run-time it will be another context,
// so do not let lookuping parents
if (lookup instanceof Definition) {
break;
}
lookup = lookup.getParent();
}
if (foundContinuable) {
addComponent(token.getValue().equals(KeywordDefinitions.BREAK) ? new Break() : new Continue(), false);
}
else {
bye(token, "there is no parent container available");
}
}
else if (token.getValue().equals(KeywordDefinitions.DAEMON)) {
if (nextAsyncable) {
if (nextDaemon) {
bye(token, "duplicated 'daemon' keyword");
}
this.nextDaemon = true;
}
else {
bye(token, "'daemon' keyword must come after an 'async' keyword");
}
}
else if (token.getValue().equals(KeywordDefinitions.DEFINE)) {
parseDefinition();
}
else if (token.getValue().equals(KeywordDefinitions.DO)) {
requireToken(Type.OPEN_BRACE, "expected an open brace");
addContainer(new DoWhileContainer(null), true);
}
else if (token.getValue().equals(KeywordDefinitions.ELSE)) {
if (justExitedIfContainer) {
parseElse();
}
else {
bye(token, "no previous 'if' container");
}
}
else if (token.getValue().equals(KeywordDefinitions.EXPORT)) {
if (container == script) {
parseExport();
}
else {
bye(token, "cannot use 'export' keyword inside container");
}
}
else if (token.getValue().equals(KeywordDefinitions.FOR)) {
parseFor();
}
else if (token.getValue().equals(KeywordDefinitions.IF)) {
parseIf(false);
}
else if (token.getValue().equals(KeywordDefinitions.INCLUDE)) {
if (container == script) {
parseInclude();
}
else {
bye(token, "cannot use 'import' keyword inside container");
}
}
else if (token.getValue().equals(KeywordDefinitions.RETURN)) {
parseReturn();
}
else if (token.getValue().equals(KeywordDefinitions.USING)) {
if (container == script) {
parseUsing();
}
else {
bye(token, "cannot use 'using' keyword inside container");
}
}
else if (token.getValue().equals(KeywordDefinitions.WHILE)) {
parseWhile();
}
else {
parseAttributionOrFunctionCall(token.getValue(), true);
}
justExitedIfContainer = false;
}
else if (token.getType() == Type.OPEN_BRACE) {
addContainer(new SimpleContainer(), true);
}
else if (token.getType() == Type.CLOSE_BRACE) {
if (container != script) {
if (container instanceof IfContainer) {
justExitedIfContainer = true;
}
if (container instanceof DoWhileContainer) {
DoWhileContainer doWhileContainer = (DoWhileContainer) container;
Token test = lexer.nextToken();
if (test.getType() == Type.NEW_LINE) {
test = lexer.nextToken();
}
if (test.getType() == Type.NAME_DEFINITION && test.getValue().equals(KeywordDefinitions.WHILE)) {
Resultor resultor = readResultor(Type.NEW_LINE);
doWhileContainer.setCondition(resultor);
}
else {
lexer.reRead(test);
}
}
do {
this.container = container.getParent();
}
while (container instanceof AsyncContainer);
}
else {
bye(token, "no container to close");
}
}
else if (token.getType() != Type.NEW_LINE) {
bye(token, "expected a name definition or close brace");
}
}
}
protected void addComponent(Component component, boolean asyncable) throws UnexpectedTokenException {
if (nextAsyncable && !asyncable) {
this.nextAsyncable = false;
bye("Cannot apply 'async' keyword to component " + component);
}
if (asyncable && nextAsyncable) {
AsyncContainer asyncContainer = new AsyncContainer(nextDaemon);
asyncContainer.setSourceLine(lexer.currentLine());
container.getChildren().add(asyncContainer);
asyncContainer.getChildren().add(component);
this.nextAsyncable = false;
this.nextDaemon = false;
}
else {
component.setSourceLine(lexer.currentLine());
container.getChildren().add(component);
}
}
protected void addContainer(Container container, boolean asyncable) throws UnexpectedTokenException {
addComponent(container, asyncable);
this.container = container;
}
protected void bye(String message) throws UnexpectedTokenException {
throw new UnexpectedTokenException(script.getDisplayName(), lexer.currentLine(), message);
}
// Do not call other bye() method, for better stacktrace
protected void bye(Token token, String message) throws UnexpectedTokenException {
throw new UnexpectedTokenException(script.getDisplayName(), lexer.currentLine(), "Invalid token \"" + token + "\"; " + message);
}
protected Value getValueOf(Token token) throws ScriptCompileException {
String value = token.getValue();
if (token.getType() == Type.BINARY_LITERAL) {
try {
return new IntegerValue(BaseConverter.encodeToLong(value, BaseConverter.BINARY));
}
catch (NumberFormatException exception) {
bye(token, "illegal binary value \"" + value + "\"");
}
}
if (token.getType() == Type.COLON) {
Token next = requireToken();
if (next.getType() == Type.DOLLAR_SIGN) {
Token next2 = requireToken();
if (next2.getType() == Type.NAME_DEFINITION) {
return new VariableRefValue(new Variable(next.getValue() + next2.getValue()));
}
lexer.reRead(next2);
}
else if (next.getType() == Type.NAME_DEFINITION) {
return new VariableRefValue(new Variable(next.getValue()));
}
lexer.reRead(next);
}
if (token.getType() == Type.CHAR_LITERAL || token.getType() == Type.STRING_LITERAL) {
return new StringValue(value);
}
if (token.getType() == Type.DECIMAL_LITERAL) {
if (ParseWorker.isLong(value)) {
return new IntegerValue(ParseWorker.toLong(value));
}
if (ParseWorker.isDouble(value)) {
return new DecimalValue(ParseWorker.toDouble(value));
}
bye(token, "illegal decimal value \"" + value + "\"");
}
if (token.getType() == Type.HEXADECIMAL_LITERAL) {
try {
return new IntegerValue(BaseConverter.encodeToLong(value, BaseConverter.HEXADECIMAL));
}
catch (NumberFormatException exception) {
bye(token, "illegal hexadecimal value \"" + value + "\"");
}
}
if (token.getType() == Type.NAME_DEFINITION) {
if (value.equals(KeywordDefinitions.TRUE)) {
return new BoolValue(true);
}
if (value.equals(KeywordDefinitions.FALSE)) {
return new BoolValue(false);
}
}
if (token.getType() == Type.OPERATOR && token.getValue().equals("*")) {
Token next = requireToken();
if (next.getType() == Type.NAME_DEFINITION) {
String keyword = next.getValue();
ValueType type = ValueType.forIdentifier(keyword);
if (type != null) {
return new TypeValue(type);
}
}
lexer.reRead(next);
}
return null;
}
// This is called when we already parsed the name and the OPEN_BRACKET token (so we go
// directly to parsing the index)
protected void parseArrayAttribution(String name) throws ScriptCompileException {
Resultor index = readResultor(Type.CLOSE_BRACKET);
Token operatorToken = requireToken(Type.OPERATOR, "expected an attribution operator");
Resultor resultor = parseAttributionHelper(name, operatorToken);
ArrayAttribution attribution = new ArrayAttribution(name, index, resultor);
addComponent(attribution, false);
}
protected void parseAttribution(String name, Token operatorToken) throws ScriptCompileException {
Resultor resultor = parseAttributionHelper(name, operatorToken);
Attribution attribution = new Attribution(name, resultor);
addComponent(attribution, false);
}
protected Resultor parseAttributionHelper(String name, Token operatorToken) throws ScriptCompileException {
String attribOperator = operatorToken.getValue();
if (attribOperator.equals("=")) {
return readResultor(Type.NEW_LINE);
}
attribOperator = readOperator(attribOperator);
if (attribOperator.endsWith("=")) {
String operatorIdentifier = attribOperator.substring(0, attribOperator.length() - 1);
Operator operator = OperatorList.forIdentifier(operatorIdentifier, false); // false for bye(excepted bin opr)
if (operator != null) {
if (operator instanceof BinaryOperator) {
Resultor resultor = readResultor(Type.NEW_LINE);
return new BinaryOperation((BinaryOperator) operator, new Variable(name), resultor);
}
bye(operatorToken, "expected an attribution with binary operator (+=, -=, ...)");
}
else {
bye(operatorToken, "expected a valid attribution operator (=, +=, -=, ...)");
}
}
else {
bye(operatorToken, "expected an attribution operator (=, +=, -=, ...)");
}
bye(operatorToken, "reached end of parseAttributionHelper");
return null; // Will not happen
}
protected void parseAttributionOrFunctionCall(String name, boolean canBeFunctionCall) throws ScriptCompileException {
Token next = requireToken();
if (next.getType() == Type.OPEN_BRACKET) {
parseArrayAttribution(name);
}
else if (next.getType() == Type.OPERATOR) {
parseAttribution(name, next);
}
else if (next.getType() == Type.OPEN_PARENTHESE && canBeFunctionCall) {
Resultor[] arguments = readFunctionArguments();
requireNewLine();
addComponent(new FunctionCall(name, arguments), true);
}
else {
bye(next, "expected attribution operator or function call");
}
}
protected void parseDefinition() throws ScriptCompileException {
Token typeToken = requireToken(Type.NAME_DEFINITION, "expected a return type");
String definitionName = typeToken.getValue();
List<Argument> arguments = new ArrayList<>();
requireToken(Type.OPEN_PARENTHESE, "expected an open parenthese");
Token reading;
while ((reading = requireToken()).getType() != Type.CLOSE_PARENTHESE) { // Reads definition arguments
if (reading.getType() == Type.NAME_DEFINITION) {
ValueType argumentType = ValueType.forIdentifier(reading.getValue());
if (argumentType != null) {
Token argumentToken = requireToken(Type.NAME_DEFINITION, "expected an argument name");
String argumentName = argumentToken.getValue();
if (!KeywordDefinitions.isKeyword(argumentName)) {
arguments.add(new Argument(argumentName, argumentType));
Token commaOrClose = requireToken();
if (commaOrClose.getType() == Type.CLOSE_PARENTHESE) {
break;
}
if (commaOrClose.getType() != Type.COMMA) {
bye(commaOrClose, "expected an argument separator (comma) or close parenthese");
}
}
else {
bye(reading, "argument name cannot be a keyword");
}
}
else {
bye(reading, "expected an argument type (" + new ArrayList<>(ValueType.values()).toString(", ") + ')');
}
}
else {
bye(reading, "expected an argument name");
}
}
requireToken(Type.OPEN_BRACE, "expected an open brace");
addContainer(new Definition(definitionName, arguments), false);
}
protected void parseElse() throws ScriptCompileException {
Token next = requireToken();
if (next.getType() == Type.NAME_DEFINITION && next.getValue().equals(KeywordDefinitions.IF)) {
parseIf(true);
}
else {
lexer.reRead(next);
requireToken(Type.OPEN_BRACE, "expected an open brace");
addContainer(new ElseContainer(), false);
}
}
protected void parseExport() throws ScriptCompileException {
Token nameToken = requireToken(Type.NAME_DEFINITION, "expected a variable name");
String variableName = nameToken.getValue();
if (!KeywordDefinitions.isKeyword(variableName)) {
Token attributionToken = requireToken();
if (attributionToken.getType() == Type.OPERATOR && attributionToken.getValue().equals("=")) {
Value value = readValue();
script.getApplicationContext().setVar(variableName, value);
requireNewLine();
}
else {
bye(attributionToken, "expected an attribution character '='");
}
}
else {
bye(nameToken, "variable name cannot be a keyword");
}
}
protected void parseFor() throws ScriptCompileException {
Token varNameToken = requireToken(Type.NAME_DEFINITION, "expected a variable name");
requireToken(Type.NAME_DEFINITION, "expected 'in' token");
Token next = requireToken();
if (next.getType() == Type.OPEN_PARENTHESE) {
Resultor[] arguments = readFunctionArguments();
requireToken(Type.OPEN_BRACE, "expected an open brace");
if (arguments.length == 2 || arguments.length == 3) {
String varName = varNameToken.getValue();
ForRangeContainer forContainer = new ForRangeContainer(varName, arguments[0], arguments[1],
arguments.length == 3 ? arguments[2] : new BinaryOperation(OperatorList.PLUS, new Variable(varName),
new Constant(new IntegerValue(1))));
addContainer(forContainer, true);
}
else {
bye("Expected 2 arguments to for definition; received " + arguments.length);
}
}
else {
lexer.reRead(next);
Resultor iterable = readResultor(Type.OPEN_BRACE);
String varName = varNameToken.getValue();
ForEachContainer forContainer = new ForEachContainer(varName, iterable);
addContainer(forContainer, true);
}
}
protected void parseIf(boolean isElseIf) throws ScriptCompileException {
Resultor resultor = readResultor(Type.OPEN_BRACE);
IfContainer ifContainer = isElseIf ? new ElseIfContainer(resultor) : new IfContainer(resultor);
addContainer(ifContainer, false);
}
protected void parseInclude() throws ScriptCompileException {
Token next = requireToken(Type.STRING_LITERAL, "expected a string literal as including script");
String includeName = next.getValue();
boolean maybe = false;
Token maybeOrNewLine = requireToken();
if (maybeOrNewLine.getType() == Type.NAME_DEFINITION) {
if (maybeOrNewLine.getValue().equals("maybe")) {
maybe = true;
requireToken(Type.NEW_LINE, "expected new line");
}
else {
bye(maybeOrNewLine, "expected 'maybe' or new line");
}
}
else if (maybeOrNewLine.getType() != Type.NEW_LINE) {
bye(maybeOrNewLine, "expected 'maybe' or new line");
}
try {
script.include(includeName, maybe);
}
catch (ScriptCompileException exception) {
bye('"' + exception.getMessage() + '"');
}
}
protected void parseReturn() throws ScriptCompileException {
Token test = lexer.nextToken();
if (test == null || test.getType() == Type.NEW_LINE) {
addComponent(new Return(null), false);
}
else {
lexer.reRead(test);
addComponent(new Return(readResultor(Type.NEW_LINE)), false);
}
}
protected void parseUsing() throws ScriptCompileException {
Token nameToken = requireToken(Type.NAME_DEFINITION, "expected a library name (without quotes)");
requireNewLine();
String libraryName = nameToken.getValue();
Supplier<VenusLibrary> supplier = script.getApplicationContext().getLibrarySuppliers().get(libraryName);
VenusLibrary library;
if (supplier != null && (library = supplier.get()) != null) {
script.getLibraryList().add(library);
}
else {
bye(nameToken, "could not find a library named \"" + libraryName + "\"");
}
}
protected void parseWhile() throws ScriptCompileException {
Resultor resultor = readResultor(Type.OPEN_BRACE);
WhileContainer whileContainer = new WhileContainer(resultor);
addContainer(whileContainer, true);
}
protected Resultor[] readFunctionArguments() throws ScriptCompileException {
return readResultors(Type.COMMA, Type.CLOSE_PARENTHESE);
}
protected String readOperator(String start) throws ScriptCompileException {
TextBuilder operatorStr = Pool.newBuilder();
Token operatorToken;
if (start != null) {
operatorStr.append(start);
}
while ((operatorToken = requireToken()).getType() == Type.OPERATOR) {
String op = operatorToken.getValue();
if (OperatorList.forIdentifier(op, true) != null && !operatorStr.isEmpty()) {
break;
}
operatorStr.append(operatorToken.getValue());
}
lexer.reRead(operatorToken); // Last token have type != OPERATOR
return operatorStr.toStringAndClear();
}
protected Resultor readResultor(Predicate<Token> process) throws ScriptCompileException {
return readResultor(process, token -> false);
}
protected Resultor readResultor(Predicate<Token> process, Predicate<Token> reReadLast) throws ScriptCompileException {
BuildingResultor resultor = new BuildingResultor();
String nameDef = null;
Token nameDefToken = null;
Token token;
while (process.test(token = requireToken())) {
if (nameDef == null) {
Value value;
try {
value = getValueOf(token);
if (value != null) {
resultor.addResultor(this, token, new Constant(value));
continue;
}
}
catch (UnexpectedTokenException exception) {
}
}
if (token.getType() == Type.AT_SIGN) {
Token next = requireToken(Type.NAME_DEFINITION, "expected a function name as reference");
resultor.addResultor(this, next, new FunctionRef(next.getValue()));
}
else if (token.getType() == Type.DOLLAR_SIGN) {
Token next = requireToken(Type.NAME_DEFINITION, "expected a variable name");
resultor.addResultor(this, next, new Variable(token.getValue() + next.getValue()));
}
else if (token.getType() == Type.OPERATOR) {
if (nameDef != null) {
resultor.addResultor(this, nameDefToken, new Variable(nameDef));
nameDef = null;
}
String operatorStr = readOperator(token.getValue());
Operator operator = OperatorList.forIdentifier(operatorStr, !resultor.hasResultor());
if (operator != null) {
resultor.addOperator(this, token, operator);
}
else {
bye(token, "expected a valid attribution operator (=, +=, -=, ...)");
}
}
else if (token.getType() == Type.OPEN_BRACKET) {
if (nameDef != null) {
Resultor index = readResultor(Type.CLOSE_BRACKET);
resultor.addResultor(this, nameDefToken, new ArrayAccess(nameDef, index));
nameDef = null;
}
else {
Resultor[] resultors = readResultors(Type.COMMA, Type.CLOSE_BRACKET);
resultor.addResultor(this, token, new ArrayDefine(resultors));
}
}
else if (token.getType() == Type.OPEN_PARENTHESE) {
if (nameDef != null) {
Resultor[] arguments = readFunctionArguments();
resultor.addResultor(this, nameDefToken, new FunctionCall(nameDef, arguments));
nameDef = null;
}
else {
resultor.addResultor(this, token, readResultor(Type.CLOSE_PARENTHESE));
}
}
else if (token.getType() == Type.NAME_DEFINITION) {
nameDef = token.getValue();
nameDefToken = token;
}
else if (nameDef != null) {
bye(token, "expected open parenthese (function) or operator after a name definition");
}
else if (token.getType() != Type.NEW_LINE) {
bye(token, "unexpected token");
}
}
if (nameDef != null) {
resultor.addResultor(this, nameDefToken, new Variable(nameDef));
}
if (reReadLast.test(token)) {
lexer.reRead(token);
}
Resultor result = resultor.build();
if (result == null) {
bye(token, "expected a resultor/value");
}
return result;
}
protected Resultor readResultor(Type stopAt) throws ScriptCompileException {
return readResultor(stopAt, token -> false);
}
protected Resultor readResultor(Type stopAt, Predicate<Token> reReadLast) throws ScriptCompileException {
return readResultor(token -> token.getType() != stopAt, reReadLast);
}
// This also consumes the last 'end' token
protected Resultor[] readResultors(Type separator, Type end) throws ScriptCompileException {
List<Resultor> result = new ArrayList<>();
Token token;
while ((token = requireToken()).getType() != end) {
lexer.reRead(token);
result.add(readResultor(
t -> t.getType() != end && t.getType() != separator,
t -> t.getType() == end));
}
return result.toArray();
}
protected Value readValue() throws ScriptCompileException {
Token token = requireToken();
Value value = getValueOf(token);
if (value == null) {
bye(token, "expected a value literal (array/boolean/char/number/string/type)");
}
return value;
}
protected void requireNewLine() throws ScriptCompileException {
Token token = requireToken();
if (token.getType() != Type.NEW_LINE) {
bye(token, "expected a new line");
}
}
protected Token requireToken() throws ScriptCompileException {
Token token = lexer.nextToken();
if (token == null) {
bye("Unexpected end of file");
}
return token;
}
protected Token requireToken(Type type, String errorMessage) throws ScriptCompileException {
Token token = requireToken();
if (token.getType() != type) {
bye(token, errorMessage);
}
return token;
}
}
|
package ch.ntb.inf.deep.runtime.mpc555;
import ch.ntb.inf.deep.unsafe.US;
/* changes:
* 11.11.10 NTB/Urs Graf creation
* 22.1.11 Urs Graf newstring added
*/
public class Heap implements ntbMpc555HB {
static private int heapBase;
static private int heapPtr;
// called by new
private static int newObject(int ref) {
int size = US.GET4(ref) + 8;
int addr = heapPtr;
while (addr < heapPtr + size) {US.PUT4(addr, 0); addr += 4;}
US.PUT4(heapPtr + 4, ref); // write tag
ref = heapPtr + 8;
heapPtr += ((size + 15) >> 4) << 4;
return ref;
}
// called by newarray
private static int newPrimTypeArray(int nofElements, int type, int ref) {
int elementSize;
if (type == 7 || type == 11) elementSize = 8;
else if (type == 6 || type == 10) elementSize = 4;
else if (type == 5 || type == 9) elementSize = 2;
else elementSize = 1;
int size = nofElements * elementSize + 8;
int addr = heapPtr;
while (addr < heapPtr + size) {US.PUT4(addr, 0); addr += 4;}
US.PUT4(heapPtr + 4, ref); // write tag
US.PUT2(heapPtr + 2, nofElements); // write length
ref = heapPtr + 8;
heapPtr += ((size + 15) >> 4) << 4;
return ref;
}
// called by anewarray
private static int newRefArray(int nofElements, int ref) {
int size = nofElements * 4 + 8;
int addr = heapPtr;
while (addr < heapPtr + size) {US.PUT4(addr, 0); addr += 4;}
US.PUT4(heapPtr + 4, ref); // write tag
US.PUT2(heapPtr + 2, nofElements); // write length
ref = heapPtr + 8;
heapPtr += ((size + 15) >> 4) << 4;
return ref;
}
// called by multianewarray
private static int newMultiDimArray(int ref, int nofDim, int dim0, int dim1, int dim2, int dim3) {
if (nofDim > 3 || nofDim < 2) US.HALT(20);
if (nofDim == 2) {
int elemSize = US.GET4(ref);
int dim1Size = (8 + dim1 * elemSize + 3) >> 2 << 2;
int size = 8 + dim0 * 4 + dim0 * dim1Size;
int addr = heapPtr;
while (addr < heapPtr + size) {US.PUT4(addr, 0); addr += 4;}
US.PUT4(heapPtr + 4, ref); // write tag
US.PUT2(heapPtr + 2, dim0); // write length of dim0
int dim1Ref = US.GET4(ref + 4);
if (dim1Ref == -1) dim1Ref = ref;
ref = heapPtr + 8;
addr = ref;
for (int i = 0; i < dim0; i++) {
int elemAddr = ref + 4 * dim0 + i * dim1Size + 8;
US.PUT4(addr, elemAddr);
US.PUT4(elemAddr - 4, dim1Ref); // write tag
US.PUT2(elemAddr - 6, dim1); // write length of dim0
addr += 4;
}
heapPtr += ((size + 15) >> 4) << 4;
} else { // nofDim == 3
int elemSize = US.GET4(ref);
int dim1Size = 8 + dim1 * 4;
int dim2Size = (8 + dim2 * elemSize + 3) >> 2 << 2;
int size = 8 + dim0 * 4 + dim0 * dim1Size + dim0 * dim1 * dim2Size;
int addr = heapPtr;
while (addr < heapPtr + size) {US.PUT4(addr, 0); addr += 4;}
US.PUT4(heapPtr + 4, ref); // write tag of dim0
US.PUT2(heapPtr + 2, dim0); // write length of dim0
int dim1Ref = US.GET4(ref + 4);
if (dim1Ref == -1) dim1Ref = ref;
int dim2Ref = US.GET4(dim1Ref + 4);
if (dim2Ref == -1) dim2Ref = ref;
ref = heapPtr + 8;
addr = ref;
for (int i = 0; i < dim0; i++) {
int elem1Addr = ref + 4 * dim0 + i * dim1Size + 8;
US.PUT4(addr, elem1Addr);
US.PUT4(elem1Addr - 4, dim1Ref); // write tag of dim1
US.PUT2(elem1Addr - 6, dim1); // write length of dim1
for (int j = 0; j < dim1; j++) {
int elem2Addr = ref + 4 * dim0 + dim0 * dim1Size + j * dim2Size + 8;
US.PUT4(elem1Addr, elem2Addr);
US.PUT4(elem2Addr - 4, dim2Ref); // write tag of dim2
US.PUT2(elem2Addr - 6, dim2); // write length of dim2
elem1Addr += 4;
}
addr += 4;
}
heapPtr += ((size + 15) >> 4) << 4;
}
return ref;
}
// called by newstring in java/lang/String
public static int newstring(int ref, int len) {
int size = len + 8;
int addr = heapPtr;
while (addr < heapPtr + size) {US.PUT4(addr, 0); addr += 4;}
US.PUT4(heapPtr + 4, ref); // write tag
ref = heapPtr + 8;
heapPtr += ((size + 15) >> 4) << 4;
return ref;
}
static {
int heapOffset = US.GET4(sysTabBaseAddr + stHeapOffset);
heapBase = US.GET4(sysTabBaseAddr + heapOffset * 4 + 4);
heapPtr = heapBase;
}
}
|
package jsaf.provider.windows.system;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.slf4j.cal10n.LocLogger;
import jsaf.Message;
import jsaf.intf.io.IFilesystem;
import jsaf.intf.system.IEnvironment;
import jsaf.intf.windows.identity.IDirectory;
import jsaf.intf.windows.io.IWindowsFilesystem;
import jsaf.intf.windows.powershell.IRunspacePool;
import jsaf.intf.windows.registry.IKey;
import jsaf.intf.windows.registry.IRegistry;
import jsaf.intf.windows.registry.IStringValue;
import jsaf.intf.windows.registry.IValue;
import jsaf.intf.windows.system.IWindowsSession;
import jsaf.intf.windows.wmi.IWmiProvider;
import jsaf.io.fs.AbstractFilesystem;
import jsaf.provider.AbstractSession;
import jsaf.provider.windows.identity.Directory;
import jsaf.provider.windows.io.WindowsFilesystem;
import jsaf.provider.windows.powershell.RunspacePool;
import jsaf.provider.windows.registry.Registry;
import jsaf.provider.windows.wmi.WmiProvider;
/**
* Windows implementation of ISession for local machines, using JACOB for WMI access via COM.
*
* @author David A. Solin
* @version %I% %G%
*/
public class WindowsSession extends AbstractSession implements IWindowsSession {
private WmiProvider wmi;
private boolean is64bit = false;
private Registry reg32, reg;
private IWindowsFilesystem fs32;
private Directory directory = null;
private RunspacePool runspaces = null;
private List<String> baseCommand = Arrays.asList("cmd", "/c");
private View accessorView = null;
// Load the JACOB DLL
static {
if ("32".equals(System.getProperty("sun.arch.data.model"))) {
System.loadLibrary("jacob-1.15-M4-x86");
} else {
System.loadLibrary("jacob-1.15-M4-x64");
}
}
public WindowsSession(File wsdir) {
super();
this.wsdir = wsdir;
}
protected List<String> getBaseCommand() {
return baseCommand;
}
// Implement ILoggable
@Override
public void setLogger(LocLogger logger) {
super.setLogger(logger);
if (fs32 != null && !fs32.equals(fs)) {
fs32.setLogger(logger);
}
if (wmi != null) {
wmi.setLogger(logger);
}
if (directory != null) {
directory.setLogger(logger);
}
}
// Implement ISession
@Override
public void dispose() {
super.dispose();
if (fs32 instanceof AbstractFilesystem) {
((AbstractFilesystem)fs32).dispose();
}
}
public boolean connect() {
if (env == null) {
try {
env = new Environment(this);
} catch (Exception e) {
logger.warn(Message.getMessage(Message.ERROR_EXCEPTION), e);
return false;
}
}
is64bit = ((Environment)env).is64bit();
if (is64bit) {
if ("64".equals(System.getProperty("sun.arch.data.model"))) {
accessorView = View._64BIT;
} else {
accessorView = View._32BIT;
StringBuffer cmd = new StringBuffer(System.getenv("SystemRoot")).append("\\SysNative\\cmd.exe");
baseCommand = Arrays.asList(cmd.toString(), "/c");
}
logger.trace(Message.STATUS_WINDOWS_BITNESS, "64");
} else {
accessorView = View._32BIT;
logger.trace(Message.STATUS_WINDOWS_BITNESS, "32");
}
if (runspaces == null) {
runspaces = new RunspacePool(this, 100);
}
if (reg == null) {
try {
reg = new Registry(this);
} catch (Exception e) {
logger.warn(Message.getMessage(Message.ERROR_EXCEPTION), e);
return false;
}
if (!is64bit) reg32 = reg;
}
if (wmi == null) {
wmi = new WmiProvider(this);
}
if (fs == null) {
try {
if (is64bit) {
fs = new WindowsFilesystem(this, View._64BIT, accessorView);
} else {
fs32 = new WindowsFilesystem(this, View._32BIT, accessorView);
fs = fs32;
}
} catch (Exception e) {
logger.warn(Message.getMessage(Message.ERROR_EXCEPTION), e);
return false;
}
}
if (wmi.register()) {
connected = true; // set this now so the IDirectory has access to the machine name
if (directory == null) {
try {
directory = new Directory(this);
} catch (Exception e) {
logger.warn(Message.getMessage(Message.ERROR_EXCEPTION), e);
connected = false;
return false;
}
}
return true;
} else {
return false;
}
}
public void disconnect() {
runspaces.shutdown();
wmi.deregister();
connected = false;
}
public Type getType() {
return Type.WINDOWS;
}
@Override
public String getMachineName() {
if (isConnected()) {
try {
IKey key = reg.getKey(IRegistry.Hive.HKLM, IRegistry.COMPUTERNAME_KEY);
IValue val = key.getValue(IRegistry.COMPUTERNAME_VAL);
if (val.getType() == IValue.Type.REG_SZ) {
return ((IStringValue)val).getData();
} else {
logger.warn(Message.ERROR_MACHINENAME);
}
} catch (Exception e) {
logger.warn(Message.ERROR_MACHINENAME);
logger.warn(Message.getMessage(Message.ERROR_EXCEPTION), e);
}
}
return getHostname();
}
// Implement IWindowsSession
public IRunspacePool getRunspacePool() {
return runspaces;
}
public IDirectory getDirectory() {
return directory;
}
public View getNativeView() {
return is64bit ? View._64BIT : View._32BIT;
}
public boolean supports(View view) {
switch(view) {
case _32BIT:
return true;
case _64BIT:
default:
return is64bit;
}
}
public IRegistry getRegistry(View view) {
switch(view) {
case _32BIT:
if (reg32 == null) {
if (getNativeView() == View._32BIT) {
reg32 = reg;
} else {
try {
reg32 = new Registry(this, View._32BIT);
} catch (Exception e) {
logger.warn(Message.getMessage(Message.ERROR_EXCEPTION), e);
}
}
}
return reg32;
default:
return reg;
}
}
public IWindowsFilesystem getFilesystem(View view) {
switch(view) {
case _32BIT:
if (fs32 == null) {
if (getNativeView() == View._32BIT) {
fs32 = (IWindowsFilesystem)fs;
} else {
try {
fs32 = new WindowsFilesystem(this, View._32BIT, accessorView);
} catch (Exception e) {
logger.warn(Message.getMessage(Message.ERROR_EXCEPTION), e);
}
}
}
return fs32;
default:
return (IWindowsFilesystem)fs;
}
}
public IWmiProvider getWmiProvider() {
return wmi;
}
}
|
package jsaf.provider.windows.system;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.slf4j.cal10n.LocLogger;
import jsaf.Message;
import jsaf.intf.io.IFilesystem;
import jsaf.intf.system.IEnvironment;
import jsaf.intf.windows.identity.IDirectory;
import jsaf.intf.windows.io.IWindowsFilesystem;
import jsaf.intf.windows.powershell.IRunspacePool;
import jsaf.intf.windows.registry.IKey;
import jsaf.intf.windows.registry.IRegistry;
import jsaf.intf.windows.registry.IStringValue;
import jsaf.intf.windows.registry.IValue;
import jsaf.intf.windows.system.IWindowsSession;
import jsaf.intf.windows.wmi.IWmiProvider;
import jsaf.io.fs.AbstractFilesystem;
import jsaf.provider.AbstractSession;
import jsaf.provider.windows.identity.Directory;
import jsaf.provider.windows.io.WindowsFilesystem;
import jsaf.provider.windows.powershell.RunspacePool;
import jsaf.provider.windows.registry.Registry;
import jsaf.provider.windows.wmi.WmiProvider;
/**
* Windows implementation of ISession for local machines, using JACOB for WMI access via COM.
*
* @author David A. Solin
* @version %I% %G%
*/
public class WindowsSession extends AbstractSession implements IWindowsSession {
private WmiProvider wmi;
private boolean is64bit = false;
private Registry reg32, reg;
private IWindowsFilesystem fs32;
private Directory directory = null;
private RunspacePool runspaces = null;
private List<String> baseCommand = Arrays.asList("cmd", "/c");
private View accessorView = null;
// Load the JACOB DLL
static {
if ("32".equals(System.getProperty("sun.arch.data.model"))) {
System.loadLibrary("jacob-1.15-M4-x86");
} else {
System.loadLibrary("jacob-1.15-M4-x64");
}
}
public WindowsSession(File wsdir) {
super();
this.wsdir = wsdir;
}
@Override
protected List<String> getBaseCommand() {
return baseCommand;
}
// Implement ILoggable
@Override
public void setLogger(LocLogger logger) {
super.setLogger(logger);
if (fs32 != null && !fs32.equals(fs)) {
fs32.setLogger(logger);
}
if (wmi != null) {
wmi.setLogger(logger);
}
if (directory != null) {
directory.setLogger(logger);
}
}
// Implement ISession
@Override
public void dispose() {
super.dispose();
if (fs32 instanceof AbstractFilesystem) {
((AbstractFilesystem)fs32).dispose();
}
}
public boolean connect() {
if (env == null) {
try {
env = new Environment(this);
} catch (Exception e) {
logger.warn(Message.getMessage(Message.ERROR_EXCEPTION), e);
return false;
}
}
is64bit = ((Environment)env).is64bit();
if (is64bit) {
if ("64".equals(System.getProperty("sun.arch.data.model"))) {
accessorView = View._64BIT;
} else {
accessorView = View._32BIT;
StringBuffer cmd = new StringBuffer(System.getenv("SystemRoot")).append("\\SysNative\\cmd.exe");
baseCommand = Arrays.asList(cmd.toString(), "/c");
}
logger.trace(Message.STATUS_WINDOWS_BITNESS, "64");
} else {
accessorView = View._32BIT;
logger.trace(Message.STATUS_WINDOWS_BITNESS, "32");
}
if (runspaces == null) {
runspaces = new RunspacePool(this, 100);
}
if (reg == null) {
try {
reg = new Registry(this);
} catch (Exception e) {
logger.warn(Message.getMessage(Message.ERROR_EXCEPTION), e);
return false;
}
if (!is64bit) reg32 = reg;
}
if (wmi == null) {
wmi = new WmiProvider(this);
}
if (fs == null) {
try {
if (is64bit) {
fs = new WindowsFilesystem(this, View._64BIT, accessorView);
} else {
fs32 = new WindowsFilesystem(this, View._32BIT, accessorView);
fs = fs32;
}
} catch (Exception e) {
logger.warn(Message.getMessage(Message.ERROR_EXCEPTION), e);
return false;
}
}
if (wmi.register()) {
connected = true;
if (directory == null) {
directory = new Directory(this);
}
directory.setWmiProvider(wmi);
return true;
} else {
return false;
}
}
public void disconnect() {
runspaces.shutdown();
wmi.deregister();
connected = false;
}
public Type getType() {
return Type.WINDOWS;
}
@Override
public String getMachineName() {
if (isConnected()) {
try {
IKey key = reg.getKey(IRegistry.Hive.HKLM, IRegistry.COMPUTERNAME_KEY);
IValue val = key.getValue(IRegistry.COMPUTERNAME_VAL);
if (val.getType() == IValue.Type.REG_SZ) {
return ((IStringValue)val).getData();
} else {
logger.warn(Message.ERROR_MACHINENAME);
}
} catch (Exception e) {
logger.warn(Message.ERROR_MACHINENAME);
logger.warn(Message.getMessage(Message.ERROR_EXCEPTION), e);
}
}
return getHostname();
}
// Implement IWindowsSession
public IRunspacePool getRunspacePool() {
return runspaces;
}
public IDirectory getDirectory() {
return directory;
}
public View getNativeView() {
return is64bit ? View._64BIT : View._32BIT;
}
public boolean supports(View view) {
switch(view) {
case _32BIT:
return true;
case _64BIT:
default:
return is64bit;
}
}
public IRegistry getRegistry(View view) {
switch(view) {
case _32BIT:
if (reg32 == null) {
if (getNativeView() == View._32BIT) {
reg32 = reg;
} else {
try {
reg32 = new Registry(this, View._32BIT);
} catch (Exception e) {
logger.warn(Message.getMessage(Message.ERROR_EXCEPTION), e);
}
}
}
return reg32;
default:
return reg;
}
}
public IWindowsFilesystem getFilesystem(View view) {
switch(view) {
case _32BIT:
if (fs32 == null) {
if (getNativeView() == View._32BIT) {
fs32 = (IWindowsFilesystem)fs;
} else {
try {
fs32 = new WindowsFilesystem(this, View._32BIT, accessorView);
} catch (Exception e) {
logger.warn(Message.getMessage(Message.ERROR_EXCEPTION), e);
}
}
}
return fs32;
default:
return (IWindowsFilesystem)fs;
}
}
public IWmiProvider getWmiProvider() {
return wmi;
}
}
|
package kg.apc.jmeter.vizualizers;
import kg.apc.jmeter.graphs.CompositeNotifierInterface;
import kg.apc.jmeter.graphs.AbstractOverTimeVisualizer;
import kg.apc.charting.DateTimeRenderer;
import java.util.HashSet;
import java.util.Iterator;
import javax.swing.ImageIcon;
import kg.apc.jmeter.JMeterPluginsUtils;
import kg.apc.charting.AbstractGraphRow;
import org.apache.jmeter.reporters.ResultCollector;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.property.CollectionProperty;
import org.apache.jmeter.testelement.property.JMeterProperty;
import org.apache.jmeter.testelement.property.NullProperty;
import org.apache.jmeter.testelement.property.PropertyIterator;
public class CompositeGraphGui extends AbstractOverTimeVisualizer {
private JCompositeRowsSelectorPanel compositeRowsSelectorPanel;
public CompositeModel compositeModel;
private long lastUpdate = 0;
private static String CONFIG_PROPERTY = "COMPOSITE_CFG";
public CompositeGraphGui() {
graphPanel.getGraphObject().setDisplayPrecision(false);
compositeModel = new CompositeModel();
ImageIcon rowsIcon = new ImageIcon(CompositeGraphGui.class.getResource("/kg/apc/jmeter/img/checks.png"));
graphPanel.remove(1);// FIXME: it is sooo bad way to make things...
compositeRowsSelectorPanel = new JCompositeRowsSelectorPanel(compositeModel, this);
compositeModel.setNotifier((CompositeNotifierInterface) compositeRowsSelectorPanel);
graphPanel.insertTab("Graphs", rowsIcon, compositeRowsSelectorPanel, "Select graphs/rows to display", 1);
graphPanel.getGraphObject().setxAxisLabelRenderer(new DateTimeRenderer("HH:mm:ss"));
graphPanel.getGraphObject().setReSetColors(true);
graphPanel.getGraphObject().setxAxisLabel("Elapsed time");
graphPanel.getGraphObject().setYAxisLabel("Scaled values");
graphPanel.getGraphObject().setExpendRows(true);
CompositeResultCollector compositeResultCollector = new CompositeResultCollector();
compositeResultCollector.setCompositeModel(compositeModel);
setModel(compositeResultCollector);
getFilePanel().setVisible(false);
}
@Override
protected JSettingsPanel createSettingsPanel() {
return new JSettingsPanel(this,
JSettingsPanel.GRADIENT_OPTION
| JSettingsPanel.FINAL_ZEROING_OPTION
| JSettingsPanel.LIMIT_POINT_OPTION
| JSettingsPanel.MAXY_OPTION
| JSettingsPanel.RELATIVE_TIME_OPTION);
}
@Override
public String getLabelResource() {
return this.getClass().getSimpleName();
}
@Override
public String getStaticLabel() {
return JMeterPluginsUtils.prefixLabel("Composite Graph");
}
@Override
public TestElement createTestElement() {
ResultCollector modelNew = getModel();
if (modelNew == null) {
modelNew = new CompositeResultCollector();
((CompositeResultCollector) modelNew).setCompositeModel(compositeModel);
setModel(modelNew);
}
modifyTestElement(modelNew);
modelNew.setComment(JMeterPluginsUtils.getWikiLinkText("CompositeGraph"));
return modelNew;
}
@Override
public void configure(TestElement te) {
//log.info("Configure");
super.configure(te);
((CompositeResultCollector) te).setCompositeModel(compositeModel);
JMeterProperty data = te.getProperty(CONFIG_PROPERTY);
if (!(data instanceof NullProperty)) {
setConfig((CollectionProperty) data);
}
}
@Override
public void modifyTestElement(TestElement c) {
super.modifyTestElement(c);
c.setProperty(getConfig());
}
private CollectionProperty getConfig() {
CollectionProperty ret = new CollectionProperty();
CollectionProperty testplans = new CollectionProperty();
CollectionProperty rows = new CollectionProperty();
ret.setName(CONFIG_PROPERTY);
Iterator<String[]> iter = compositeRowsSelectorPanel.getItems();
while (iter.hasNext()) {
String[] item = iter.next();
testplans.addItem(item[0]);
rows.addItem(item[1]);
}
ret.addItem(testplans);
ret.addItem(rows);
return ret;
}
private void setConfig(CollectionProperty properties) {
PropertyIterator iter = properties.iterator();
CollectionProperty testplans = (CollectionProperty) iter.next();
CollectionProperty rows = (CollectionProperty) iter.next();
if (rows.size() > 0) {
PropertyIterator iterTestplans = testplans.iterator();
PropertyIterator iterRows = rows.iterator();
while (iterTestplans.hasNext() && iterRows.hasNext()) {
String testplan = iterTestplans.next().getStringValue();
String row = iterRows.next().getStringValue();
compositeRowsSelectorPanel.addItemsToComposite(testplan, row);
}
}
}
@Override
public void updateGui() {
Iterator<String[]> iter = compositeRowsSelectorPanel.getItems();
HashSet<String> validRows = new HashSet<String>();
while (iter.hasNext()) {
String[] item = iter.next();
AbstractGraphRow row = compositeModel.getRow(item[0], item[1]);
if (row != null) {
String rowName = item[0] + " > " + item[1];
validRows.add(rowName);
if (!model.containsKey(rowName)) {
model.put(rowName, row);
//SH: buggy code maybe because of issue 67 ?
// handle relative start times
/*if (relativeStartTime == 0 || relativeStartTime > row.getFirstTime()) {
relativeStartTime = row.getFirstTime();
handleRelativeStartTime();
}*/
}
}
}
//remove invalid rows
Iterator<String> iterModelRows = model.keySet().iterator();
while (iterModelRows.hasNext()) {
String rowName = iterModelRows.next();
if (!validRows.contains(rowName)) {
iterModelRows.remove();
}
}
super.updateGui();
}
@Override
public void add(SampleResult sr) {
super.add(sr);
long time = System.currentTimeMillis();
if (time > lastUpdate + 1000) {
lastUpdate = time;
updateGui();
}
}
@Override
public String getWikiPage() {
return "CompositeGraph";
}
@Override
public void clearData() {
super.clearData();
updateGui();
}
}
|
package com.blackmoonit.database;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
import org.apache.http.impl.cookie.DateParseException;
import android.text.format.DateFormat;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
public class DbDateTime {
/**
* Current UTC date and time to the second.
* @return Returns the current date and time to the second.
*/
static public Calendar getNow() {
Calendar theCurrentDay = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
theCurrentDay.set(Calendar.MILLISECOND,0);
return theCurrentDay;
}
/**
* Current UTC date and time to the millisecond.
* @return Returns the current date and time to the millisecond.
*/
static public Calendar getNowMs() {
Calendar theCurrentDay = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
return theCurrentDay;
}
/**
* Current UTC date without time.
* @return Returns the current date, but no time.
*/
static public Calendar getToday() {
Calendar theCurrentDay = getNow();
theCurrentDay.set(Calendar.HOUR,0);
theCurrentDay.set(Calendar.MINUTE,0);
theCurrentDay.set(Calendar.SECOND,0);
return theCurrentDay;
}
/**
* Convert calendar object to SQL db string format.
* @param aCal - the datetime to convert.
* @return Returns the string as used by SQL.
*/
static public String toDbStr(Calendar aCal) {
String theResult = (String)DateFormat.format("yyyy-MM-dd'T'kk:mm:ss", aCal);
int theMs = aCal.get(Calendar.MILLISECOND);
if (theMs>0) {
theResult = theResult + "."+String.format(Locale.US,"%03d",theMs)+"000";
}
return theResult+"Z";
}
/**
* Convert the SQL date time string into a Calendar object.
* @param aStr - SQL date time string.
* @return Returns the Calendar representation of the db SQL string.
* @throws DateParseException
*/
static public Calendar fromDbStr(String aStr) {
Calendar theCurrentDay = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
SimpleDateFormat iso8601Format;
if (aStr!=null && aStr.contains("000Z")) {
iso8601Format = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss.S000'Z'",Locale.US);
} else {
iso8601Format = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss'Z'",Locale.US);
}
try {
theCurrentDay.setTime(iso8601Format.parse(aStr));
} catch (ParseException e) {
//means we do not modify the calendar at all, leaves it as "now"
}
return theCurrentDay;
}
/**
* Returns the current time in the proper SQL Date format
* @return Returns the String representation of the current datetime
* @param bNowMs - boolean for getNow with Milliseconds or seconds
*/
static public String getNowAsDbStr(boolean bNowMs) {
if (bNowMs) {
return toDbStr(getNowMs());
} else {
return toDbStr(getNow());
}
}
/**
* Adds aNumDays to the timestamp. If timestamp is null, {@link #getToday()} is used.
* @param aTimestamp - timestamp, getToday() if null is passed in.
* @param aNumDays - number of days to add.
* @return Returns calendar object with aNumDays added to it.
*/
static public Calendar addDays(Calendar aTimestamp, int aNumDays) {
if (aTimestamp==null)
aTimestamp = getToday();
aTimestamp.add(Calendar.DAY_OF_MONTH,aNumDays);
return aTimestamp;
}
/**
* Convenience function to get the date out of a picker as a Calendar.
* @param aDatePicker - Widget to read.
* @return Returns the Calendar date the picker represents.
*/
static public Calendar getDateFromDatePicker(DatePicker aDatePicker) {
Calendar theDate = getToday();
if (aDatePicker!=null)
theDate.set(aDatePicker.getYear(),aDatePicker.getMonth(),aDatePicker.getDayOfMonth());
return theDate;
}
/**
* Convenience function to set the picker date.
* @param aCal - Date to set, if null, use getNow().
* @param aDatePicker - Widget to set.
* @param aListener - part of the Widget's params
* @return Returns the Calendar object used.
*/
static public Calendar setDateToDatePicker(Calendar aCal, DatePicker aDatePicker, OnDateChangedListener aListener) {
if (aCal==null)
aCal = getNow();
if (aDatePicker!=null)
aDatePicker.init(aCal.get(Calendar.YEAR),aCal.get(Calendar.MONTH),aCal.get(Calendar.DAY_OF_MONTH),aListener);
return aCal;
}
}
|
package com.calculator.base.downloader;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
public class Main {
private static final Properties properties = new Properties();
private final List<Instrument> instruments;
private Main() throws IOException {
instruments = new LinkedList<>();
readInstruments();
processInstruments();
PrintWriter mainWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream("data/db_instruments.csv"), StandardCharsets.UTF_8), true);
Instrument.writeHead(mainWriter);
instruments.forEach(instr -> instr.writeMeta(mainWriter));
mainWriter.close();
}
private void readInstruments() {
System.out.print("Read ETFs... ");
readInstrument("input.instruments.etf");
}
private void readInstrument(String property) {
new ReaderCSV("\"", ",", null)
.read(properties.getProperty(property))
.body()
.lines()
.forEach(line -> {
if (!instruments.stream().anyMatch(i -> i.getTicker().equals(line.get(0)))) {
instruments.add(
new Instrument(
line.get(0),
line.get(1),
Instrument.Type.ETF,
Instrument.BEGINNING,
Calendar.getInstance().getTime()
)
);
}
});
System.out.println("Got " + instruments.size() + ".");
}
private void processInstruments() {
System.out.print("Start download process...");
instruments.forEach(this::processInstrument);
System.out.print("Download complete...");
}
private void processInstrument(Instrument instr) {
instr.download(new YahooDownloader(), allOk -> {
if (allOk) {
try {
PrintWriter iWriter = new PrintWriter(
new OutputStreamWriter(
new FileOutputStream(String.format("data/%s_etf.csv", instr.getTicker().toLowerCase())),
StandardCharsets.UTF_8),
true);
InstrumentHistory.writeMeta(iWriter);
instr.write(iWriter);
iWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
}
public static void main(String[] args) throws IOException {
try {
properties.load(new FileInputStream("downloader.properties"));
} catch (IOException e) {
System.err.println("Can't read properties. Use default!");
e.printStackTrace();
properties.setProperty("input.instruments.etf", "sources/nasdaq_etf_full.csv");
}
new Main();
}
}
|
package com.creeaaakk.tools.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Queue;
public class CycleQueue<T> implements Queue<T>
{
private final List<T> queue = new ArrayList<T>();
private int index = 0;
public CycleQueue()
{
}
public CycleQueue(Collection<? extends T> c)
{
addAll(c);
}
@Override
public int size()
{
return queue.size();
}
@Override
public boolean isEmpty()
{
return queue.isEmpty();
}
@Override
public boolean contains(Object o)
{
return queue.contains(o);
}
@Override
public Iterator<T> iterator()
{
return queue.iterator();
}
@Override
public Object[] toArray()
{
return queue.toArray();
}
@Override
public <E> E[] toArray(E[] a)
{
return queue.toArray(a);
}
@Override
public boolean remove(Object o)
{
return queue.remove(o);
}
@Override
public boolean containsAll(Collection<?> c)
{
return queue.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends T> c)
{
return queue.addAll(c);
}
@Override
public boolean removeAll(Collection<?> c)
{
return queue.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c)
{
return queue.retainAll(c);
}
@Override
public void clear()
{
queue.clear();
}
@Override
public boolean add(T e)
{
return queue.add(e);
}
@Override
public boolean offer(T e)
{
return queue.add(e);
}
@Override
public T remove()
{
if (isEmpty())
{
return null;
}
T ret = queue.get(getIndex());
incIndex();
return ret;
}
@Override
public T poll()
{
return remove();
}
@Override
public T element()
{
if (isEmpty())
{
throw new NoSuchElementException();
}
return queue.get(getIndex());
}
@Override
public T peek()
{
if (isEmpty())
{
return null;
}
return queue.get(getIndex());
}
private int getIndex()
{
return index = index % queue.size();
}
private void incIndex()
{
index++;
}
}
|
package com.ecyrd.jspwiki.tags;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
import com.ecyrd.jspwiki.WikiContext;
import org.apache.log4j.Logger;
/**
* Converts the body text into HTML content.
*
* @author Janne Jalkanen
* @since 2.0
*/
public class TranslateTag
extends BodyTagSupport
{
static Logger log = Logger.getLogger( TranslateTag.class );
public final int doAfterBody()
throws JspException
{
try
{
WikiContext context = (WikiContext) pageContext.getAttribute( WikiTagBase.ATTR_CONTEXT,
PageContext.REQUEST_SCOPE );
BodyContent bc = getBodyContent();
String wikiText = bc.getString();
bc.clearBody();
String result = context.getEngine().textToHTML( context, wikiText );
getPreviousOut().write( result );
}
catch( Exception e )
{
log.error( "Tag failed", e );
throw new JspException( "Tag failed, check logs: "+e.getMessage() );
}
return SKIP_BODY;
}
}
|
package com.example.visionapp;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.opencv.android.Utils;
import org.opencv.core.Core;
//import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfFloat;
import org.opencv.core.MatOfInt;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import com.googlecode.tesseract.android.TessBaseAPI;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class ImageActivity extends Activity {
Mat image, yellow, hist;
public static final String DATA_PATH = Environment.getExternalStorageDirectory().toString() + "/VisionBusApp/";
public static final String lang = "eng";
private static final String TAG = "ImageActivity.java";
private static String stopNumber;
@Override
protected void onCreate(Bundle savedInstanceState) {
String[] paths = new String[] {DATA_PATH, DATA_PATH + "tessdata/"};
for (String path: paths) {
File dir = new File(path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.v(TAG, "ERROR: Creation of directory " + path + " on sdcard failed");
return;
}
else {
Log.v(TAG, "Created directory " + path + " on sdcard");
}
}
}
if (!(new File(DATA_PATH + "tessdata/" + lang + ".traineddata")).exists()) {
try {
AssetManager am = getResources().getAssets();
InputStream is = am.open("tessdata/" + lang + ".traineddata");
OutputStream os = new FileOutputStream(DATA_PATH + "tessData/" + lang + ".traineddata");
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) > 0) {
os.write(buf, 0, len);
}
is.close();
os.close();
Log.v(TAG, "Copied " + lang + ".traineddata");
} catch (IOException e) {
Log.v(TAG, "Was unable to copy eng.traineddata " + e.toString());
}
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
protected void onResume() {
super.onResume();
try {
processImage();
} catch (Exception e) {
e.printStackTrace();
}
}
public void processImage() throws Exception {
Bitmap bitmap = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
bitmap = (Bitmap) getIntent().getParcelableExtra("image");
}
AssetManager asset = getResources().getAssets();
InputStream in = asset.open("sign.jpg");
bitmap = BitmapFactory.decodeStream(in);
Bitmap signBitmap = bitmap.copy(bitmap.getConfig(), true);
ImageView mImageView = (ImageView) findViewById(R.id.imageView1);
mImageView.setImageBitmap(signBitmap);
image = new Mat(bitmap.getWidth(), bitmap.getHeight(), CvType.CV_8UC1);
Utils.bitmapToMat(bitmap, image);
imageProcessing();
Utils.matToBitmap(image, bitmap);
stopNumber = digitRecognition(bitmap).split("\n")[1].replace(" ", "");
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(stopNumber);
}
private void imageProcessing() throws IOException {
Mat backProj = backProject();
Mat im1 = new Mat();
Mat im2 = new Mat();
backProj.copyTo(im1);
backProj.copyTo(im2);
backProj.convertTo(im1, CvType.CV_8U);
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Imgproc.findContours(im1, contours, im2, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE);
double maxArea = 0;
int maxIdX = 0;
for (int i = 0; i < contours.size(); i++) {
double area = Imgproc.contourArea(contours.get(i));
maxIdX = area > maxArea ? i : maxIdX;
maxArea = area > maxArea ? area : maxArea;
}
im1.setTo(new Scalar(0));
Imgproc.drawContours(im1, contours, maxIdX, new Scalar(255), -1);
backProj.copyTo(image);
Core.absdiff(backProj, im1, image);
Imgproc.erode(image, image, Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(5, 5)));
Imgproc.dilate(image, image, Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(15, 15)));
}
private Mat backProject() throws IOException {
Mat backProj = new Mat();
AssetManager am = getResources().getAssets();
InputStream is = am.open("yellow.png");
Bitmap yellowBitmap = BitmapFactory.decodeStream(is);
yellow = new Mat(yellowBitmap.getWidth(), yellowBitmap.getHeight(), CvType.CV_8UC1);
Utils.bitmapToMat(yellowBitmap, yellow);
ArrayList<Mat> imageList = new ArrayList<Mat>();
Imgproc.cvtColor(image, backProj, Imgproc.COLOR_BGR2HSV);
imageList.add(backProj);
//MatOfInt ch = new MatOfInt(0);
//Core.mixChannels(imageList, imageList, ch);
ArrayList<Mat> yellowList = new ArrayList<Mat>();
Imgproc.cvtColor(yellow, yellow, Imgproc.COLOR_BGR2HSV);
yellowList.add(yellow);
//Core.mixChannels(yellowList, yellowList, ch);
MatOfInt channels = new MatOfInt(0);
Mat hist= new Mat();
MatOfInt histSize = new MatOfInt(25);
MatOfFloat ranges = new MatOfFloat(0, 180);
Imgproc.calcHist(yellowList, channels, new Mat(), hist, histSize, ranges);
Imgproc.calcBackProject(imageList, channels, hist, backProj, ranges, 1);
return backProj;
}
private String digitRecognition(Bitmap bitmap) {
TessBaseAPI tess = new TessBaseAPI();
//tess.init("/storage/sdcard0/FYP/", "eng");
tess.init(DATA_PATH, lang);
tess.setVariable("tessedit_char_whitelist", "0123456789");
tess.setImage(bitmap);
String stopNumber = tess.getUTF8Text();
tess.end();
return stopNumber;
}
public void goBack(View view) {
finish();
}
public void getRtpi(View view) throws Exception {
Intent intent = new Intent(getBaseContext(), ResultsActivity.class);
intent.putExtra("rtpi stop", stopNumber);
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.image, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_image,
container, false);
return rootView;
}
}
}
|
package com.flashmath.util;
import java.util.ArrayList;
import org.json.JSONArray;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.activeandroid.query.Select;
import com.flashmath.models.OfflineScore;
import com.flashmath.network.FlashMathClient;
import com.loopj.android.http.JsonHttpResponseHandler;
public class ConnectivityUtil extends BroadcastReceiver {
public static final String INTERNET_CONNECTION_IS_NOT_AVAILABLE = "Internet connection is not available";
private static OfflineScore unsentScore;
@Override
public void onReceive(Context context, Intent intent) {
ArrayList<OfflineScore> scoresToSent = new Select().from(OfflineScore.class).execute();
if (scoresToSent != null && scoresToSent.size() > 0) {
boolean unsentScoreIsSaved = false;
if (unsentScore != null) {
for (int i = 0; i < scoresToSent.size(); i++) {
OfflineScore os = scoresToSent.get(i);
if (os != null && os.getTimeStampInSeconds() == unsentScore.getTimeStampInSeconds()) {
unsentScoreIsSaved = true;
break;
}
}
}
if (!unsentScoreIsSaved && unsentScore != null) {
scoresToSent.add(unsentScore);
}
//clear it since it's either in the db or has been added to the array
unsentScore = null;
} else if (unsentScore != null && scoresToSent == null){
scoresToSent = new ArrayList<OfflineScore>();
scoresToSent.add(unsentScore);
unsentScore = null;
}
if (scoresToSent != null) {
FlashMathClient client = FlashMathClient.getClient(context);
final Context localContext = context;
if(ConnectivityUtil.isInternetConnectionAvailable(context)) {
for (int i = 0; i < scoresToSent.size(); i++) {
final OfflineScore osToSent = scoresToSent.get(i);
if (osToSent != null) {
client.putScore(osToSent.getSubject(), String.valueOf(osToSent.getScore()),
new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONArray jsonScores) {
//score has been sent successfully, so clear the score
osToSent.delete();
Toast.makeText(localContext, "Sent offline score successfully!", Toast.LENGTH_LONG).show();
}
});
}
}
}
}
}
@SuppressWarnings("unused")
private void debugIntent(Intent intent, String tag) {
Log.v(tag, "action: " + intent.getAction());
Log.v(tag, "component: " + intent.getComponent());
Bundle extras = intent.getExtras();
if (extras != null) {
for (String key: extras.keySet()) {
Log.v(tag, "key [" + key + "]: " +
extras.get(key));
}
}
else {
Log.v(tag, "no extras");
}
}
public static boolean isInternetConnectionAvailable(Context context) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return isConnected;
}
public static OfflineScore getUnsentScore() {
return unsentScore;
}
public static void setUnsentScore(OfflineScore unsentScore) {
ConnectivityUtil.unsentScore = unsentScore;
}
}
|
package com.jme.scene.model.ms3d;
import com.jme.scene.model.Loader;
import com.jme.scene.Node;
import com.jme.bounding.BoundingBox;
import com.jme.system.JmeException;
import com.jme.util.LittleEndien;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Class to load .ms3d files for jME. Base directory for textures
* is by default the same directory as the first loaded file, unless changed
* otherwise set by <code>Loader.setBase</code>
*
* @author Jack Lindamood
*/
public class MilkLoader extends Loader{
private MilkFile lastLoad;
/**
* Private helper method to create a MS3D file from a MilkFile
*
* @param myFile MilkFile to create a scene from
* @return Scene created from the file
* @see Node
*/
private Node createScene(MilkFile myFile){
Node myScene=new Node("Loaded MilkShape3D scene");
for (int i=0;i<myFile.nNumGroups;i++)
myScene.attachChild(myFile.myGroups[i]);
if ((loadFlags&LOAD_CONTROLLERS)!=0){
MilkAnimation ma=new MilkAnimation(myFile,0,myFile.iTotalFrames-1,myFile.speed);
if ((loadFlags&PRECOMPUTE_BOUNDS)!=0){
for (int i=0;i<myFile.nNumGroups;i++){
if (dirty || myFile.myGroups[i].getModelBound()==null)
myFile.myGroups[i].setModelBound(ma.findBiggestFit(i));
}
}
myScene.addController(ma);
} else{
for (int i=0;i<myFile.nNumGroups;i++){
if (dirty || myFile.myGroups[i].getModelBound()==null){
myFile.myGroups[i].setModelBound(new BoundingBox());
myFile.myGroups[i].updateModelBound();
}
}
}
dirty=false;
return myScene;
}
/**
* Produces a copy of the last file loaded. More efficient than reloaded a
* file because initial processing is completed and no file needs to be opened
*
* @return a new MS3D file by spawning the last loaded file, or null no preivous file was loaded
* @see Node
*/
public Node fetchCopy(){
if (lastLoad==null)
return null;
else
return createScene(lastLoad.spawnCopy());
}
/**
* Loads a MilkShape file from the path in the URL. All texture/alpha
* maps associated with the URL are by default in the same directory as the
* .ms3d file specified. Texture directory can be changed by a call to
* setBase(URL), allowing the programmer to seperate storage of model
* files and pictures.
*
* @param url Location of .ms3d file
* @see Node
*/
public Node load(URL url){
if (url==null){
throw new JmeException("Can't load null models");
}
if (baseUrl==null){
try {
baseUrl=new URL(url.getProtocol(),url.getHost(),url.getPort(),new File(url.getPath()).getParent()+'\\');
} catch (MalformedURLException e) {
throw new JmeException("Try setting a baseURL: " +e.getMessage());
}
}
try {
LittleEndien file=new LittleEndien(url.openStream());
lastLoad=new MilkFile(baseUrl,file);
file.close();
} catch (IOException e) {
throw new JmeException("Something wierd in load(URL) (DataInputStream) " + e.getMessage());
}
return createScene(lastLoad);
}
}
|
package com.jmex.angelfont;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import com.jme.image.Texture.MagnificationFilter;
import com.jme.image.Texture.MinificationFilter;
import com.jme.util.TextureManager;
/**
*
* A Loader class for {@link BitmapFont} objects.
*
* @author dhdd, Andreas Grabner
* @author Momoko_Fan (enhancements)
*/
public class BitmapFontLoader {
/**
*
* Loads the jme default {@link BitmapFont}
*
* @return the BitmapFont that is the jme default
*/
public static BitmapFont loadDefaultFont() {
URL fontFile = BitmapFontLoader.class.getClassLoader().getResource("com/jmex/angelfont/angelFont.fnt");
URL textureFile = BitmapFontLoader.class.getClassLoader().getResource("com/jmex/angelfont/angelFont.png");
try {
return load(fontFile, textureFile);
} catch (IOException e) {
return null;
} // catch
} // loadDefaultFont
/**
*
* loads the {@link BitmapFont} defined by the two provided URLs
*
* @param fontFile the URL to the .fnt file of the {@link BitmapFont}
* @param textureFile the URL to the texture file of the {@link BitmapFont}
* @return the BitmapFont defined by the two provided {@link URL}s
* @throws IOException if one of the provided {@link URL}s is null
*/
public static BitmapFont load(URL fontFile, URL textureFile) throws IOException {
try {
BitmapCharacterSet charSet = new BitmapCharacterSet();
BitmapFont font = new BitmapFont();
if (fontFile == null) {
throw new IOException("The given URL to the requested font file is null!");
}
if (textureFile == null) {
throw new IOException("The given URL to the requested font texture file is null!");
}
font.setFontTexture(TextureManager.loadTexture(textureFile, true));
font.getFontTexture().setMinificationFilter(MinificationFilter.Trilinear);
font.getFontTexture().setMagnificationFilter(MagnificationFilter.Bilinear);
BufferedReader reader = new BufferedReader(new InputStreamReader(fontFile.openStream()));
String regex = "[\\s=]+";
font.setCharSet(charSet);
while (reader.ready()) {
String line = reader.readLine();
String[] tokens = line.split(regex);
if (tokens[0].equals("info")) {
// Get rendered size
for (int i = 1; i < tokens.length; i++) {
if (tokens[i].equals("size")) {
charSet.setRenderedSize(Math.abs(Integer.parseInt(tokens[i + 1])));
}
}
} else if (tokens[0].equals("common")) {
// Fill out BitmapCharacterSet fields
for (int i = 1; i < tokens.length; i++) {
String token = tokens[i];
if (token.equals("lineHeight")) {
charSet.setLineHeight(Integer.parseInt(tokens[i + 1]));
} else if (token.equals("base")) {
charSet.setBase(Integer.parseInt(tokens[i + 1]));
} else if (token.equals("scaleW")) {
charSet.setWidth(Integer.parseInt(tokens[i + 1]));
} else if (token.equals("scaleH")) {
charSet.setHeight(Integer.parseInt(tokens[i + 1]));
} // else if
}
} else if (tokens[0].equals("char")) {
// New BitmapCharacter
BitmapCharacter ch = null;
for (int i = 1; i < tokens.length; i++) {
String token = tokens[i];
if (token.equals("id")) {
int index = Integer.parseInt(tokens[i + 1]);
ch = new BitmapCharacter();
charSet.addCharacter(index, ch);
} else if (token.equals("x")) {
ch.setX(Integer.parseInt(tokens[i + 1]));
} else if (token.equals("y")) {
ch.setY(Integer.parseInt(tokens[i + 1]));
} else if (token.equals("width")) {
ch.setWidth(Integer.parseInt(tokens[i + 1]));
} else if (token.equals("height")) {
ch.setHeight(Integer.parseInt(tokens[i + 1]));
} else if (token.equals("xoffset")) {
ch.setXOffset(Integer.parseInt(tokens[i + 1]));
} else if (token.equals("yoffset")) {
ch.setYOffset(Integer.parseInt(tokens[i + 1]));
} else if (token.equals("xadvance")) {
ch.setXAdvance(Integer.parseInt(tokens[i + 1]));
}
}
} else if (tokens[0].equals("kerning")) {
// Build kerning list
int index = 0;
Kerning k = new Kerning();
for (int i = 1; i < tokens.length; i++) {
if (tokens[i].equals("first")) {
index = Integer.parseInt(tokens[i + 1]);
} else if (tokens[i].equals("second")) {
k.setSecond(Integer.parseInt(tokens[i + 1]));
} else if (tokens[i].equals("amount")) {
k.setAmount(Integer.parseInt(tokens[i + 1]));
}
}
BitmapCharacter ch = charSet.getCharacter(index);
ch.getKerningList().add(k);
}
}
reader.close();
return font;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
} // load
}
|
package com.nucleus.android;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLSurfaceView.Renderer;
import com.nucleus.opengl.GLException;
import com.nucleus.renderer.NucleusRenderer;
import com.nucleus.renderer.ProcessFrameRunnable;
/**
* Base implementation for Android renderer used with GLSurfaceView
* This will handle the most common situations for rendering and reading input events.
*
* @author Richard Sahlin
*/
public class AndroidRenderer implements Renderer {
public final static String ANDROID_RENDERER_TAG = "AndroidRenderer";
private final static String NULL_RENDERER_ERROR = "NucleusRenderer is null";
NucleusRenderer renderer;
ProcessFrameRunnable frameRunnable;
Thread runnableThread;
public AndroidRenderer(NucleusRenderer renderer) {
if (renderer == null) {
throw new IllegalArgumentException(NULL_RENDERER_ERROR);
}
this.renderer = renderer;
frameRunnable = new ProcessFrameRunnable(renderer);
if (Runtime.getRuntime().availableProcessors() > 1) {
System.out.println("Started extra process for logic processing, number of processors: "
+ Runtime.getRuntime().availableProcessors());
runnableThread = new Thread(frameRunnable);
} else {
System.out.println("Running everything on one thread.");
}
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
renderer.getViewFrustum().setViewPort(0, 0, width, height);
renderer.GLContextCreated(width, height);
}
@Override
public void onDrawFrame(GL10 gl) {
renderer.beginFrame();
try {
if (runnableThread != null) {
if (!runnableThread.isAlive()) {
runnableThread.start();
} else {
synchronized (frameRunnable) {
frameRunnable.notify();
}
}
} else {
renderer.processFrame();
}
renderer.renderScene();
} catch (GLException e) {
throw new RuntimeException(e);
}
renderer.endFrame();
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
renderer.init();
}
}
|
package com.pxhero.coolweather.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Switch;
import com.pxhero.coolweather.db.CoolWeatherDB;
import com.pxhero.coolweather.model.City;
import com.pxhero.coolweather.model.Weather;
import com.pxhero.coolweather.model.WeatherForecastInfo;
import org.json.JSONArray;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
public class Utility {
public synchronized static void handleWeatherResponse(Context context, String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("HeWeather5");
if (jsonArray.length() > 0) {
Weather weather = new Weather();
JSONObject weatherObj = jsonArray.getJSONObject(0);
JSONObject basicObj = weatherObj.getJSONObject("basic");
JSONObject updateObj = basicObj.getJSONObject("update");
String updateTime = updateObj.getString("loc");
weather.setUpdateTime(updateTime);
String cityId = basicObj.getString("id");
weather.setCityId(cityId);
String cityName = basicObj.getString("city");
weather.setCityName(cityName);
JSONObject nowObj = weatherObj.getJSONObject("now");
JSONObject condObj = nowObj.getJSONObject("cond");
String desText = condObj.getString("txt");
weather.setDescription(desText);
//weather code
weather.setCode(condObj.getString("code"));
String temp = nowObj.getString("tmp");
weather.setTmp(temp);
if(weatherObj.has("aqi")) {
JSONObject aqiObj = weatherObj.getJSONObject("aqi");
JSONObject cityAqiObj = aqiObj.getJSONObject("city");
weather.setAirDes(cityAqiObj.getString("qlty"));
}
else {
weather.setAirDes("");
LogUtil.d("û" + weather.getCityName() + "apiָ");
}
saveWeatherInfo(context, weather);
ParseForecastInfo(weatherObj, cityId);
}
} catch (Exception e) {
// TODO: handle exception
LogUtil.d("v5:handleWeatherResponse has a exception");
e.printStackTrace();
}
}
private static void ParseForecastInfo(JSONObject weatherObj, String cityId) throws Exception {
List<WeatherForecastInfo> forecastList = new ArrayList<>();
JSONArray forecastArray = weatherObj.getJSONArray("daily_forecast");
if (forecastArray != null) {
for (int i = 0; i < forecastArray.length(); i++) {
JSONObject oneForecast = forecastArray.getJSONObject(i);
WeatherForecastInfo fInfo = new WeatherForecastInfo();
fInfo.setmCityId(cityId);
fInfo.setmDate(oneForecast.getString("date"));
JSONObject tmpObj = oneForecast.getJSONObject("tmp");
StringBuilder tmpRange = new StringBuilder();
tmpRange.append(tmpObj.getString("min") + "~" + tmpObj.getString("max") + "");
fInfo.setmTemDes(tmpRange.toString());
JSONObject WeaObj = oneForecast.getJSONObject("cond");
String dayWeather = WeaObj.getString("txt_d");
String nightWeather = WeaObj.getString("txt_n");
if (dayWeather.equals(nightWeather)) {
fInfo.setmWeatherDes(dayWeather);
} else {
StringBuilder weatherRange = new StringBuilder();
weatherRange.append(dayWeather);
weatherRange.append("ת");
weatherRange.append(nightWeather);
fInfo.setmWeatherDes(weatherRange.toString());
}
fInfo.setmCodeId(WeaObj.getString("code_d"));
JSONObject windObj = oneForecast.getJSONObject("wind");
StringBuilder windDes = new StringBuilder();
windDes.append(windObj.getString("dir"));
String strSc = new String();
strSc = windObj.getString("sc");
boolean bNumberWind = false;
for (int k = 0; k < 20; k++) {
if (strSc.contains(String.valueOf(k))) {
bNumberWind = true;
break;
}
}
if (bNumberWind) {
windDes.append("(");
windDes.append(strSc);
windDes.append("");
windDes.append(")");
} else {
windDes.append("(");
windDes.append(strSc);
windDes.append(")");
}
fInfo.setmWindDes(windDes.toString());
if (i == 0) {
fInfo.setmDateDes("");
} else if (i == 1) {
fInfo.setmDateDes("");
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(fInfo.getmDate());
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
boolean isFirstSunday = (calendar.getFirstDayOfWeek() == Calendar.SUNDAY);
int weekDay = calendar.get(Calendar.DAY_OF_WEEK);
if(isFirstSunday){
weekDay = weekDay - 1;
if(weekDay == 0){
weekDay = 7;
}
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("");
switch (weekDay) {
case 1:
stringBuilder.append("һ");
break;
case 2:
stringBuilder.append("");
break;
case 3:
stringBuilder.append("");
break;
case 4:
stringBuilder.append("");
break;
case 5:
stringBuilder.append("");
break;
case 6:
stringBuilder.append("");
break;
case 7:
stringBuilder.append("");
break;
default:
break;
}
fInfo.setmDateDes(stringBuilder.toString());
}
forecastList.add(fInfo);
}
}
WeatherForecastInfo.setS_WeatherInfoList(null);
WeatherForecastInfo.setS_WeatherInfoList(forecastList);
}
private static void saveWeatherInfo(Context context, Weather weather) {
if (weather == null)
return;
LogUtil.d("v5:saveWeatherInfo ʼweatherϢSharedPreferencesļ,id=" + weather.getCityId()
+ ",name=" + weather.getCityName());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMd", Locale.CHINA);
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putBoolean("city_selected", true);
editor.putString("city_name", weather.getCityName());
editor.putString("city_id", weather.getCityId());
editor.putString("current_date", simpleDateFormat.format(new Date()));
editor.putString("update_time", weather.getUpdateTime());
editor.putString("description", weather.getDescription());
editor.putString("tmp", weather.getTmp());
editor.putString("air_des", weather.getAirDes());
editor.putString("code", weather.getCode());
editor.commit();
}
public synchronized static boolean handleCityResponse(CoolWeatherDB db, String Response) {
boolean bResult = false;
if (db == null || TextUtils.isEmpty(Response)) {
bResult = false;
return bResult;
}
try {
JSONArray dataArray = new JSONArray(Response);
if (dataArray != null) {
LogUtil.d("handleCityResponse:: the dataArray!=null, parse json success!");
for (int i = 0; i < dataArray.length(); ++i) {
City city = new City();
JSONObject oneData = dataArray.getJSONObject(i);
city.setName(oneData.getString("cityZh"));
city.setCounty(oneData.getString("countryZh"));
city.setId(oneData.getString("id"));
String strLatitude = oneData.getString("lat");
city.setLatitude(Float.valueOf(strLatitude));
String strLongtitude = oneData.getString("lon");
city.setLongtitude(Float.valueOf(strLongtitude));
city.setProvince(oneData.getString("provinceZh"));
db.AddCityToList(city);
}
db.SaveAllCityToDB();
bResult = true;
} else {
LogUtil.d("handleCityResponse:: the dataArray==null,parse json failed!");
}
} catch (Exception e) {
e.printStackTrace();
LogUtil.d("Utility.handlerCityResponse ");
// TODO: handle exception
}
return bResult;
}
}
|
package com.sf.jintn3270.telnet;
import java.io.ByteArrayOutputStream;
import com.sf.jintn3270.TerminalModel;
/**
* Implementation of RFC 885
*
* When this option is enabled, each outgoing frame being sent to the remote
* host is appended with and EOR command. Incoming frames with IAC, EOR are
* then consumed by this option.
*/
public class EndOfRecord extends Option {
public static final byte EOR = (byte)25; // End of Record.
byte[] markEOR;
public EndOfRecord() {
super();
markEOR = new byte[] {TelnetClient.IAC, EOR};
}
public String getName() {
return "EndOfRecord";
}
public byte getCode() {
return EOR;
}
public void initiate(TelnetClient client) {
client.sendWill(getCode());
}
public byte[] outgoingBytes(ByteArrayOutputStream toSend, TelnetClient client) {
byte[] ret = nill;
if (isEnabled() && toSend.size() > 0) {
ret = markEOR;
}
return ret;
}
public int consumeIncomingBytes(byte[] incoming, TelnetClient client) {
if (incoming[0] == TelnetClient.IAC && incoming[1] == EOR) {
return 2;
}
return 0;
}
}
|
package com.tuxofil.android;
import android.view.View;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.ToggleButton;
import android.widget.EditText;
/**
* Represents application's user interface.
*/
public class Gps2UdpActivity extends Activity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Config config = new Config(this);
((ToggleButton) findViewById(R.id.btn_enabled)).
setChecked(config.isEnabled());
((EditText) findViewById(R.id.dst_host)).
setText(config.getHost());
((EditText) findViewById(R.id.dst_port)).
setText(String.valueOf(config.getPort()));
((EditText) findViewById(R.id.send_period)).
setText(String.valueOf(config.getPeriod()));
// automatically start the background service if not started yet
setDaemonEnabled(config.isEnabled());
}
/**
* Called when the activity is lost the focus
* but is still visible to the user.
*/
@Override
public void onPause() {
super.onPause();
applyConfigs();
}
/**
* Called when Enable/Disable button clicked.
*/
public void onOnOffClicked(View view) {
setDaemonEnabled(((ToggleButton) view).isChecked());
}
/**
* Called when Apply button clicked.
*/
public void onApplyClicked(View view) {
applyConfigs();
}
/**
* Validate the configuration values from the form
* and store them to the application's persistent storage.
*/
private void applyConfigs() {
boolean enabled =
((ToggleButton) findViewById(R.id.btn_enabled)).isChecked();
String host = _getText(R.id.dst_host);
int port = Integer.parseInt(_getText(R.id.dst_port));
if (port < 1) port = 1;
if (port >= 0xffff) port = 0xffff - 1;
int period = Integer.parseInt(_getText(R.id.send_period));
if (period < 1) period = 1;
(new Config(this)).set(enabled, host, port, period);
}
/**
* Return the text from the text field.
*/
private String _getText(int id) {
return ((EditText) findViewById(id)).getText().toString();
}
/**
* Enable or disable the daemon according to the argument value.
*/
private void setDaemonEnabled(boolean enabled) {
if (enabled) {
startService(new Intent(Gps2UdpService.ACTION_START));
} else {
stopService(new Intent(Gps2UdpService.ACTION_STOP));
}
}
}
|
package edu.wustl.catissuecore.action;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.catissuecore.actionForm.ConfigureResultViewForm;
import edu.wustl.catissuecore.actionForm.DistributionReportForm;
import edu.wustl.catissuecore.bizlogic.AbstractBizLogic;
import edu.wustl.catissuecore.bizlogic.BizLogicFactory;
import edu.wustl.catissuecore.bizlogic.QueryBizLogic;
import edu.wustl.catissuecore.domain.DistributedItem;
import edu.wustl.catissuecore.domain.Distribution;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.query.DataElement;
import edu.wustl.catissuecore.query.Operator;
import edu.wustl.catissuecore.query.Query;
import edu.wustl.catissuecore.query.QueryFactory;
import edu.wustl.catissuecore.query.SimpleConditionsNode;
import edu.wustl.catissuecore.query.SimpleQuery;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.util.logger.Logger;
/**
* This is the Base action class for the Distribution report actions
* @author Poornima Govindrao
*
*/
public abstract class BaseDistributionReportAction extends BaseAction
{
protected String []getColumnNames(String []selectedColumnsList)
{
String [] columnNames=new String[selectedColumnsList.length];
for(int i=0;i<selectedColumnsList.length;i++)
{
/*Split the string which is in the form TableAlias.columnNames.columnDisplayNames
* to get the column Names
*/
StringTokenizer st= new StringTokenizer(selectedColumnsList[i],".");
while (st.hasMoreTokens())
{
st.nextToken();
st.nextToken();
columnNames[i]=st.nextToken();
Logger.out.debug("Selected column names in configuration "+columnNames[i]);
if(st.hasMoreTokens())
st.nextToken();
}
}
return columnNames;
}
protected DistributionReportForm getDistributionReportForm(Distribution dist) throws Exception
{
//For a given Distribution object set the values for Distribution report.
DistributionReportForm distributionReportForm = new DistributionReportForm();
distributionReportForm.setAllValues(dist);
return distributionReportForm;
}
protected Distribution getDistribution(Long distributionId, SessionDataBean sessionDataBean, int securityParam)throws Exception
{
//For a given Distribution ID retrieve the distribution object
AbstractBizLogic bizLogic = BizLogicFactory.getBizLogic(Constants.DISTRIBUTION_FORM_ID);
List list = bizLogic.retrieve(Distribution.class.getName(),Constants.SYSTEM_IDENTIFIER,distributionId);
Distribution dist = (Distribution) list.get(0);
return dist;
}
protected List getListOfData(Distribution dist, ConfigureResultViewForm configForm) throws Exception
{
//Get the list of data for Distributed items data for the report.
List listOfData = new ArrayList();
Collection distributedItemCollection = dist.getDistributedItemCollection();
//Specimen Ids which are getting distributed.
String []specimenIds = new String[distributedItemCollection.size()];
int i=0;
Iterator itr = distributedItemCollection.iterator();
while(itr.hasNext())
{
DistributedItem item = (DistributedItem)itr.next();
Specimen specimen = item.getSpecimen();
Logger.out.debug("Specimen "+specimen);
Logger.out.debug("Specimen "+specimen.getSystemIdentifier());
specimenIds[i] = specimen.getSystemIdentifier().toString();
i++;
}
String action = configForm.getNextAction();
Logger.out.debug("Configure/Default action "+action);
String selectedColumns[] = getSelectedColumns(action,configForm);
Logger.out.debug("Selected columns length"+selectedColumns.length);
for(int j=0;j<specimenIds.length;j++)
{
Collection simpleConditionNodeCollection = new ArrayList();
Query query = QueryFactory.getInstance().newQuery(Query.SIMPLE_QUERY, "Participant");
Logger.out.debug("Specimen ID" +specimenIds[j]);
SimpleConditionsNode simpleConditionsNode = new SimpleConditionsNode();
simpleConditionsNode.getCondition().setValue(specimenIds[j]);
simpleConditionsNode.getCondition().getDataElement().setTable("Specimen");
simpleConditionsNode.getCondition().getDataElement().setField("Identifier");
simpleConditionsNode.getCondition().getDataElement().setFieldType(Constants.FIELD_TYPE_BIGINT);
simpleConditionsNode.getCondition().getOperator().setOperator("=");
SimpleConditionsNode simpleConditionsNode1 = new SimpleConditionsNode();
simpleConditionsNode1.getCondition().getDataElement().setTable("DistributedItem");
simpleConditionsNode1.getCondition().getDataElement().setField("Distribution_Id");
simpleConditionsNode1.getCondition().getDataElement().setFieldType(Constants.FIELD_TYPE_BIGINT);
simpleConditionsNode1.getCondition().getOperator().setOperator("=");
simpleConditionsNode1.getCondition().setValue(dist.getSystemIdentifier().toString());
simpleConditionsNode1.setOperator(new Operator(Constants.AND_JOIN_CONDITION));
simpleConditionNodeCollection.add(simpleConditionsNode1);
simpleConditionNodeCollection.add(simpleConditionsNode);
((SimpleQuery)query).addConditions(simpleConditionNodeCollection);
Set tableSet = new HashSet();
tableSet.add("Participant");
tableSet.add("Specimen");
tableSet.add("CollectionProtocolRegistration");
tableSet.add("SpecimenCollectionGroup");
tableSet.add("DistributedItem");
tableSet.add("SpecimenCharacteristics");
//Vector vector = setViewElements(selectedColumns);
//Set the resultViewVector
Vector vector = new Vector();
for(i=0;i<selectedColumns.length;i++)
{
StringTokenizer st= new StringTokenizer(selectedColumns[i],".");
DataElement dataElement = new DataElement();
String tableInPath = null;
while (st.hasMoreTokens())
{
dataElement.setTable(st.nextToken());
dataElement.setField(st.nextToken());
st.nextToken();
if(st.hasMoreTokens())
tableInPath=st.nextToken();
}
//Include the tables in tableSet if tableInPath is not null.
if (tableInPath != null)
{
StringTokenizer tableInPathTokenizer = new StringTokenizer(tableInPath, ":");
String aliasName = null;
while (tableInPathTokenizer.hasMoreTokens())
{
Long tableId = Long.valueOf(tableInPathTokenizer.nextToken());
QueryBizLogic bizLogic = (QueryBizLogic)BizLogicFactory
.getBizLogic(Constants.SIMPLE_QUERY_INTERFACE_ID);
aliasName = bizLogic.getAliasNameFromTableId(tableId);
Logger.out.debug("aliasName for from Set**************************"+aliasName);
}
if (aliasName != null)
{
tableSet.add(aliasName);
}
}
vector.add(dataElement);
}
query.setTableSet(tableSet);
query.setResultView(vector);
List list1 = query.execute(null,false, null);
Logger.out.debug("Size of the Data from the database" +list1.size());
Iterator listItr = list1.iterator();
while(listItr.hasNext())
{
Logger.out.debug("Data from the database according to the selected columns"+ listItr.next());
}
listOfData.add(list1);
}
return listOfData;
}
protected String [] getSelectedColumns(String action,ConfigureResultViewForm form)
{
//Set the columns according action(Default/Configured report)
if(("configure").equals(action))
{
String selectedColumns[] = form.getSelectedColumnNames();
Logger.out.debug("Selected columns length"+selectedColumns.length);
return selectedColumns;
}
else
{
form.setSelectedColumnNames(Constants.SELECTED_COLUMNS);
return Constants.SELECTED_COLUMNS;
}
}
protected abstract ActionForward executeAction(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception;
protected void setSelectedMenuRequestAttribute(HttpServletRequest request)
{
request.setAttribute(Constants.MENU_SELECTED,new String("16") );
}
}
|
package com.intellij.ide.actions;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.ListPopup;
import com.intellij.openapi.util.IconLoader;
import com.intellij.util.ui.EmptyIcon;
import javax.swing.*;
/**
* @author max
*/
public abstract class QuickSwitchSchemeAction extends AnAction {
protected static final Icon ourCurrentAction = IconLoader.getIcon("/diff/currentLine.png");
protected static final Icon ourNotCurrentAction = new EmptyIcon(ourCurrentAction.getIconWidth(), ourCurrentAction.getIconHeight());
public void actionPerformed(AnActionEvent e) {
Project project = e.getData(DataKeys.PROJECT);
DefaultActionGroup group = new DefaultActionGroup();
fillActions(project, group);
showPopup(e, group);
}
protected abstract void fillActions(Project project, DefaultActionGroup group);
private static void showPopup(AnActionEvent e, DefaultActionGroup group) {
if (group.getChildrenCount() == 0) return;
final ListPopup popup = JBPopupFactory.getInstance()
.createActionGroupPopup(e.getPresentation().getText(),
group,
e.getDataContext(),
JBPopupFactory.ActionSelectionAid.NUMBERING,
true);
popup.showCenteredInCurrentWindow(e.getData(DataKeys.PROJECT));
}
public void update(AnActionEvent e) {
super.update(e);
e.getPresentation().setEnabled(e.getData(DataKeys.PROJECT) != null && isEnabled());
}
protected abstract boolean isEnabled();
}
|
package sg.ncl.adapter.deterlab;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import sg.ncl.adapter.deterlab.data.jpa.DeterLabUserRepository;
import sg.ncl.adapter.deterlab.dtos.entities.DeterLabUserEntity;
import sg.ncl.adapter.deterlab.exceptions.*;
import javax.inject.Inject;
@Component
public class AdapterDeterLab {
private DeterLabUserRepository deterLabUserRepository;
private ConnectionProperties properties;
private static final Logger logger = LoggerFactory.getLogger(AdapterDeterLab.class);
@Inject
private RestTemplate restTemplate;
@Inject
public AdapterDeterLab(DeterLabUserRepository repository, ConnectionProperties connectionProperties) {
this.deterLabUserRepository = repository;
this.properties = connectionProperties;
}
/**
* Creates a join project request to Deterlab
* Also creates a new user
* @param jsonString
* @return The Deter userid (randomly generated)
*/
public String joinProjectNewUsers(String jsonString) {
logger.info("Joining project as new user to {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getJoinProjectNewUsers(), HttpMethod.POST, request, String.class);
} catch (Exception e) {
throw new AdapterDeterlabConnectException();
}
logger.info("Join project request (new user) submitted to deterlab");
String jsonResult = new JSONObject(response.getBody().toString()).getString("msg");
if ("join project request new users fail".equals(jsonResult) || !"user is created".equals(jsonResult)) {
throw new JoinProjectException();
}
// Will return the following JSON:
// msg: join project request new users fail
// msg: no user created, uid: xxx
// msg: user is created, uid: xxx
// msg: user not found, uid: xxx
return response.getBody().toString();
}
/**
* Creates a apply project request to Deterlab
* Also creates a new user
* @param jsonString
* @return The Deter userid (randomly generated)
*/
public String applyProjectNewUsers(String jsonString) {
logger.info("Applying new project as new user to {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getApplyProjectNewUsers(), HttpMethod.POST, request, String.class);
} catch (Exception e) {
throw new AdapterDeterlabConnectException();
}
logger.info("Apply project request (new user) submitted to deterlab");
String jsonResult = new JSONObject(response.getBody().toString()).getString("msg");
if ("apply project request new users fail".equals(jsonResult) || !"user is created".equals(jsonResult)) {
throw new ApplyNewProjectException();
}
// Will return the following JSON:
// msg: apply project request new users fail
// msg: no user created, uid: xxx
// msg: user is created, uid: xxx
// msg: user not found, uid: xxx
return response.getBody().toString();
}
/**
* Creates a apply project request to Deterlab
* Does not create a new user
* @param jsonString Contains uid, project name, pid, project goals, project web, project organisation, project visibility
*/
public void applyProject(String jsonString) {
logger.info("Applying project as logged on user to {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getApplyProject(), HttpMethod.POST, request, String.class);
} catch (Exception e) {
throw new AdapterDeterlabConnectException();
}
String jsonResult = new JSONObject(response.getBody().toString()).getString("msg");
logger.info("Apply new project request existing users submitted to deterlab: {}", jsonResult);
if (!"apply project request existing users success".equals(jsonResult)) {
throw new ApplyNewProjectException();
}
}
/**
* Creates a join project request to Deterlab
* Does not create a new user
* @param jsonString Contains uid, pid
*/
public void joinProject(String jsonString) {
logger.info("Joining project as logged on user to {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getJoinProject(), HttpMethod.POST, request, String.class);
} catch (Exception e) {
throw new AdapterDeterlabConnectException();
}
logger.info("Join project request submitted to deterlab");
String jsonResult = new JSONObject(response.getBody().toString()).getString("msg");
if (!"join project request existing users success".equals(jsonResult)) {
throw new JoinProjectException();
}
}
/**
* Creates a edit user profile request to Deterlab
* @param jsonString Contains uid, password, confirm password
*/
public void updateCredentials(String jsonString) {
logger.info("Updating credentials to {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getUpdateCredentials(), HttpMethod.POST, request, String.class);
} catch (Exception e) {
throw new AdapterDeterlabConnectException();
}
String jsonResult = new JSONObject(response.getBody().toString()).getString("msg");
if ("password change fail".equals(jsonResult)) {
throw new CredentialsUpdateException();
}
}
public void saveDeterUserIdMapping(String deterUserId, String nclUserId) {
DeterLabUserEntity deterLabUserEntity = new DeterLabUserEntity();
deterLabUserEntity.setNclUserId(nclUserId);
deterLabUserEntity.setDeterUserId(deterUserId);
deterLabUserRepository.save(deterLabUserEntity);
}
public String getDeterUserIdByNclUserId(String nclUserId) {
DeterLabUserEntity deterLabUserEntity = deterLabUserRepository.findByNclUserId(nclUserId);
if (deterLabUserEntity == null) {
throw new UserNotFoundException();
}
return deterLabUserEntity.getDeterUserId();
}
public void createExperiment(String jsonString) {
logger.info("Creating experiment to {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getCreateExperiment(), HttpMethod.POST, request, String.class);
} catch (Exception e) {
throw new AdapterDeterlabConnectException();
}
String jsonResult = new JSONObject(response.getBody().toString()).getString("msg");
if ("experiment create fail ns file error".equals(jsonResult)) {
throw new NSFileParseException();
} else if ("experiment create fail exp name already in use".equals(jsonResult)) {
throw new ExpNameAlreadyExistsException();
} else if (!"experiment create success".equals(jsonResult)) {
throw new AdapterDeterlabConnectException();
}
}
public String startExperiment(String jsonString) {
logger.info("Start experiment - {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity responseEntity = restTemplate.exchange(properties.startExperiment(), HttpMethod.POST, request, String.class);
return responseEntity.getBody().toString();
}
public String stopExperiment(String jsonString) {
logger.info("Stop experiment - {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity responseEntity = restTemplate.exchange(properties.stopExperiment(), HttpMethod.POST, request, String.class);
return responseEntity.getBody().toString();
}
public String deleteExperiment(String jsonString) {
logger.info("Delete experiment - {} at {} : {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity responseEntity = restTemplate.exchange(properties.deleteExperiment(), HttpMethod.POST, request, String.class);
return responseEntity.getBody().toString();
}
public String approveJoinRequest(String jsonString) {
// for team leaders to accept join request
logger.info("Approving join request to {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity responseEntity = restTemplate.exchange(properties.getApproveJoinRequest(), HttpMethod.POST, request, String.class);
return responseEntity.getBody().toString();
}
public String rejectJoinRequest(String jsonString) {
// for team leaders to reject join request
logger.info("Rejecting join request to {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity responseEntity = restTemplate.exchange(properties.getRejectJoinRequest(), HttpMethod.POST, request, String.class);
return responseEntity.getBody().toString();
}
public String approveProject(String jsonString) {
// for ncl admins to approve teams
logger.info("Approving team to {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity responseEntity = restTemplate.exchange(properties.getApproveProject(), HttpMethod.POST, request, String.class);
return responseEntity.getBody().toString();
}
public String rejectProject(String jsonString) {
// for ncl admins to reject teams
logger.info("Rejecting team to {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity responseEntity = restTemplate.exchange(properties.getRejectProject(), HttpMethod.POST, request, String.class);
return responseEntity.getBody().toString();
}
}
|
package sg.ncl.adapter.deterlab;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import sg.ncl.adapter.deterlab.data.jpa.DeterLabProjectRepository;
import sg.ncl.adapter.deterlab.data.jpa.DeterLabUserRepository;
import sg.ncl.adapter.deterlab.dtos.entities.DeterLabProjectEntity;
import sg.ncl.adapter.deterlab.dtos.entities.DeterLabUserEntity;
import sg.ncl.adapter.deterlab.exceptions.*;
import javax.inject.Inject;
@Component
@Slf4j
public class AdapterDeterLab {
private DeterLabProjectRepository deterLabProjectRepository;
private DeterLabUserRepository deterLabUserRepository;
private ConnectionProperties properties;
private RestTemplate restTemplate;
@Inject
public AdapterDeterLab(DeterLabUserRepository repository, DeterLabProjectRepository deterLabProjectRepository, ConnectionProperties connectionProperties, RestTemplate restTemplate) {
this.deterLabUserRepository = repository;
this.deterLabProjectRepository = deterLabProjectRepository;
this.properties = connectionProperties;
this.restTemplate = restTemplate;
}
/**
* Creates a join project request to Deterlab
* Also creates a new user
*
* @param jsonString
* @return The Deter userid (randomly generated)
*/
public String joinProjectNewUsers(String jsonString) {
log.debug("Joining project as new user: {}", jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getJoinProjectNewUsers(), HttpMethod.POST, request, String.class);
} catch (ResourceAccessException rae) {
log.warn("New user join project error: {}", rae);
throw new AdapterConnectionException(rae.getMessage());
} catch (HttpServerErrorException hsee) {
log.warn("New user join project error: Adapter DeterLab internal server error {}", hsee);
throw hsee;
}
// Will get the following JSON:
// msg: join project request new users fail
// msg: no user created, uid: xxx
// msg: user is created, uid: xxx
// msg: user not found, uid: xxx
String responseBody = response.getBody().toString();
try {
//checkAdapterResultNewUsers(responseBody, "Join new project as new user failed: {}.");
String deterMessage = new JSONObject(responseBody).getString("msg");
if("user is created".equalsIgnoreCase(deterMessage)) {
log.info("Join project as new user to DeterLab OK");
return responseBody;
}
log.warn("Join project new user error: {}", deterMessage);
throw new DeterLabOperationFailedException(deterMessage);
} catch (JSONException e) {
log.warn("Error parsing response code new user join project: {}", responseBody);
throw e;
}
}
/**
* Creates a apply project request to Deterlab
* Also creates a new user
*
* @param jsonString
* @return The Deter userid (randomly generated)
*/
public String applyProjectNewUsers(String jsonString) {
log.debug("Applying new project as new user: {}", jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getApplyProjectNewUsers(), HttpMethod.POST, request, String.class);
} catch (RestClientException e) {
log.warn("DeterLab connection error new user apply project: {}", e);
throw new AdapterConnectionException();
}
// Will get the following JSON:
// msg: join project request new users fail
// msg: no user created, uid: xxx
// msg: user is created, uid: xxx
// msg: user not found, uid: xxx
String responseBody = response.getBody().toString();
try {
// checkAdapterResultNewUsers(responseBody, "Apply new project as new user failed: {}. ");
String deterMessage = new JSONObject(responseBody).getString("msg");
if("user is created".equalsIgnoreCase(deterMessage)) {
log.info("Apply project as new user to DeterLab OK");
return responseBody;
}
log.warn("Apply project new user error: {}", deterMessage);
throw new DeterLabOperationFailedException(deterMessage);
} catch (JSONException e) {
log.warn("Error parsing response code new user apply project: {}", responseBody);
throw e;
}
}
/**
* Creates a apply project request to Deterlab
* Does not create a new user
*
* @param jsonString Contains uid, project name, pid, project goals, project web, project organisation, project visibility
*/
public String applyProject(String jsonString) {
log.info("Applying project as existing user: {}", jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getApplyProject(), HttpMethod.POST, request, String.class);
final String responseBody = response.getBody().toString();
log.debug("Apply project as existing user : Deter response -- {}", responseBody);
String deterMessage = new JSONObject(responseBody).getString("msg");
if ("apply project existing users ok".equalsIgnoreCase(deterMessage)) {
log.info("Apply project as existing user : OK");
return responseBody;
}
log.warn("Apply project as existing user : error: {}", deterMessage);
throw new DeterLabOperationFailedException(deterMessage);
} catch (ResourceAccessException rae) {
log.warn("Apply project as existing user : Adapter connection error {}", rae);
throw new AdapterConnectionException();
} catch (HttpServerErrorException hsee) {
log.warn("Apply project as existing user : Adapter internal server error {}", hsee);
throw new AdapterInternalErrorException();
} catch (JSONException e) {
log.warn("Apply project as existing user : error parsing response body");
throw e;
}
}
/**
* Creates a join project request to Deterlab
* Does not create a new user
*
* @param jsonString Contains uid, pid
*/
public String joinProject(String jsonString) {
log.info("Joining project as existing user : {}", jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getJoinProject(), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
log.debug("Join project as existing user : adapter response body -- {}", responseBody);
String deterMessage = new JSONObject(responseBody).getString("msg");
if ("Join project existing user ok".equalsIgnoreCase(deterMessage)) {
log.info("Join project as existing user : OK");
return responseBody;
}
log.warn("Join project as existing user : error on DeterLab -- {}", deterMessage);
throw new DeterLabOperationFailedException(deterMessage);
} catch (ResourceAccessException rae) {
log.warn("Join project as existing user : adapter connection error {}", rae);
throw new AdapterConnectionException();
} catch (HttpServerErrorException hsee) {
log.warn("Join project as existing user : adapter internal server error {}", hsee);
throw new AdapterInternalErrorException();
} catch (JSONException e) {
log.warn("Join project as existing user : error parsing response body");
throw e;
}
}
/**
* Creates a edit user profile request to Deterlab
*
* @param jsonString Contains uid, password, confirm password
*/
public void updateCredentials(String jsonString) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getUpdateCredentials(), HttpMethod.POST, request, String.class);
} catch (RestClientException e) {
log.warn("DeterLab connection error update credentials: {}", e);
throw new AdapterConnectionException();
}
try {
String jsonResult = new JSONObject(response.getBody().toString()).getString("msg");
if (!"password change success".equals(jsonResult)) {
log.warn("Change password failed: {}", response.getBody().toString());
throw new CredentialsUpdateException();
}
log.info("Change password OK");
} catch (JSONException e) {
log.warn("Error parsing response code update credentials: {}", response.getBody().toString());
throw e;
}
}
/**
*
* @param jsonString {"uid" : "uid",
* "password": "password"
* }
*/
public void resetPassword(String jsonString) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getResetPasswordURI(), HttpMethod.POST, request, String.class);
} catch (RestClientException e) {
log.warn("Cannot connect to adapter | server internal error: {}", e);
throw new AdapterConnectionException();
}
String msg = new JSONObject(response.getBody().toString()).getString("msg");
if ("password was reset".equals(msg)) {
log.info("Password was reset");
return;
}
log.warn("Reset password failed: {}", msg);
throw new CredentialsUpdateException();
}
/**
* Creates the cookie file on the boss machine due to the timeout issue
*
* @param nclUserId The ncl user id is required to retrieve the deter user id
* @param password Raw password
*/
public void login(String nclUserId, String password) {
if (!properties.isEnabled()) {
log.info("Bypass login");
return;
}
JSONObject adapterObject = new JSONObject();
adapterObject.put("uid", getDeterUserIdByNclUserId(nclUserId));
adapterObject.put("password", password);
log.info("Now attempting to invoke adapter to login and create cookie file");
log.info("Login on deterlab");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(adapterObject.toString(), headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.login(), HttpMethod.POST, request, String.class);
} catch (RestClientException e) {
log.warn("DeterLab connection error login on deterlab: {}", e);
throw new AdapterConnectionException();
}
try {
String jsonResult = new JSONObject(response.getBody().toString()).getString("msg");
if (!"user is logged in".equals(jsonResult)) {
log.warn("login failed: {}", response.getBody().toString());
throw new DeterLabOperationFailedException(jsonResult);
}
log.info("login success");
} catch (JSONException e) {
log.warn("Error parsing response code login on deterlab: {}", response.getBody().toString());
throw e;
}
}
@Transactional
public void saveDeterUserIdMapping(String deterUserId, String nclUserId) {
DeterLabUserEntity deterLabUserEntity = new DeterLabUserEntity();
deterLabUserEntity.setNclUserId(nclUserId);
deterLabUserEntity.setDeterUserId(deterUserId);
deterLabUserRepository.save(deterLabUserEntity);
}
@Transactional
public String getDeterUserIdByNclUserId(String nclUserId) {
DeterLabUserEntity deterLabUserEntity = deterLabUserRepository.findByNclUserId(nclUserId);
if (deterLabUserEntity == null) {
throw new UserNotFoundException(nclUserId);
}
return deterLabUserEntity.getDeterUserId();
}
// deterProjectId is ncl teamName
@Transactional
public DeterLabProjectEntity saveDeterProjectId(String deterProjectId, String nclTeamId) {
DeterLabProjectEntity deterLabProjectEntity = new DeterLabProjectEntity();
deterLabProjectEntity.setNclTeamId(nclTeamId);
deterLabProjectEntity.setDeterProjectId(deterProjectId);
return deterLabProjectRepository.save(deterLabProjectEntity);
}
@Transactional
public String getDeterProjectIdByNclTeamId(String nclTeamId) {
DeterLabProjectEntity deterLabProjectEntity = deterLabProjectRepository.findByNclTeamId(nclTeamId);
if (deterLabProjectEntity == null) {
throw new TeamNotFoundException(nclTeamId);
}
return deterLabProjectEntity.getDeterProjectId();
}
/**
* Creates a create experiment request to Deterlab
*
* @param jsonString Contains id, userId, teamId, teamName, name (experiment name), description, nsFile, nsFileContent, idleSwap, maxDuration, deterLogin (deter userId), userServerUri
*/
public void createExperiment(String jsonString) {
log.info("Creating experiment to {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getCreateExperiment(), HttpMethod.POST, request, String.class);
} catch (Exception e) {
throw new AdapterConnectionException();
}
String jsonResult = new JSONObject(response.getBody().toString()).getString("msg");
if ("experiment create fail ns file error".equals(jsonResult)) {
throw new NSFileParseException(jsonResult);
} else if ("experiment create fail exp name already in use".equals(jsonResult)) {
throw new ExperimentNameAlreadyExistsException(jsonResult);
} else if (!"experiment create success".equals(jsonResult)) {
throw new AdapterConnectionException();
}
}
/**
* Creates a start experiment request to Deterlab
*
* @param teamName equivalent of pid
* @param experimentName equivalent of eid
* @param nclUserId the ncl user id who starts the experiment
* @return a experiment report if the experiment is started successfully and active, otherwise a "experiment start fail" is return
* @implNote must return the entire response body as realization service needs to store the experiment report to transmit back to UI
*/
public String startExperiment(String teamName, String experimentName, String nclUserId) {
String jsonString = craftJSONStringStartStopExperiment("in", teamName, experimentName, nclUserId);
log.info("Start experiment - {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.startExperiment(), HttpMethod.POST, request, String.class);
} catch (Exception e) {
log.warn("Adapter error start experiment: {}", e);
throw new AdapterConnectionException(e.getMessage());
}
log.info("Start experiment request submitted to deterlab");
log.info("Start experiment response from deterlab: {}", response.getBody());
String jsonResult = new JSONObject(response.getBody().toString()).getString("msg");
if ("experiment start fail".equals(jsonResult)) {
log.warn("Fail to start experiment at deterlab {}", jsonString);
throw new ExperimentStartException();
} else if (!"experiment start success".equals(jsonResult)) {
log.warn("Start experiment connection error {}", jsonString);
throw new AdapterConnectionException();
}
log.info("Start experiment request success at deterlab {}", response.getBody().toString());
return response.getBody().toString();
}
/**
* Creates a stop experiment request to Deterlab
*
* @param teamName equivalent of pid
* @param experimentName equivalent of eid
* @param nclUserId the ncl user id that stops the experiment
* @return the experiment status
* @implNote we don't throw any exception if the result returned from deterlab is not "swapped" since there may be other types of experiment status unknown to us
*/
public String stopExperiment(String teamName, String experimentName, String nclUserId) {
String jsonString = craftJSONStringStartStopExperiment("out", teamName, experimentName, nclUserId);
log.info("Stop experiment - {} at {}: {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.stopExperiment(), HttpMethod.POST, request, String.class);
} catch (Exception e) {
log.warn("Adapter error start experiment: {}", e);
throw new AdapterConnectionException(e.getMessage());
}
log.info("Stop experiment request submitted to deterlab");
String expStatus = new JSONObject(response.getBody().toString()).getString("status");
if (!"swapped".equals(expStatus)) {
log.warn("Fail to stop experiment at deterlab {}", jsonString);
}
log.info("Stop experiment request success at deterlab {}", response.getBody().toString());
return expStatus;
}
/**
* Creates a delete experiment request to Deterlab
*
* @param teamName equivalent of pid
* @param experimentName equivalent of eid
* @param nclUserId the ncl user id who deletes the experiment
* @return the experiment status
*/
public String deleteExperiment(String teamName, String experimentName, String nclUserId) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("teamName", teamName);
jsonObject.put("experimentName", experimentName);
jsonObject.put("deterLogin", getDeterUserIdByNclUserId(nclUserId));
String jsonString = jsonObject.toString();
log.info("Delete experiment - {} at {} : {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.deleteExperiment(), HttpMethod.POST, request, String.class);
} catch (Exception e) {
log.warn("Adapter error delete experiment: {}", e);
throw new AdapterConnectionException(e.getMessage());
}
log.info("Delete experiment request submitted to deterlab");
String expStatus = new JSONObject(response.getBody().toString()).getString("status");
if (!"no experiment found".equals(expStatus)) {
log.warn("Fail to delete experiment at deterlab {}", jsonString);
throw new ExperimentDeleteException();
}
log.info("Delete experiment request success at deterlab {}", response.getBody().toString());
return expStatus;
}
/**
* Retrieves the experiment status from Deterlab
*
* @param teamName equivalent of pid
* @param experimentName equivalent of eid
* @return the status of the experiment, a "error" if the request fails
* @implNote cannot throw exception for this method
*/
public String getExperimentStatus(String teamName, String experimentName) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("pid", teamName);
jsonObject.put("eid", experimentName);
String jsonString = jsonObject.toString();
log.info("Get experiment status - {} at {} : {}", properties.getIp(), properties.getPort(), jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getExpStatus(), HttpMethod.POST, request, String.class);
} catch (Exception e) {
log.warn("Adapter connection error get experiment status: {}", e);
return "{\"status\": \"error\"}";
}
log.info("Get experiment status request submitted to deterlab");
return response.getBody().toString();
}
public String processJoinRequest(String jsonString) {
JSONObject request = new JSONObject(jsonString);
if (request.length() < 5) {
log.warn("NOT enough inputs: {}", jsonString);
throw new IllegalArgumentException();
}
String pid = request.getString("pid");
String approverUid = request.getString("approverUid");
String uid = request.getString("uid");
String gid = request.getString("gid");
String action = request.getString("action");
log.info("Processing join request: team {}, requester {}, approver {}, group {}, action {}",
pid, uid, approverUid, gid, action);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> httpRequest = new HttpEntity<>(jsonString, headers);
String reqUrl = "approve".equals(action) ? properties.getApproveJoinRequest() : properties.getRejectJoinRequest();
ResponseEntity httpResponse;
try {
httpResponse = restTemplate.exchange(reqUrl, HttpMethod.POST, httpRequest, String.class);
} catch (RestClientException e) {
log.warn("DeterLab connection error process join request: {}", e);
throw new AdapterConnectionException();
}
String responseBody = httpResponse.getBody().toString();
try {
// cases where we want to process join request:
// case1: normal join request entry exists on deterlab
// case2: approve a join request not updated on our DB but already approved on deterlab DB
// case3: reject a join request not updated on our DB but does not exists on deterlab DB
String adapterResponse = new JSONObject(responseBody).getString("msg");
log.info("process join request adapter response: {}", adapterResponse);
if ("process join request OK".equals(adapterResponse) || isJoinRequestValid(action, adapterResponse)) {
log.info("{} join request to team {} OK", action, pid);
return responseBody;
} else {
log.warn("{} join request to team {} FAIL", action, pid);
throw new DeterLabOperationFailedException(responseBody);
}
} catch (JSONException e) {
log.warn("Error parsing response code process join request: {}", responseBody);
throw e;
}
}
private boolean isJoinRequestValid(String action, String adapterResponse) {
return ("approve".equals(action) && "user is already an approved member in the project".equals(adapterResponse)) ||
("deny".equals(action) && "no join request found".equals(adapterResponse));
}
public String approveProject(String jsonString) {
// for ncl admins to approve teams
String pid = new JSONObject(jsonString).getString("pid");
log.info("Approving team {}: {}", pid, jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getApproveProject(), HttpMethod.POST, request, String.class);
} catch (RestClientException e) {
log.warn("DeterLab connection error approve project: {}", e);
throw new AdapterConnectionException();
}
try {
String jsonResult = new JSONObject(response.getBody().toString()).getString("msg");
if ("approve project OK".equals(jsonResult)) {
log.info("Approve team {} OK", pid);
return response.getBody().toString();
} else {
log.warn("Approve team {} FAIL", pid);
throw new DeterLabOperationFailedException(jsonResult);
}
} catch (JSONException e) {
log.warn("Error parsing response code approve project: {}", response.getBody().toString());
throw e;
}
}
public String rejectProject(String jsonString) {
// for ncl admins to reject teams
String pid = new JSONObject(jsonString).getString("pid");
log.info("Rejecting team {}: {}", pid, jsonString);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getRejectProject(), HttpMethod.POST, request, String.class);
} catch (RestClientException e) {
log.warn("DeterLab connection error reject project: {}", e);
throw new AdapterConnectionException();
}
try {
String jsonResult = new JSONObject(response.getBody().toString()).getString("msg");
if ("reject project OK".equals(jsonResult)) {
log.info("Reject team {} OK", pid);
return response.getBody().toString();
} else {
log.warn("Reject team {} FAIL", pid);
throw new DeterLabOperationFailedException(jsonResult);
}
} catch (JSONException e) {
log.warn("Error parsing response code reject project: {}", response.getBody().toString());
throw e;
}
}
public String getFreeNodes() {
log.info("Getting free nodes...");
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> request = new HttpEntity<>(headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getFreeNodes(), HttpMethod.GET, request, String.class);
} catch (RestClientException e) {
log.warn("DeterLab connection error get free nodes: {}", e);
return "0";
}
return response.getBody().toString();
}
public String getTopologyThumbnail(String jsonString) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonString, headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getTopoThumbnail(), HttpMethod.POST, request, String.class);
} catch (RestClientException e) {
log.warn("DeterLab connection error get thumbnail: {}", e);
throw new AdapterConnectionException();
}
return response.getBody().toString();
}
public String getUsageStatistics(String teamId, String startDate, String endDate) {
// start : mm/dd/yy
// end : mm/dd/yy
JSONObject tmp = new JSONObject();
tmp.put("pid", deterLabProjectRepository.findByNclTeamId(teamId).getDeterProjectId());
tmp.put("start", startDate);
tmp.put("end", endDate);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(tmp.toString(), headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getUsageStatistics(), HttpMethod.POST, request, String.class);
} catch (RestClientException e) {
log.warn("DeterLab connection error get usage statistics: {}", e);
return "?";
}
return response.getBody().toString();
}
public String getSavedImages(String teamId) {
final String pid = getDeterProjectIdByNclTeamId(teamId);
log.info("Getting list of saved images for project: {}", pid);
JSONObject json = new JSONObject();
json.put("pid", pid);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(json.toString(), headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getSavedImages(), HttpMethod.POST, request, String.class);
} catch (RestClientException e) {
log.warn("Adapter connection error get list of saved images by team: {}", e);
return "{}";
}
log.info("Get list of saved images OK, Deter response: {}", response.getBody().toString());
return response.getBody().toString();
}
public String saveImage(String nclTeamId, String nclUserId, String nodeId, String imageName, String currentOS) {
final String pid = getDeterProjectIdByNclTeamId(nclTeamId);
final String uid = getDeterUserIdByNclUserId(nclUserId);
log.info("Saving image: pid {}, uid {}, node ID {}, image name {}", pid, uid, nodeId, imageName);
JSONObject json = new JSONObject();
json.put("pid", pid);
json.put("uid", uid);
json.put("nodeId", nodeId);
json.put("imageName", imageName);
json.put("currentOS", currentOS);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(json.toString(), headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.saveImage(), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
String deterMessage = new JSONObject(responseBody).getString("msg");
if ("save image OK".equals(deterMessage)) {
log.info("Save image OK");
return responseBody;
} else {
log.warn("Save image FAIL");
throw new DeterLabOperationFailedException(deterMessage);
}
} catch (ResourceAccessException rae) {
log.warn("Save image error: {}", rae);
throw new AdapterConnectionException(rae.getMessage());
} catch (HttpServerErrorException hsee) {
log.warn("Save image error: Adapter DeterLab internal server error {}", hsee);
throw new AdapterInternalErrorException();
}
}
public String removeUserFromTeam(String nclTeamId, String nclUserId, String nclTeamOwnerId) {
final String pid = getDeterProjectIdByNclTeamId(nclTeamId);
final String uid = getDeterUserIdByNclUserId(nclUserId);
final String ownerUid = getDeterUserIdByNclUserId(nclTeamOwnerId);
log.info("Removing user {} from team {} requested by owner {}", uid, pid, ownerUid);
JSONObject json = new JSONObject();
json.put("pid", pid);
json.put("uidToBeRemoved", uid);
json.put("ownerUid", ownerUid);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(json.toString(), headers);
ResponseEntity response;
try {
response = restTemplate.exchange(properties.removeUserFromTeam(), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
String deterMessage = new JSONObject(responseBody).getString("msg");
if ("remove user from team ok".equals(deterMessage)) {
log.info("Remove user from team OK");
return responseBody;
} else {
log.warn("Remove user from team FAIL");
throw new DeterLabOperationFailedException(deterMessage);
}
} catch (ResourceAccessException rae) {
log.warn("Remove user from team: {}", rae);
throw new AdapterConnectionException(rae.getMessage());
} catch (HttpServerErrorException hsee) {
log.warn("Remove user from team: Adapter DeterLab internal server error {}", hsee);
throw new AdapterInternalErrorException();
}
}
/**
* Checks the response from adapter deterlab when applying or joining a new project as a new user and determines the exception to be thrown
* Use only if @applyProjectNewUsers and @joinProjectNewUsers are performing identical checks
* @param responseBody the JSON response from adapter deterlab python script
* @param logPrefix the prefix for the log messages to display either "Apply new project as new user..." or "Join new project as new user..."
*/
/*
private void checkAdapterResultNewUsers(String responseBody, String logPrefix) {
String jsonResult = new JSONObject(responseBody).getString("msg");
checkUserNotFoundError (responseBody, jsonResult, logPrefix);
checkEmailAddressError (responseBody, jsonResult, logPrefix);
checkInvalidPasswordError (responseBody, jsonResult, logPrefix);
checkTeamNameAlreadyExistsError (responseBody, jsonResult, logPrefix);
checkVerificationKeyError (responseBody, jsonResult, logPrefix);
if (!"user is created".equals(jsonResult)) {
log.warn(logPrefix, responseBody);
throw new DeterLabOperationFailedException("User creation failed");
}
}
private void checkVerificationKeyError (String responseBody, String jsonResult, String logPrefix) {
if ("verification key not found".equals(jsonResult)) {
log.warn(logPrefix + "Verification key is not found", responseBody);
throw new DeterLabOperationFailedException("Verification key is not found");
} else if ("incorrect verification key".equals(jsonResult)) {
log.warn(logPrefix + "Incorrect verification key", responseBody);
throw new DeterLabOperationFailedException("Incorrect verification key");
} else if ("user verification failed".equals(jsonResult)) {
log.warn(logPrefix + "user verification failed", responseBody);
throw new DeterLabOperationFailedException("User verification failed");
}
}
private void checkEmailAddressError (String responseBody, String jsonResult, String logPrefix) {
if ("email address in use".equals(jsonResult)) {
log.warn(logPrefix + "Email address already exists.", responseBody);
throw new EmailAlreadyExistsException("Email address already exists.");
}
}
private void checkInvalidPasswordError (String responseBody, String jsonResult, String logPrefix) {
if ("invalid password".equals(jsonResult)) {
log.warn(logPrefix + "Password is invalid.", responseBody);
throw new InvalidPasswordException();
}
}
private void checkTeamNameAlreadyExistsError (String responseBody, String jsonResult, String logPrefix) {
if ("team name is already in use".equals(jsonResult)) {
log.warn(logPrefix + "Team Name is already in use.", responseBody);
throw new TeamNameAlreadyExistsException("Team Name is already in use.");
}
}
private void checkUserNotFoundError (String responseBody, String jsonResult, String logPrefix) {
if ("user not created in deter database".equals(jsonResult)) {
log.warn(logPrefix + "User is not found in database.", responseBody);
throw new UserNotFoundException("User is not found in database.");
}
}
*/
/**
* Crafts the JSON string for start/stop experiment
* @param operation in or out, implies start or stop experiment respectively
* @param teamName the equivalent of pid
* @param experimentName the equivalent of eid
* @param nclUserId the ncl user id that initiate the start/stop experiment
* @return a JSON string representation of the items to be sent to adapter
*/
private String craftJSONStringStartStopExperiment(String operation, String teamName, String experimentName, String nclUserId) {
StringBuilder httpCommand = new StringBuilder();
httpCommand.append("?inout=" + operation);
httpCommand.append("&");
httpCommand.append("pid=" + teamName);
httpCommand.append("&");
httpCommand.append("eid=" + experimentName);
JSONObject jsonObject = new JSONObject();
jsonObject.put("httpCommand", httpCommand.toString());
jsonObject.put("deterLogin", getDeterUserIdByNclUserId(nclUserId));
jsonObject.put("pid", teamName);
jsonObject.put("eid", experimentName);
return jsonObject.toString();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package qa.qcri.aidr.predictui.api;
import java.util.List;
import qa.qcri.aidr.predictui.util.ResponseWrapper;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import qa.qcri.aidr.predictui.entities.Model;
import qa.qcri.aidr.predictui.facade.ModelFacade;
import qa.qcri.aidr.predictui.util.Config;
import qa.qcri.aidr.predictui.dto.ModelWrapper;
/**
* REST Web Service
*
* @author Imran
*/
@Path("/model")
@Stateless
public class ModelResource {
@Context
private UriInfo context;
@EJB
private ModelFacade modelLocalEJB;
public ModelResource() {
}
@GET
@Produces("application/json")
@Path("/all")
public Response getAllModels() {
List<Model> modelList = modelLocalEJB.getAllModels();
ResponseWrapper response = new ResponseWrapper();
response.setMessage(Config.STATUS_CODE_SUCCESS);
response.setModels(modelList);
return Response.ok(response).build();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
public Response getModelByID(@PathParam("id") int id){
Model model = modelLocalEJB.getModelByID(id);
return Response.ok(model).build();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("crisis/{crisisID}")
public Response getModelByCrisisID(@PathParam("crisisID") int crisisID){
List<ModelWrapper> modelList = modelLocalEJB.getModelByCrisisID(crisisID);
ResponseWrapper response = new ResponseWrapper();
if (modelList == null){
response.setMessage("No models found for the given crisis-id");
return Response.ok(response).build();
}
response.setModelWrapper(modelList);
return Response.ok(response).build();
}
}
|
package app.batch;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/*
* JobController
*
*/
@RestController
public class BatchLauncherController {
@Autowired
private JobLauncher launcher;
/*
* TODO
* CDINamedQualifier
* Bean
* @Bean(name = "job3")
*/
@Autowired
private Job job;
private final AtomicLong idGenerator = new AtomicLong(1);
@RequestMapping("/launch")
public String launch() throws JobExecutionAlreadyRunningException,
JobRestartException, JobInstanceAlreadyCompleteException,
JobParametersInvalidException {
//JobParameters
//cf. JobParametersIncrementer
JobParameters jobParameters = new JobParametersBuilder().addLong(
"simpleBatchId", idGenerator.getAndIncrement())
.toJobParameters();
JobExecution execution = launcher.run(job, jobParameters);
return execution.toString();
}
}
|
package application.factories;
import application.controllers.MainController;
import application.fxobjects.graphCells.CollectionCell;
import application.fxobjects.graphCells.RectangleCell;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Modality;
import javafx.stage.Stage;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
import static core.filtering.Filter.*;
import static java.lang.String.format;
@SuppressFBWarnings({"MS_PKGPROTECT", "MS_CANNOT_BE_FINAL"})
public class MenuFactory {
private static Menu filterLineage, filterHIV, filterCohort, filterStudyDistrict,
filterSpecimenType, filterIsolation, filterPhenoDST, filterCapreomycin, filterEthambutol,
filterEthionAmide, filterIsoniazid, filterKanamycin, filterPyrazinamide, filterOfloxacin,
filterRifampin, filterStreptomycin, filterSpoligotype, filterGenoDST, filterTF;
public static MenuItem loadPhylogeneticTree, loadGenome, loadMetadata, loadAnnotations, resetView,
shortcuts, about, showPhylogeneticTree, showGenomeSequence, showSelectedStrains, showOnlyThisStrain;
private MainController mainController;
private static Menu mostRecentGFA, mostRecentNWK, mostRecentGFF, mostRecentMeta;
private Menu fileMenu;
/**
* Enum for the recent menu dropdown types.
*/
private enum RecentMenuTypes {
GFF,
META_DATA,
GFA,
NWK
}
/**
* Constructor method for this class.
*
* @param controller the mainController to use.
*/
public MenuFactory(MainController controller) {
mainController = controller;
}
/**
* Method that creates a Menu.
*
* @param bar a MenuBar.
* @return the completed MenuBar.
*/
public MenuBar createMenu(MenuBar bar) {
fileMenu = initFileMenu();
Menu viewMenu = initViewMenu();
Menu filterMenu = initFilterMenu();
Menu helpMenu = initHelpMenu();
bar.getMenus().addAll(fileMenu, viewMenu, filterMenu, helpMenu);
return bar;
}
/**
* Method to disable and enable buttons in View-Menu
*
* @param x boolean
*/
public static void toggleViewMenu(boolean x) {
showGenomeSequence.setDisable(x);
showOnlyThisStrain.setDisable(x);
showPhylogeneticTree.setDisable(x);
showSelectedStrains.setDisable(x);
resetView.setDisable(x);
}
/**
* Method to disable and enable buttons in File-Menu
*
* @param x boolean
*/
public static void toggleFileMenu(boolean x) {
loadAnnotations.setDisable(x);
loadGenome.setDisable(x);
loadMetadata.setDisable(x);
loadPhylogeneticTree.setDisable(x);
}
/**
* Method to enable and disable buttons in the MostRecent menu
*
* @param x boolean
*/
public static void toggleMostRecent(boolean x) {
mostRecentNWK.setDisable(x);
mostRecentMeta.setDisable(x);
mostRecentGFA.setDisable(x);
mostRecentGFF.setDisable(x);
}
/**
* Create Help-Menu
*
* @return the Help-Menu
*/
private Menu initHelpMenu() {
about = initMenuItem("About", new KeyCodeCombination(KeyCode.TAB), event -> {
final Stage dialog = new Stage();
dialog.initModality(Modality.APPLICATION_MODAL);
LegendFactory legendFactory = new LegendFactory();
VBox content = new VBox();
content.getChildren().add(legendFactory.createLegend());
Text title = new Text(" Highlighting");
title.setFont(Font.font("Arial", FontWeight.BOLD, 18));
content.getChildren().add(title);
GridPane grid = buildHelpGridPane();
Text moreInfo = new Text(" More Information");
moreInfo.setFont(Font.font("Arial", FontWeight.BOLD, 18));
GridPane grid2 = buildHelpGridPane2();
content.getChildren().addAll(grid, moreInfo, grid2);
Scene dialogScene = new Scene(content, 900, 600);
dialog.setScene(dialogScene);
dialog.show();
});
shortcuts = initMenuItem("Shortcuts", null, event -> showShortCutMenu());
return initMenu("Help", shortcuts, about);
}
/**
* Build part 2 of the about Help-Section
*
* @return part 2
*/
private GridPane buildHelpGridPane2() {
GridPane grid2 = new GridPane();
grid2.setVgap(10);
grid2.setPadding(new Insets(10, 10, 10, 10));
grid2.add(new Text("- The box in the top right shows a "
+ "list of strains present in the graph."), 1, 0);
grid2.add(new Text("- The box below that gives info on "
+ "a selected node, like which strains\n"
+ "the node is in, its sequence and "
+ "annotation information."), 1, 1);
grid2.add(new Text(" "), 1, 2);
grid2.add(new Text("- The number inside a node indicates "
+ "how many other nodes are collapsed into it.\n"
+ "The size of a node is based on the total sequence "
+ "length inside it."), 1, 3);
return grid2;
}
/**
* Method to show and build the menu containing all shortcuts
*/
private void showShortCutMenu() {
final Stage dialog = new Stage();
dialog.initModality(Modality.APPLICATION_MODAL);
VBox content = new VBox();
GridPane grid = new GridPane();
grid.setVgap(5);
grid.setHgap(10);
grid.setPadding(new Insets(10, 10, 10, 10));
grid.add(new Text("Ctrl + G"), 0, 0);
grid.add(new Text("Load a GFA file (Genome Sequence"), 1, 0);
grid.add(new Text("Ctrl + O"), 0, 1);
grid.add(new Text("Load a NWK file (Phylogenetic Tree"), 1, 1);
grid.add(new Text("Ctrl + A"), 0, 2);
grid.add(new Text("Load a GFF file (Annotation data)"), 1, 2);
grid.add(new Text("Ctrl + M"), 0, 3);
grid.add(new Text("Load a MetaData file"), 1, 3);
grid.add(new Text("Tab"), 0, 4);
grid.add(new Text("Open about-information"), 1, 4);
content.getChildren().addAll(grid);
Scene dialogScene = new Scene(content, 300, 150);
dialog.setScene(dialogScene);
dialog.show();
}
/**
* Part 2 of the about Help-section
*
* @return part 2
*/
private GridPane buildHelpGridPane() {
final GridPane grid = new GridPane();
grid.setVgap(10);
grid.setPadding(new Insets(10, 20, 10, 10));
CollectionCell originallyFocusedCell = new CollectionCell(0, 1, "N");
originallyFocusedCell.originalFocus();
grid.add(originallyFocusedCell, 0, 1);
grid.add(new Text(" - When you click a cell, it becomes highlighted like this.\n "
+ "This means you will keep focus on this node, until deselection or selection "
+ "of another node."), 1, 1);
RectangleCell node1 = new RectangleCell(0, 1);
node1.sideFocus();
grid.add(node1, 0, 2);
grid.add(new Text(" - When zooming in on the originally focused node, nodes that \n"
+ "were previously collapsed under the selected node will light up."), 1, 2);
CollectionCell focusedCell = new CollectionCell(0, 1, "N");
focusedCell.focus();
grid.add(focusedCell, 0, 3);
grid.add(new Text(" - When zooming out, your originally focused node may collapse. "
+ "The node that contains \n your originally focused node, will now be marked as the "
+ "new focus. Zooming in will bring you back to your originally focused node."), 1, 3);
return grid;
}
/**
* Create the View-Menu
*
* @return the View-Menu
*/
private Menu initViewMenu() {
showGenomeSequence = initMenuItem("Show Graph", null, event -> {
if (mainController.getFiltering().isFiltering()) {
mainController.strainSelection(mainController.getLoadedGenomeNames());
} else {
mainController.fillGraph(new ArrayList<>(), new ArrayList<>());
}
});
showPhylogeneticTree = initMenuItem("Show Phylogenetic Tree", null, event -> mainController.fillTree());
showOnlyThisStrain = initMenuItem("Show graph & highlight selected strain", null, event -> {
mainController.getGraphController().getGraph().reset();
mainController.soloStrainSelection(mainController.getTreeController().getSelectedGenomes());
});
showSelectedStrains = initMenuItem("Show only the selected strains in graph", null, event -> {
mainController.toggleGenomeSearchBar(true);
mainController.strainSelection(mainController.getTreeController().getSelectedGenomes());
});
MenuItem separatorOne = new SeparatorMenuItem();
MenuItem separatorTwo = new SeparatorMenuItem();
resetView = initMenuItem("Reset", null, event -> {
mainController.getGraphController().getGraph().reset();
mainController.setCurrentView(mainController.getGraphController().getGraph().getLevelMaps().size() - 1);
if (mainController.getFiltering().isFiltering()) {
mainController.strainSelection(mainController.getLoadedGenomeNames());
} else {
mainController.fillGraph(new ArrayList<>(), new ArrayList<>());
}
mainController.getGraphController().getZoomBox().reset();
mainController.getGraphController().getGraphMouseHandling().setPrevClick(null);
mainController.createList();
});
showSelectedStrains.setDisable(true);
showOnlyThisStrain.setDisable(true);
return initMenu("View", showGenomeSequence, showPhylogeneticTree, separatorOne,
showSelectedStrains, showOnlyThisStrain, separatorTwo, resetView);
}
/**
* Create the File-Menu
*
* @return the File-Menu
*/
private Menu initFileMenu() {
loadAnnotations = initMenuItem("Load Annotation data",
new KeyCodeCombination(KeyCode.A, KeyCodeCombination.CONTROL_DOWN),
t -> WindowFactory.createAnnotationChooser());
loadMetadata = initMenuItem("Load Meta Data",
new KeyCodeCombination(KeyCode.M, KeyCodeCombination.CONTROL_DOWN),
t -> WindowFactory.createMetadataChooser());
loadGenome = initMenuItem("Load Genome Sequence",
new KeyCodeCombination(KeyCode.G, KeyCodeCombination.CONTROL_DOWN),
t -> WindowFactory.createGraphChooser());
loadPhylogeneticTree = initMenuItem("Load Phylogenetic Tree",
new KeyCodeCombination(KeyCode.O, KeyCodeCombination.CONTROL_DOWN),
t -> WindowFactory.createTreeChooser());
return initMenu("File", loadGenome, loadPhylogeneticTree, loadAnnotations, loadMetadata,
initMostRecentGFAMenu(), initMostRecentNWKMenu(), initMostRecentGFFMenu(),
initMostRecentMetadataMenu());
}
/**
* Create the menu for choosing a most recent GFF file
*
* @return the mostRecentGFFMenu
*/
private Menu initMostRecentGFFMenu() {
mostRecentGFF = initMostRecentMenu(RecentMenuTypes.GFF, mainController.getMostRecentGFF());
return mostRecentGFF;
}
/**
* Create the menu for choosing a most recent MetaData file
*
* @return the mostRecentMetaDataMenu
*/
private Menu initMostRecentMetadataMenu() {
mostRecentMeta = initMostRecentMenu(RecentMenuTypes.META_DATA, mainController.getMostRecentMetadata());
return mostRecentMeta;
}
/**
* Create the menu for choosing a most recent GFA file
*
* @return the mostRecentGFAMenu
*/
private Menu initMostRecentGFAMenu() {
mostRecentGFA = initMostRecentMenu(RecentMenuTypes.GFA, mainController.getMostRecentGFA());
return mostRecentGFA;
}
/**
* Create the menu for choosing a most recent NWK file
*
* @return the mostRecentNWKMenu
*/
private Menu initMostRecentNWKMenu() {
mostRecentNWK = initMostRecentMenu(RecentMenuTypes.NWK, mainController.getMostRecentNWK());
return mostRecentNWK;
}
/**
* Method to create a generic most recent menu
*
* @param type - the type of the menu (NWK, GFA, GFF or MetaData)
* @param mostRecentFileNames - list of most recent chosen filenames
* @return the created menu
*/
private Menu initMostRecentMenu(RecentMenuTypes type, Stack<String> mostRecentFileNames) {
List<String> recents = new ArrayList<>(Arrays.asList("Empty", "Empty", "Empty"));
for (int idx = 0; idx < 3; idx++) {
if (mostRecentFileNames.size() >= (idx + 1) && !(mostRecentFileNames.get(idx).equals("Empty"))) {
recents.set(idx, mostRecentFileNames.get(idx));
}
}
Menu menu = getMenuFromRecentMenuType(type);
for (int idx = 0; idx < recents.size(); idx++) {
int finalIdx = idx;
MenuItem recentMenuItem = initMenuItem(recents.get(idx), null, event -> {
String recentFile = recents.get(finalIdx);
setActionOnSelection(type, recentFile);});
if (recents.get(finalIdx).equals("Empty")) {
recentMenuItem.setDisable(true);
}
menu.getItems().add(recentMenuItem);
}
return menu;
}
/**
* Method to create the right menu with the right type
*
* @param type the wanted type
* @return
*/
private Menu getMenuFromRecentMenuType(RecentMenuTypes type) {
String fileTypeStr = "";
switch (type) {
case GFF: fileTypeStr = "GFF";
break;
case META_DATA: fileTypeStr = "Metadata";
break;
case GFA: fileTypeStr = "GFA";
break;
case NWK: fileTypeStr = "NWK";
break;
default: break;
}
return new Menu(format("Load recently opened %s file", fileTypeStr));
}
/**
* Add actions to perform when a button is selected to load a file
*
* @param type the file type
* @param recentFile the previously selected file
*/
private void setActionOnSelection(RecentMenuTypes type, String recentFile) {
if (!recentFile.isEmpty()) {
File file = new File(recentFile);
File parentDir = file.getParentFile();
switch (type) {
case GFF:
mainController.initAnnotations(recentFile);
mainController.addRecentGFF(recentFile);
break;
case META_DATA:
mainController.initMetadata(recentFile);
mainController.addRecentMetadata(recentFile);
break;
case GFA:
WindowFactory.createGFApopup(parentDir, file);
break;
case NWK:
WindowFactory.createNWKpopup(parentDir, file);
break;
default:
break;
}
}
}
/**
* Method to create a Menu containing all filters
*
* @return the created menu
*/
private Menu initFilterMenu() {
initLineageFilter();
initHIVFilter();
initCohortFilter();
initDistrictFilter();
initSpecimenFilter();
initIsolationFilter();
initPhenoDSTfilter();
initCapreomycinFilter();
initEthambutolFilter();
initEthionamideFilter();
initIsoniazidFilter();
initKanamycinFilter();
initPyrazinamideFilter();
initOfloxacinFilter();
initRifampinFilter();
initStreptomycinFilter();
initSpoligotypeFilter();
initGenoDSTFilter();
initTFFilter();
return initMenu("Filter", filterCapreomycin, filterCohort, filterEthambutol, filterEthionAmide,
filterGenoDST, filterHIV, filterIsolation, filterIsoniazid, filterKanamycin, filterLineage,
filterOfloxacin, filterPhenoDST, filterPyrazinamide, filterRifampin, filterSpecimenType,
filterSpoligotype, filterStreptomycin, filterStudyDistrict, filterTF);
}
/**
* Template method to create a Menu
*
* @param title the title of the Menu
* @param items the items in the Menu
* @return the new Menu
*/
private Menu initMenu(String title, final MenuItem... items) {
Menu newMenu = new Menu(title);
newMenu.getItems().addAll(items);
return newMenu;
}
/**
* Template method to create a MenuItem
*
* @param title the title of the MenuItem
* @param combination the keycombination to invoke the action of the button
* @param handler the EventHandler
* @return the new MenuItem
*/
private MenuItem initMenuItem(String title, KeyCombination combination, EventHandler<ActionEvent> handler) {
MenuItem newItem = new MenuItem(title);
newItem.setAccelerator(combination);
newItem.setOnAction(handler);
return newItem;
}
/**
* Method to create each LineageFilter
*/
private void initLineageFilter() {
filterLineage = new Menu("Lineage");
CheckMenuItem lin1 = new CheckMenuItem("LIN 1");
lin1.setOnAction(event -> mainController.modifyFilter(LIN1, lin1.isSelected()));
CheckMenuItem lin2 = new CheckMenuItem("LIN 2");
lin2.setOnAction(event -> mainController.modifyFilter(LIN2, lin2.isSelected()));
CheckMenuItem lin3 = new CheckMenuItem("LIN 3");
lin3.setOnAction(event -> mainController.modifyFilter(LIN3, lin3.isSelected()));
CheckMenuItem lin4 = new CheckMenuItem("LIN 4");
lin4.setOnAction(event -> mainController.modifyFilter(LIN4, lin4.isSelected()));
CheckMenuItem lin5 = new CheckMenuItem("LIN 5");
lin5.setOnAction(event -> mainController.modifyFilter(LIN5, lin5.isSelected()));
CheckMenuItem lin6 = new CheckMenuItem("LIN 6");
lin6.setOnAction(event -> mainController.modifyFilter(LIN6, lin6.isSelected()));
CheckMenuItem lin7 = new CheckMenuItem("LIN 7");
lin7.setOnAction(event -> mainController.modifyFilter(LIN7, lin7.isSelected()));
CheckMenuItem lin8 = new CheckMenuItem("LIN animal");
lin8.setOnAction(event -> mainController.modifyFilter(LIN8, lin8.isSelected()));
CheckMenuItem lin9 = new CheckMenuItem("LIN B");
lin9.setOnAction(event -> mainController.modifyFilter(LIN9, lin9.isSelected()));
CheckMenuItem lin10 = new CheckMenuItem("LIN CANETTII");
lin10.setOnAction(event -> mainController.modifyFilter(LIN10, lin10.isSelected()));
filterLineage = initMenu("Lineage", lin1, lin2, lin3, lin4, lin5, lin6, lin7, lin8, lin9, lin10);
}
/**
* Method to create the HIVFilter
*/
private void initHIVFilter() {
final ToggleGroup hiv = new ToggleGroup();
RadioMenuItem pos = new RadioMenuItem("Positive");
RadioMenuItem neg = new RadioMenuItem("Negative");
RadioMenuItem non = new RadioMenuItem("Either");
pos.setToggleGroup(hiv);
neg.setToggleGroup(hiv);
non.setToggleGroup(hiv);
non.setSelected(true);
hiv.selectedToggleProperty().addListener(ob -> {
if (pos.isSelected()) {
mainController.modifyFilter(HIVN, false);
mainController.modifyFilter(HIVP, true);
} else if (neg.isSelected()) {
mainController.modifyFilter(HIVP, false);
mainController.modifyFilter(HIVN, true);
} else {
mainController.modifyFilter(HIVP, false);
mainController.modifyFilter(HIVN, false);
}
});
filterHIV = initMenu("HIV", pos, neg, non);
}
/**
* Method to create the CohortFilter
*/
private void initCohortFilter() {
filterCohort = new Menu("Cohort");
CheckMenuItem cohort1 = new CheckMenuItem("KZNSUR");
cohort1.setOnAction(event -> mainController.modifyFilter(KZNSUR, cohort1.isSelected()));
CheckMenuItem cohort2 = new CheckMenuItem("PROX");
cohort2.setOnAction(event -> mainController.modifyFilter(PROX, cohort2.isSelected()));
CheckMenuItem cohort3 = new CheckMenuItem("NHLS");
cohort3.setOnAction(event -> mainController.modifyFilter(NHLS, cohort3.isSelected()));
CheckMenuItem cohort4 = new CheckMenuItem("CUBS");
cohort4.setOnAction(event -> mainController.modifyFilter(CUBS, cohort4.isSelected()));
CheckMenuItem cohort5 = new CheckMenuItem("Phage");
cohort5.setOnAction(event -> mainController.modifyFilter(PHAGE, cohort5.isSelected()));
filterCohort = initMenu("Cohort", cohort1, cohort2, cohort3, cohort4, cohort5);
}
/**
* Method to create the DistrictFilter
*/
private void initDistrictFilter() {
CheckMenuItem dist1 = new CheckMenuItem("Amajuba");
dist1.setOnAction(event -> mainController.modifyFilter(AMAJUBA, dist1.isSelected()));
CheckMenuItem dist2 = new CheckMenuItem("eThekwini");
dist1.setOnAction(event -> mainController.modifyFilter(ETHEKWINI, dist2.isSelected()));
CheckMenuItem dist3 = new CheckMenuItem("iLembe");
dist1.setOnAction(event -> mainController.modifyFilter(ILEMBE, dist3.isSelected()));
CheckMenuItem dist4 = new CheckMenuItem("Sisonke");
dist1.setOnAction(event -> mainController.modifyFilter(SISONKE, dist4.isSelected()));
CheckMenuItem dist5 = new CheckMenuItem("Ugu");
dist1.setOnAction(event -> mainController.modifyFilter(UGU, dist5.isSelected()));
CheckMenuItem dist6 = new CheckMenuItem("uMgungundlovu");
dist1.setOnAction(event -> mainController.modifyFilter(UMGUNGUNDLOVU, dist6.isSelected()));
CheckMenuItem dist7 = new CheckMenuItem("uMkhanyakude");
dist1.setOnAction(event -> mainController.modifyFilter(UMKHANYAKUDE, dist7.isSelected()));
CheckMenuItem dist8 = new CheckMenuItem("uMzinyathi");
dist1.setOnAction(event -> mainController.modifyFilter(UMZINYATHI, dist8.isSelected()));
CheckMenuItem dist9 = new CheckMenuItem("Uthukela");
dist1.setOnAction(event -> mainController.modifyFilter(UTHUKELA, dist9.isSelected()));
CheckMenuItem dist10 = new CheckMenuItem("uThungulu");
dist1.setOnAction(event -> mainController.modifyFilter(UTHUNGULU, dist10.isSelected()));
CheckMenuItem dist11 = new CheckMenuItem("Zululand");
dist1.setOnAction(event -> mainController.modifyFilter(ZULULAND, dist11.isSelected()));
filterStudyDistrict = initMenu("Study District", dist1, dist2, dist3, dist4, dist5,
dist6, dist7, dist8, dist9, dist10, dist11);
}
/**
* Method to create the SpecimenFilter
*/
private void initSpecimenFilter() {
CheckMenuItem spec1 = new CheckMenuItem("blood");
spec1.setOnAction(event -> mainController.modifyFilter(BLOOD, spec1.isSelected()));
CheckMenuItem spec2 = new CheckMenuItem("CSF");
spec2.setOnAction(event -> mainController.modifyFilter(CSF, spec2.isSelected()));
CheckMenuItem spec3 = new CheckMenuItem("pleura");
spec3.setOnAction(event -> mainController.modifyFilter(PLEURA, spec3.isSelected()));
CheckMenuItem spec4 = new CheckMenuItem("pleural fluid");
spec4.setOnAction(event -> mainController.modifyFilter(PLEURAL_FLUID, spec4.isSelected()));
CheckMenuItem spec5 = new CheckMenuItem("pus");
spec5.setOnAction(event -> mainController.modifyFilter(PUS, spec5.isSelected()));
CheckMenuItem spec6 = new CheckMenuItem("sputum");
spec6.setOnAction(event -> mainController.modifyFilter(SPUTUM, spec6.isSelected()));
filterSpecimenType = initMenu("Specimen type", spec1, spec2, spec3, spec4, spec5, spec6);
}
/**
* Method to create the IsolationFilter
*/
private void initIsolationFilter() {
CheckMenuItem iso1 = new CheckMenuItem("single colony");
iso1.setOnAction(event -> mainController.modifyFilter(SINGLE_COLONY, iso1.isSelected()));
CheckMenuItem iso2 = new CheckMenuItem("non-single colony");
iso2.setOnAction(event -> mainController.modifyFilter(NON_SINGLE_COLONY, iso2.isSelected()));
filterIsolation = initMenu("DNA isolation", iso1, iso2);
}
/**
* Method to create the PhenoDSTFilter
*/
private void initPhenoDSTfilter() {
CheckMenuItem dst1 = new CheckMenuItem("MDR");
dst1.setOnAction(event -> mainController.modifyFilter(PHENO_MDR, dst1.isSelected()));
CheckMenuItem dst2 = new CheckMenuItem("mono");
dst2.setOnAction(event -> mainController.modifyFilter(PHENO_MONO, dst2.isSelected()));
CheckMenuItem dst3 = new CheckMenuItem("poly");
dst3.setOnAction(event -> mainController.modifyFilter(PHENO_POLY, dst3.isSelected()));
CheckMenuItem dst4 = new CheckMenuItem("susceptible");
dst4.setOnAction(event -> mainController.modifyFilter(PHENO_SUSCEPTIBLE, dst4.isSelected()));
CheckMenuItem dst5 = new CheckMenuItem("XDR");
dst5.setOnAction(event -> mainController.modifyFilter(PHENO_XDR, dst5.isSelected()));
filterPhenoDST = initMenu("Phenotypic DST", dst1, dst2, dst3, dst4, dst5);
}
/**
* Method to create the CapreomycinFilter
*/
private void initCapreomycinFilter() {
CheckMenuItem cap1 = new CheckMenuItem("R");
cap1.setOnAction(event -> mainController.modifyFilter(CAPREOMYCIN_R, cap1.isSelected()));
CheckMenuItem cap2 = new CheckMenuItem("S");
cap2.setOnAction(event -> mainController.modifyFilter(CAPREOMYCIN_S, cap2.isSelected()));
CheckMenuItem cap3 = new CheckMenuItem("U");
cap3.setOnAction(event -> mainController.modifyFilter(CAPREOMYCIN_U, cap3.isSelected()));
filterCapreomycin = initMenu("Capreomycin", cap1, cap2, cap3);
}
/**
* Method to create the EthambutolFilter
*/
private void initEthambutolFilter() {
CheckMenuItem eth1 = new CheckMenuItem("R");
eth1.setOnAction(event -> mainController.modifyFilter(ETHAMBUTOL_R, eth1.isSelected()));
CheckMenuItem eth2 = new CheckMenuItem("S");
eth2.setOnAction(event -> mainController.modifyFilter(ETHAMBUTOL_S, eth2.isSelected()));
CheckMenuItem eth3 = new CheckMenuItem("U");
eth3.setOnAction(event -> mainController.modifyFilter(ETHAMBUTOL_R, eth3.isSelected()));
filterEthambutol = initMenu("Ethambutol", eth1, eth2, eth3);
}
/**
* Method to create the EthionamideFilter
*/
private void initEthionamideFilter() {
CheckMenuItem eth1 = new CheckMenuItem("R");
eth1.setOnAction(event -> mainController.modifyFilter(ETHIONAMIDE_R, eth1.isSelected()));
CheckMenuItem eth2 = new CheckMenuItem("S");
eth2.setOnAction(event -> mainController.modifyFilter(ETHIONAMIDE_S, eth2.isSelected()));
CheckMenuItem eth3 = new CheckMenuItem("U");
eth3.setOnAction(event -> mainController.modifyFilter(ETHIONAMIDE_U, eth3.isSelected()));
filterEthionAmide = initMenu("Ethionamide", eth1, eth2, eth3);
}
/**
* Method to create the IsoniazidFilter
*/
private void initIsoniazidFilter() {
CheckMenuItem iso1 = new CheckMenuItem("R");
iso1.setOnAction(event -> mainController.modifyFilter(ISONIAZID_R, iso1.isSelected()));
CheckMenuItem iso2 = new CheckMenuItem("S");
iso2.setOnAction(event -> mainController.modifyFilter(ISONIAZID_S, iso2.isSelected()));
CheckMenuItem iso3 = new CheckMenuItem("U");
iso3.setOnAction(event -> mainController.modifyFilter(ISONIAZID_U, iso3.isSelected()));
filterIsoniazid = initMenu("Isoniazid", iso1, iso2, iso3);
}
/**
* Method to create the KanamycinFilter
*/
private void initKanamycinFilter() {
CheckMenuItem kan1 = new CheckMenuItem("R");
kan1.setOnAction(event -> mainController.modifyFilter(KANAMYCIN_R, kan1.isSelected()));
CheckMenuItem kan2 = new CheckMenuItem("S");
kan2.setOnAction(event -> mainController.modifyFilter(KANAMYCIN_S, kan2.isSelected()));
CheckMenuItem kan3 = new CheckMenuItem("U");
kan3.setOnAction(event -> mainController.modifyFilter(KANAMYCIN_U, kan3.isSelected()));
filterKanamycin = initMenu("Kanamycin", kan1, kan2, kan3);
}
/**
* Method to create the PyrazinamideFilter
*/
private void initPyrazinamideFilter() {
CheckMenuItem pyr1 = new CheckMenuItem("R");
pyr1.setOnAction(event -> mainController.modifyFilter(PYRAZINAMIDE_R, pyr1.isSelected()));
CheckMenuItem pyr2 = new CheckMenuItem("S");
pyr2.setOnAction(event -> mainController.modifyFilter(PYRAZINAMIDE_S, pyr2.isSelected()));
CheckMenuItem pyr3 = new CheckMenuItem("U");
pyr3.setOnAction(event -> mainController.modifyFilter(PYRAZINAMIDE_U, pyr3.isSelected()));
filterPyrazinamide = initMenu("Pyrazinamide", pyr1, pyr2, pyr3);
}
/**
* Method to create the OfloxacinFilter
*/
private void initOfloxacinFilter() {
CheckMenuItem ofl1 = new CheckMenuItem("R");
ofl1.setOnAction(event -> mainController.modifyFilter(OFLOXACIN_R, ofl1.isSelected()));
CheckMenuItem ofl2 = new CheckMenuItem("S");
ofl2.setOnAction(event -> mainController.modifyFilter(OFLOXACIN_S, ofl2.isSelected()));
CheckMenuItem ofl3 = new CheckMenuItem("U");
ofl3.setOnAction(event -> mainController.modifyFilter(OFLOXACIN_U, ofl3.isSelected()));
filterOfloxacin = initMenu("Ofloxacin", ofl1, ofl2, ofl3);
}
/**
* Method to create the RifampinFilter
*/
private void initRifampinFilter() {
CheckMenuItem rif1 = new CheckMenuItem("R");
rif1.setOnAction(event -> mainController.modifyFilter(RIFAMPIN_R, rif1.isSelected()));
CheckMenuItem rif2 = new CheckMenuItem("S");
rif2.setOnAction(event -> mainController.modifyFilter(RIFAMPIN_S, rif2.isSelected()));
CheckMenuItem rif3 = new CheckMenuItem("U");
rif3.setOnAction(event -> mainController.modifyFilter(RIFAMPIN_U, rif3.isSelected()));
filterRifampin = initMenu("Rifampin", rif1, rif2, rif3);
}
/**
* Method to create the StreptomycinFilter
*/
private void initStreptomycinFilter() {
CheckMenuItem str1 = new CheckMenuItem("R");
str1.setOnAction(event -> mainController.modifyFilter(STREPTOMYCIN_R, str1.isSelected()));
CheckMenuItem str2 = new CheckMenuItem("S");
str2.setOnAction(event -> mainController.modifyFilter(STREPTOMYCIN_S, str2.isSelected()));
CheckMenuItem str3 = new CheckMenuItem("U");
str3.setOnAction(event -> mainController.modifyFilter(STREPTOMYCIN_U, str3.isSelected()));
filterStreptomycin = initMenu("Streptomycin", str1, str2, str3);
}
/**
* Method to create the SpoligotypeFilter
*/
private void initSpoligotypeFilter() {
CheckMenuItem spo1 = new CheckMenuItem("Bejing");
spo1.setOnAction(event -> mainController.modifyFilter(SPOLIGOTYPE_BEJING, spo1.isSelected()));
CheckMenuItem spo2 = new CheckMenuItem("CAS");
spo2.setOnAction(event -> mainController.modifyFilter(SPOLIGOTYPE_CAS, spo2.isSelected()));
CheckMenuItem spo3 = new CheckMenuItem("CAS1-Delhi");
spo3.setOnAction(event -> mainController.modifyFilter(SPOLIGOTYPE_CAS1_DELHI, spo3.isSelected()));
CheckMenuItem spo4 = new CheckMenuItem("CAS1-Kili");
spo4.setOnAction(event -> mainController.modifyFilter(SPOLIGOTYPE_CAS1_KILI, spo4.isSelected()));
CheckMenuItem spo5 = new CheckMenuItem("EAI1-SOM");
spo5.setOnAction(event -> mainController.modifyFilter(SPOLIGOTYPE_EAI1_SOM, spo5.isSelected()));
CheckMenuItem spo6 = new CheckMenuItem("H1");
spo6.setOnAction(event -> mainController.modifyFilter(SPOLIGOTYPE_H1, spo6.isSelected()));
CheckMenuItem spo7 = new CheckMenuItem("H37Rv");
spo7.setOnAction(event -> mainController.modifyFilter(SPOLIGOTYPE_H37RV, spo7.isSelected()));
initSpoligotypeFilter2(spo1, spo2, spo3, spo4, spo5, spo6, spo7);
}
/**
* Method to create the second part of the SpoligotypeFilter
*/
private void initSpoligotypeFilter2(CheckMenuItem spo1, CheckMenuItem spo2, CheckMenuItem spo3,
CheckMenuItem spo4, CheckMenuItem spo5, CheckMenuItem spo6, CheckMenuItem sp7) {
CheckMenuItem s = new CheckMenuItem("LAM11-ZWE");
s.setOnAction(event -> mainController.modifyFilter(SPOLIGOTYPE_LAM11_ZWE, s.isSelected()));
CheckMenuItem s9 = new CheckMenuItem("LAM3");
s9.setOnAction(event -> mainController.modifyFilter(SPOLIGOTYPE_LAM3, s9.isSelected()));
CheckMenuItem s11 = new CheckMenuItem("LAM4");
s11.setOnAction(event -> mainController.modifyFilter(SPOLIGOTYPE_LAM4, s11.isSelected()));
CheckMenuItem s12 = new CheckMenuItem("LAM5");
s12.setOnAction(event -> mainController.modifyFilter(SPOLIGOTYPE_LAM5, s12.isSelected()));
CheckMenuItem s13 = new CheckMenuItem("LAM6");
s13.setOnAction(event -> mainController.modifyFilter(SPOLIGOTYPE_LAM6, s13.isSelected()));
CheckMenuItem s14 = new CheckMenuItem("LAM9");
s14.setOnAction(event -> mainController.modifyFilter(SPOLIGOTYPE_LAM9, s14.isSelected()));
CheckMenuItem s15 = new CheckMenuItem("S");
s15.setOnAction(event -> mainController.modifyFilter(SPOLIGOTYPE_S, s15.isSelected()));
CheckMenuItem s16 = new CheckMenuItem("T1");
s16.setOnAction(event -> mainController.modifyFilter(SPOLIGOTYPE_T1, s16.isSelected()));
CheckMenuItem s17 = new CheckMenuItem("T2");
s17.setOnAction(event -> mainController.modifyFilter(SPOLIGOTYPE_T2, s17.isSelected()));
CheckMenuItem s18 = new CheckMenuItem("T3");
s18.setOnAction(event -> mainController.modifyFilter(SPOLIGOTYPE_T3, s18.isSelected()));
CheckMenuItem sn = new CheckMenuItem("T5-RUS1");
sn.setOnAction(event -> mainController.modifyFilter(SPOLIGOTYPE_T5_RUS1, sn.isSelected()));
CheckMenuItem s20 = new CheckMenuItem("X2");
s20.setOnAction(event -> mainController.modifyFilter(SPOLIGOTYPE_X2, s20.isSelected()));
CheckMenuItem s21 = new CheckMenuItem("X3");
s21.setOnAction(event -> mainController.modifyFilter(SPOLIGOTYPE_X3, s21.isSelected()));
filterSpoligotype = initMenu("Digital spoligotype", spo1, spo2, spo3, spo4, spo5, spo6, sp7, s, s9,
s11, s12, s13, s14, s15, s16, s17, s18, sn, s20, s21);
}
/**
* Method to create the GenoDSTFilter
*/
private void initGenoDSTFilter() {
CheckMenuItem gen1 = new CheckMenuItem("Drug-resistant (other)");
gen1.setOnAction(event -> mainController.modifyFilter(GENO_DRUG_RESIST, gen1.isSelected()));
CheckMenuItem gen2 = new CheckMenuItem("MDR");
gen2.setOnAction(event -> mainController.modifyFilter(GENO_MDR, gen2.isSelected()));
CheckMenuItem gen3 = new CheckMenuItem("susceptible");
gen3.setOnAction(event -> mainController.modifyFilter(GENO_SUSCEPTIBLE, gen3.isSelected()));
CheckMenuItem gen4 = new CheckMenuItem("XDR");
gen4.setOnAction(event -> mainController.modifyFilter(GENO_XDR, gen4.isSelected()));
filterGenoDST = initMenu("Genotypic DST", gen1, gen2, gen3, gen4);
}
/**
* Method to create the TFF filter
*/
private void initTFFilter() {
final ToggleGroup tf = new ToggleGroup();
RadioMenuItem pos = new RadioMenuItem("True");
RadioMenuItem neg = new RadioMenuItem("False");
RadioMenuItem non = new RadioMenuItem("Either");
pos.setToggleGroup(tf);
neg.setToggleGroup(tf);
non.setToggleGroup(tf);
non.setSelected(true);
tf.selectedToggleProperty().addListener(ob -> {
if (pos.isSelected()) {
mainController.modifyFilter(NTF, false);
mainController.modifyFilter(TF, true);
} else if (neg.isSelected()) {
mainController.modifyFilter(TF, false);
mainController.modifyFilter(NTF, true);
} else {
mainController.modifyFilter(TF, false);
mainController.modifyFilter(NTF, false);
}
});
filterTF = initMenu("Tugela Ferry XDR", pos, neg, non);
}
}
|
package bixie.translation.soot;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import bixie.translation.Options;
import bixie.util.Log;
import soot.Body;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
/**
* The Soot Runner
*
* @author schaef
*/
public class SootRunner {
protected final soot.options.Options sootOpt = soot.options.Options.v();
public void run(String input) {
if (null == input || input.isEmpty()) {
return;
}
if (input.endsWith(".jar")) {
// run with JAR file
runWithJar(input);
} else {
File file = new File(input);
if (file.isDirectory()) {
runWithPath(input);
} else {
throw new RuntimeException("Don't know what to do with: "
+ input);
}
}
}
/**
* Runs Soot by using a JAR file
*
* @param jarFile
* JAR file
* @param smtFile
* Boogie file
*/
public void runWithJar(String jarFile) {
try {
// extract dependent JARs
List<File> jarFiles = new ArrayList<File>();
jarFiles.addAll(extractClassPath(new File(jarFile)));
jarFiles.add(new File(jarFile));
// additional classpath available?
String cp = buildClassPath(jarFiles);
if (Options.v().hasClasspath()) {
cp += File.pathSeparatorChar + Options.v().getClasspath();
}
// set soot-class-path
sootOpt.set_soot_classpath(cp);
// finally, run soot
runSootAndAnalysis(enumClasses(new File(jarFile)));
} catch (Exception e) {
Log.error(e.toString());
}
}
/**
* Runs Soot by using a path (e.g., from Joogie)
*
* @param path
* Path
* @param smtFile
* Boogie file
*/
public void runWithPath(String path) {
try {
// dependent JAR files
List<File> jarFiles = new ArrayList<File>();
// additional classpath available?
String cp = buildClassPath(jarFiles);
if (Options.v().hasClasspath()) {
cp += File.pathSeparatorChar + Options.v().getClasspath();
}
// set soot-class-path
sootOpt.set_soot_classpath(cp);
sootOpt.set_src_prec(soot.options.Options.src_prec_class);
List<String> processDirs = new LinkedList<String>();
processDirs.add(path);
sootOpt.set_process_dir(processDirs);
// finally, run soot
runSootAndAnalysis(new LinkedList<String>());
} catch (Exception e) {
Log.error(e.toString());
}
}
/**
* Enumeration containing the callgraph algorithms supported for the use
* with the data flow tracker
*
* @see https
* ://github.com/secure-software-engineering/soot-infoflow/blob/develop
* /src/soot/jimple/infoflow/Infoflow.java
*/
public enum CallgraphAlgorithm {
None, CHA, VTA, RTA, SPARK
}
/**
* Enumeration containing the aliasing algorithms supported by FlowDroid
*
* @see https
* ://github.com/secure-software-engineering/soot-infoflow/blob/develop
* /src/soot/jimple/infoflow/Infoflow.java
*/
public enum AliasingAlgorithm {
/**
* A fully flow-sensitive algorithm based on Andromeda
*/
FlowSensitive,
/**
* A flow-insensitive algorithm based on Soot's point-to-sets
*/
PtsBased
}
/**
* Run Soot and creates an inter-procedural callgraph
* that could be loaded by Soot.
* @param classes additional classes that need to be loaded (e.g., when analyzing jars)
*/
protected void runSootAndAnalysis(List<String> classes) {
sootOpt.set_keep_line_number(true);
sootOpt.set_prepend_classpath(true);
sootOpt.set_output_format(soot.options.Options.output_format_none);
sootOpt.set_allow_phantom_refs(true);
sootOpt.setPhaseOption("jop.cpf", "enabled:false");
for (String s : classes) {
Scene.v().addBasicClass(s, SootClass.BODIES);
}
// CallgraphAlgorithm cga = Options.v().getCallGraphAlgorithm();
// if (cga!=CallgraphAlgorithm.None) {
// sootOpt.set_whole_program(true);
// // Configure the callgraph algorithm
// switch (cga) {
// case CHA:
// sootOpt.setPhaseOption("cg.cha", "on");
// break;
// case RTA:
// sootOpt.setPhaseOption("cg.spark", "on");
// sootOpt.setPhaseOption("cg.spark", "rta:true");
// sootOpt.setPhaseOption("cg.spark", "string-constants:true");
// break;
// case VTA:
// sootOpt.setPhaseOption("cg.spark", "on");
// sootOpt.setPhaseOption("cg.spark", "vta:true");
// sootOpt.setPhaseOption("cg.spark", "string-constants:true");
// break;
// case SPARK:
// sootOpt.setPhaseOption("cg.spark", "on");
// sootOpt.setPhaseOption("cg.spark", "string-constants:true");
// break;
// default:
// throw new RuntimeException("Invalid callgraph algorithm");
// Iterator Hack
Scene.v().addBasicClass(
"org.eclipse.jdt.core.compiler.CategorizedProblem",
SootClass.HIERARCHY);
Scene.v().addBasicClass("java.lang.Iterable", SootClass.SIGNATURES);
Scene.v().addBasicClass("java.util.Iterator", SootClass.SIGNATURES);
Scene.v()
.addBasicClass("java.lang.reflect.Array", SootClass.SIGNATURES);
try {
// redirect soot output into a stream.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
soot.G.v().out = new PrintStream(baos, true, "utf-8");
//Now load the soot classes.
Scene.v().loadNecessaryClasses();
Scene.v().loadBasicClasses();
for (SootClass sc : Scene.v().getClasses()) {
if (classes.contains(sc.getName())) {
sc.setApplicationClass();
}
}
for (SootClass sc : new LinkedList<SootClass>(Scene.v().getClasses())) {
if (sc.resolvingLevel()<SootClass.SIGNATURES) {
continue;
}
if (sc.isApplicationClass()) {
for (SootMethod sm : sc.getMethods()) {
if (sm.isConcrete()) {
try {
Body body = sm.retrieveActiveBody();
sm.setActiveBody(body);
if (body!=null) {
SootBodyTransformer sbt = new SootBodyTransformer();
sbt.transform(body);
}
} catch (Throwable t) {
Log.error("Failed to process "+sm.getSignature());
t.printStackTrace();
}
}
}
}
}
Log.info("Done.");
} catch (UnsupportedEncodingException e) {
Log.error(e.toString());
} catch (Throwable e) {
Log.error("Soot could not process the input. STOPPING");
e.printStackTrace();
}
}
/**
* Returns the class path argument for Soot
*
* @param files
* Files in the class path
* @return Class path argument for Soot
*/
protected String buildClassPath(List<File> files) {
StringBuilder sb = new StringBuilder();
for (File file : files) {
sb.append(file.getPath() + File.pathSeparatorChar);
}
return sb.toString();
}
/**
* Extracts dependent JARs from the JAR's manifest
*
* @param file
* JAR file object
* @returns jarFiles
* List of dependent JARs
*/
protected List<File> extractClassPath(File file) {
List<File> jarFiles = new LinkedList<File>();
try {
// open JAR file
JarFile jarFile = new JarFile(file);
// get manifest and their main attributes
Manifest manifest = jarFile.getManifest();
if (manifest == null) {
jarFile.close();
return jarFiles;
}
Attributes mainAttributes = manifest.getMainAttributes();
if (mainAttributes == null) {
jarFile.close();
return jarFiles;
}
String classPath = mainAttributes
.getValue(Attributes.Name.CLASS_PATH);
// close JAR file
jarFile.close();
// empty class path?
if (null == classPath)
return jarFiles;
// look for dependent JARs
String[] classPathItems = classPath.split(" ");
for (String classPathItem : classPathItems) {
if (classPathItem.endsWith(".jar")) {
// add jar
Log.debug("Adding " + classPathItem
+ " to Soot's class path");
jarFiles.add(new File(file.getParent(), classPathItem));
}
}
} catch (IOException e) {
Log.error(e.toString());
}
return jarFiles;
}
/**
* Enumerates all classes in a JAR file
* @param file a Jar file
* @returns list of classes in the Jar file.
*/
protected List<String> enumClasses(File file) {
List<String> classes = new LinkedList<String>();
try {
// open JAR file
Log.debug("Opening jar " + file.getPath());
JarFile jarFile = new JarFile(file);
Enumeration<JarEntry> entries = jarFile.entries();
// iterate JAR entries
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String entryName = entry.getName();
if (entryName.endsWith(".class")) {
// get class
String className = entryName.substring(0,
entryName.length() - ".class".length());
className = className.replace('/', '.');
// add class
Log.debug("Adding class " + className);
classes.add(className);
}
}
// close JAR file
jarFile.close();
} catch (IOException e) {
Log.error(e.toString());
}
return classes;
}
}
|
package cn.com.lemon.framework.model;
/**
* The tree data base bean
*
* @author shellpo shih
* @version 1.0
*/
public class Node<I, N> {
public I id;
public N name;
public void setId(I id) {
this.id = id;
}
public I getId() {
return id;
}
public N getName() {
return name;
}
public void setName(N name) {
this.name = name;
}
}
|
package com.algolia.search.saas;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
/**
* Entry point in the Java API.
* You should instantiate a Client object with your ApplicationID, ApiKey and Hosts
* to start using Algolia Search API
*/
public class APIClient {
private int httpSocketTimeoutMS = 30000;
private int httpConnectTimeoutMS = 3000;
private final static String version;
static {
String tmp = "N/A";
try {
InputStream versionStream = APIClient.class.getResourceAsStream("/version.properties");
if (versionStream != null) {
BufferedReader versionReader = new BufferedReader(new InputStreamReader(versionStream));
tmp = versionReader.readLine();
versionReader.close();
}
} catch (IOException e) {
// not fatal
}
version = tmp;
}
private final String applicationID;
private final String apiKey;
private final List<String> hostsArray;
private final HttpClient httpClient;
private String forwardRateLimitAPIKey;
private String forwardEndUserIP;
private String forwardAdminAPIKey;
private HashMap<String, String> headers;
/**
* Algolia Search initialization
* @param applicationID the application ID you have in your admin interface
* @param apiKey a valid API key for the service
*/
public APIClient(String applicationID, String apiKey) {
this(applicationID, apiKey, Arrays.asList(applicationID + "-1.algolia.net",
applicationID + "-2.algolia.net",
applicationID + "-3.algolia.net"));
}
/**
* Algolia Search initialization
* @param applicationID the application ID you have in your admin interface
* @param apiKey a valid API key for the service
* @param hostsArray the list of hosts that you have received for the service
*/
public APIClient(String applicationID, String apiKey, List<String> hostsArray) {
forwardRateLimitAPIKey = forwardAdminAPIKey = forwardEndUserIP = null;
if (applicationID == null || applicationID.length() == 0) {
throw new RuntimeException("AlgoliaSearch requires an applicationID.");
}
this.applicationID = applicationID;
if (apiKey == null || apiKey.length() == 0) {
throw new RuntimeException("AlgoliaSearch requires an apiKey.");
}
this.apiKey = apiKey;
if (hostsArray == null || hostsArray.size() == 0) {
throw new RuntimeException("AlgoliaSearch requires a list of hostnames.");
}
// randomize elements of hostsArray (act as a kind of load-balancer)
Collections.shuffle(hostsArray);
this.hostsArray = hostsArray;
httpClient = HttpClientBuilder.create().build();
headers = new HashMap<String, String>();
}
/**
* Allow to use IP rate limit when you have a proxy between end-user and Algolia.
* This option will set the X-Forwarded-For HTTP header with the client IP and the X-Forwarded-API-Key with the API Key having rate limits.
* @param adminAPIKey the admin API Key you can find in your dashboard
* @param endUserIP the end user IP (you can use both IPV4 or IPV6 syntax)
* @param rateLimitAPIKey the API key on which you have a rate limit
*/
public void enableRateLimitForward(String adminAPIKey, String endUserIP, String rateLimitAPIKey)
{
this.forwardAdminAPIKey = adminAPIKey;
this.forwardEndUserIP = endUserIP;
this.forwardRateLimitAPIKey = rateLimitAPIKey;
}
/**
* Disable IP rate limit enabled with enableRateLimitForward() function
*/
public void disableRateLimitForward() {
forwardAdminAPIKey = forwardEndUserIP = forwardRateLimitAPIKey = null;
}
/**
* Allow to set custom headers
*/
public void setExtraHeader(String key, String value) {
headers.put(key, value);
}
/**
* Allow to set the timeout
* @param connectTimeout connection timeout in MS
* @param readTimeout socket timeout in MS
*/
public void setTimeout(int connectTimeout, int readTimeout) {
httpSocketTimeoutMS = readTimeout;
httpConnectTimeoutMS = connectTimeout;
}
/**
* List all existing indexes
* return an JSON Object in the form:
* { "items": [ {"name": "contacts", "createdAt": "2013-01-18T15:33:13.556Z"},
* {"name": "notes", "createdAt": "2013-01-18T15:33:13.556Z"}]}
*/
public JSONObject listIndexes() throws AlgoliaException {
return getRequest("/1/indexes/");
}
/**
* Delete an index
*
* @param indexName the name of index to delete
* return an object containing a "deletedAt" attribute
*/
public JSONObject deleteIndex(String indexName) throws AlgoliaException {
try {
return deleteRequest("/1/indexes/" + URLEncoder.encode(indexName, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); // $COVERAGE-IGNORE$
}
}
/**
* Move an existing index.
* @param srcIndexName the name of index to copy.
* @param dstIndexName the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist).
*/
public JSONObject moveIndex(String srcIndexName, String dstIndexName) throws AlgoliaException {
try {
JSONObject content = new JSONObject();
content.put("operation", "move");
content.put("destination", dstIndexName);
return postRequest("/1/indexes/" + URLEncoder.encode(srcIndexName, "UTF-8") + "/operation", content.toString());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); // $COVERAGE-IGNORE$
} catch (JSONException e) {
throw new AlgoliaException(e.getMessage()); // $COVERAGE-IGNORE$
}
}
/**
* Copy an existing index.
* @param srcIndexName the name of index to copy.
* @param dstIndexName the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist).
*/
public JSONObject copyIndex(String srcIndexName, String dstIndexName) throws AlgoliaException {
try {
JSONObject content = new JSONObject();
content.put("operation", "copy");
content.put("destination", dstIndexName);
return postRequest("/1/indexes/" + URLEncoder.encode(srcIndexName, "UTF-8") + "/operation", content.toString());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); // $COVERAGE-IGNORE$
} catch (JSONException e) {
throw new AlgoliaException(e.getMessage()); // $COVERAGE-IGNORE$
}
}
public enum LogType
{
/// all query logs
LOG_QUERY,
/// all build logs
LOG_BUILD,
/// all error logs
LOG_ERROR,
/// all logs
LOG_ALL
}
/**
* Return 10 last log entries.
*/
public JSONObject getLogs() throws AlgoliaException {
return getRequest("/1/logs");
}
/**
* Return last logs entries.
* @param offset Specify the first entry to retrieve (0-based, 0 is the most recent log entry).
* @param length Specify the maximum number of entries to retrieve starting at offset. Maximum allowed value: 1000.
*/
public JSONObject getLogs(int offset, int length) throws AlgoliaException {
return getRequest("/1/logs?offset=" + offset + "&length=" + length);
}
/**
* Return last logs entries.
* @param offset Specify the first entry to retrieve (0-based, 0 is the most recent log entry).
* @param length Specify the maximum number of entries to retrieve starting at offset. Maximum allowed value: 1000.
* @param onlyErrors Retrieve only logs with an httpCode different than 200 and 201
*/
public JSONObject getLogs(int offset, int length, boolean onlyErrors) throws AlgoliaException {
return getRequest("/1/logs?offset=" + offset + "&length=" + length + "&onlyErrors=" + onlyErrors);
}
/**
* Return last logs entries.
* @param offset Specify the first entry to retrieve (0-based, 0 is the most recent log entry).
* @param length Specify the maximum number of entries to retrieve starting at offset. Maximum allowed value: 1000.
* @param logType Specify the type of log to retrieve
*/
public JSONObject getLogs(int offset, int length, LogType logType) throws AlgoliaException {
String type = null;
switch (logType) {
case LOG_BUILD:
type = "build";
break;
case LOG_QUERY:
type = "query";
break;
case LOG_ERROR:
type = "error";
break;
case LOG_ALL:
type = "all";
break;
}
return getRequest("/1/logs?offset=" + offset + "&length=" + length + "&type=" + type);
}
/**
* Get the index object initialized (no server call needed for initialization)
*
* @param indexName the name of index
*/
public Index initIndex(String indexName) {
return new Index(this, indexName);
}
/**
* List all existing user keys with their associated ACLs
*/
public JSONObject listUserKeys() throws AlgoliaException {
return getRequest("/1/keys");
}
/**
* Get ACL of a user key
*/
public JSONObject getUserKeyACL(String key) throws AlgoliaException {
return getRequest("/1/keys/" + key);
}
/**
* Delete an existing user key
*/
public JSONObject deleteUserKey(String key) throws AlgoliaException {
return deleteRequest("/1/keys/" + key);
}
/**
* Create a new user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
*/
public JSONObject addUserKey(List<String> acls) throws AlgoliaException {
JSONArray array = new JSONArray(acls);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("acl", array);
} catch (JSONException e) {
throw new RuntimeException(e); // $COVERAGE-IGNORE$
}
return postRequest("/1/keys", jsonObject.toString());
}
/**
* Update a user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
*/
public JSONObject updateUserKey(String key, List<String> acls) throws AlgoliaException {
JSONArray array = new JSONArray(acls);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("acl", array);
} catch (JSONException e) {
throw new RuntimeException(e); // $COVERAGE-IGNORE$
}
return putRequest("/1/keys/" + key, jsonObject.toString());
}
/**
* Create a new user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key)
* @param maxQueriesPerIPPerHour Specify the maximum number of API calls allowed from an IP address per hour. Defaults to 0 (no rate limit).
* @param maxHitsPerQuery Specify the maximum number of hits this API key can retrieve in one call. Defaults to 0 (unlimited)
*/
public JSONObject addUserKey(List<String> acls, int validity, int maxQueriesPerIPPerHour, int maxHitsPerQuery) throws AlgoliaException {
return addUserKey(acls, validity, maxQueriesPerIPPerHour, maxHitsPerQuery, null);
}
/**
* Update a user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key)
* @param maxQueriesPerIPPerHour Specify the maximum number of API calls allowed from an IP address per hour. Defaults to 0 (no rate limit).
* @param maxHitsPerQuery Specify the maximum number of hits this API key can retrieve in one call. Defaults to 0 (unlimited)
*/
public JSONObject updateUserKey(String key, List<String> acls, int validity, int maxQueriesPerIPPerHour, int maxHitsPerQuery) throws AlgoliaException {
return updateUserKey(key, acls, validity, maxQueriesPerIPPerHour, maxHitsPerQuery, null);
}
/**
* Create a new user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key)
* @param maxQueriesPerIPPerHour Specify the maximum number of API calls allowed from an IP address per hour. Defaults to 0 (no rate limit).
* @param maxHitsPerQuery Specify the maximum number of hits this API key can retrieve in one call. Defaults to 0 (unlimited)
* @param indexes the list of targeted indexes
*/
public JSONObject addUserKey(List<String> acls, int validity, int maxQueriesPerIPPerHour, int maxHitsPerQuery, List<String> indexes) throws AlgoliaException {
JSONArray array = new JSONArray(acls);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("acl", array);
jsonObject.put("validity", validity);
jsonObject.put("maxQueriesPerIPPerHour", maxQueriesPerIPPerHour);
jsonObject.put("maxHitsPerQuery", maxHitsPerQuery);
if (indexes != null) {
jsonObject.put("indexes", new JSONArray(indexes));
}
} catch (JSONException e) {
throw new RuntimeException(e); // $COVERAGE-IGNORE$
}
return postRequest("/1/keys", jsonObject.toString());
}
/**
* Update a user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key)
* @param maxQueriesPerIPPerHour Specify the maximum number of API calls allowed from an IP address per hour. Defaults to 0 (no rate limit).
* @param maxHitsPerQuery Specify the maximum number of hits this API key can retrieve in one call. Defaults to 0 (unlimited)
* @param indexes the list of targeted indexes
*/
public JSONObject updateUserKey(String key, List<String> acls, int validity, int maxQueriesPerIPPerHour, int maxHitsPerQuery, List<String> indexes) throws AlgoliaException {
JSONArray array = new JSONArray(acls);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("acl", array);
jsonObject.put("validity", validity);
jsonObject.put("maxQueriesPerIPPerHour", maxQueriesPerIPPerHour);
jsonObject.put("maxHitsPerQuery", maxHitsPerQuery);
if (indexes != null) {
jsonObject.put("indexes", new JSONArray(indexes));
}
} catch (JSONException e) {
throw new RuntimeException(e); // $COVERAGE-IGNORE$
}
return putRequest("/1/keys/" + key, jsonObject.toString());
}
/**
* Generate a secured and public API Key from a list of tagFilters and an
* optional user token identifying the current user
*
* @param privateApiKey your private API Key
* @param tagFilters the list of tags applied to the query (used as security)
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
public String generateSecuredApiKey(String privateApiKey, String tagFilters) throws NoSuchAlgorithmException, InvalidKeyException {
return generateSecuredApiKey(privateApiKey, tagFilters, null);
}
/**
* Generate a secured and public API Key from a query and an
* optional user token identifying the current user
*
* @param privateApiKey your private API Key
* @param query contains the parameter applied to the query (used as security)
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
public String generateSecuredApiKey(String privateApiKey, Query query) throws NoSuchAlgorithmException, InvalidKeyException {
return generateSecuredApiKey(privateApiKey, query.toString(), null);
}
/**
* Generate a secured and public API Key from a list of tagFilters and an
* optional user token identifying the current user
*
* @param privateApiKey your private API Key
* @param tagFilters the list of tags applied to the query (used as security)
* @param userToken an optional token identifying the current user
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
public String generateSecuredApiKey(String privateApiKey, String tagFilters, String userToken) throws NoSuchAlgorithmException, InvalidKeyException {
return hmac(privateApiKey, tagFilters + (userToken != null ? userToken : ""));
}
/**
* Generate a secured and public API Key from a query and an
* optional user token identifying the current user
*
* @param privateApiKey your private API Key
* @param query contains the parameter applied to the query (used as security)
* @param userToken an optional token identifying the current user
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
public String generateSecuredApiKey(String privateApiKey, Query query, String userToken) throws NoSuchAlgorithmException, InvalidKeyException {
return hmac(privateApiKey, query.toString() + (userToken != null ? userToken : ""));
}
static String hmac(String key, String msg) {
Mac hmac;
try {
hmac = Mac.getInstance("HmacSHA256");
} catch (NoSuchAlgorithmException e) {
throw new Error(e);
}
try {
hmac.init(new SecretKeySpec(key.getBytes(), "HmacSHA256"));
} catch (InvalidKeyException e) {
throw new Error(e);
}
byte[] rawHmac = hmac.doFinal(msg.getBytes());
byte[] hexBytes = new Hex().encode(rawHmac);
return new String(hexBytes);
}
private static enum Method {
GET, POST, PUT, DELETE, OPTIONS, TRACE, HEAD;
}
protected JSONObject getRequest(String url) throws AlgoliaException {
return _request(Method.GET, url, null);
}
protected JSONObject deleteRequest(String url) throws AlgoliaException {
return _request(Method.DELETE, url, null);
}
protected JSONObject postRequest(String url, String obj) throws AlgoliaException {
return _request(Method.POST, url, obj);
}
protected JSONObject putRequest(String url, String obj) throws AlgoliaException {
return _request(Method.PUT, url, obj);
}
private JSONObject _request(Method m, String url, String json) throws AlgoliaException {
HttpRequestBase req;
switch (m) {
case DELETE:
req = new HttpDelete();
break;
case GET:
req = new HttpGet();
break;
case POST:
req = new HttpPost();
break;
case PUT:
req = new HttpPut();
break;
default:
throw new IllegalArgumentException("Method " + m + " is not supported");
}
HashMap<String, String> errors = new HashMap<String, String>();
// for each host
for (String host : this.hostsArray) {
req.reset();
// set URL
try {
req.setURI(new URI("https://" + host + url));
} catch (URISyntaxException e) {
// never reached
throw new IllegalStateException(e);
}
// set auth headers
req.setHeader("X-Algolia-Application-Id", this.applicationID);
if (forwardAdminAPIKey == null) {
req.setHeader("X-Algolia-API-Key", this.apiKey);
} else {
req.setHeader("X-Algolia-API-Key", this.forwardAdminAPIKey);
req.setHeader("X-Forwarded-For", this.forwardEndUserIP);
req.setHeader("X-Forwarded-API-Key", this.forwardRateLimitAPIKey);
}
for (Entry<String, String> entry : headers.entrySet()) {
req.setHeader(entry.getKey(), entry.getValue());
}
// set user agent
req.setHeader("User-Agent", "Algolia for Java " + version);
// set JSON entity
if (json != null) {
if (!(req instanceof HttpEntityEnclosingRequestBase)) {
throw new IllegalArgumentException("Method " + m + " cannot enclose entity");
}
req.setHeader("Content-type", "application/json");
try {
StringEntity se = new StringEntity(json, "UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
((HttpEntityEnclosingRequestBase) req).setEntity(se);
} catch (UnsupportedEncodingException e) {
throw new AlgoliaException("Invalid JSON Object: " + json); // $COVERAGE-IGNORE$
}
}
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(httpSocketTimeoutMS)
.setConnectTimeout(httpConnectTimeoutMS)
.setConnectionRequestTimeout(httpConnectTimeoutMS)
.build();
req.setConfig(config);
HttpResponse response;
try {
response = httpClient.execute(req);
} catch (IOException e) {
// on error continue on the next host
errors.put(host, String.format("%s=%s", e.getClass().getName(), e.getMessage()));
continue;
}
try {
int code = response.getStatusLine().getStatusCode();
if (code == 200 || code == 201) {
} else if (code == 400) {
EntityUtils.consumeQuietly(response.getEntity());
throw new AlgoliaException(400, "Bad request");
} else if (code == 403) {
EntityUtils.consumeQuietly(response.getEntity());
throw new AlgoliaException(403, "Invalid Application-ID or API-Key");
} else if (code == 404) {
EntityUtils.consumeQuietly(response.getEntity());
throw new AlgoliaException(404, "Resource does not exist");
} else {
try {
errors.put(host, EntityUtils.toString(response.getEntity()));
} catch (IOException e) {
errors.put(host, String.valueOf(code));
}
EntityUtils.consumeQuietly(response.getEntity());
// KO, continue
continue;
}
try {
InputStream istream = response.getEntity().getContent();
InputStreamReader is = new InputStreamReader(istream, "UTF-8");
JSONTokener tokener = new JSONTokener(is);
JSONObject res = new JSONObject(tokener);
is.close();
return res;
} catch (IOException e) {
continue;
} catch (JSONException e) {
//System.out.println(response.getEntity().getContent().read);
throw new AlgoliaException("JSON decode error:" + e.getMessage());
}
} finally {
req.releaseConnection();
}
}
StringBuilder builder = new StringBuilder("Hosts unreachable: ");
Boolean first = true;
for (Map.Entry<String, String> entry : errors.entrySet()) {
if (!first) {
builder.append(", ");
}
builder.append(entry.toString());
first = false;
}
throw new AlgoliaException(builder.toString());
}
static public class IndexQuery {
private String index;
private Query query;
public IndexQuery(String index, Query q) {
this.index = index;
this.query = q;
}
public String getIndex() {
return index;
}
public void setIndex(String index) {
this.index = index;
}
public Query getQuery() {
return query;
}
public void setQuery(Query query) {
this.query = query;
}
}
/**
* This method allows to query multiple indexes with one API call
*/
public JSONObject multipleQueries(List<IndexQuery> queries) throws AlgoliaException {
try {
JSONArray requests = new JSONArray();
for (IndexQuery indexQuery : queries) {
String paramsString = indexQuery.getQuery().getQueryString();
requests.put(new JSONObject().put("indexName", indexQuery.getIndex()).put("params", paramsString));
}
JSONObject body = new JSONObject().put("requests", requests);
return postRequest("/1/indexes/*/queries", body.toString());
} catch (JSONException e) {
new AlgoliaException(e.getMessage());
}
return null;
}
}
|
package com.atexpose.api;
import com.atexpose.api.datatypes.AbstractDataType;
import io.schinzel.basicutils.Checker;
import lombok.Builder;
import lombok.Getter;
import java.util.List;
class RequestArguments {
/** The request argument values as object. */
@Getter private final Object[] mArgumentValuesAsObjects;
@Builder
RequestArguments(MethodArguments methodArguments, List<String> argumentValuesAsStrings, List<String> argumentNames) {
Object[] argumentValuesAsObjects = castArgumentValuesToUse(methodArguments, argumentValuesAsStrings, argumentNames);
mArgumentValuesAsObjects = setDefaultArgumentValues(methodArguments, argumentValuesAsObjects, argumentNames);
}
private static Object[] castArgumentValuesToUse(MethodArguments methodArguments, List<String> argumentValuesAsStrings, List<String> argumentNames) {
Object[] argumentValuesAsObjects = null;
if (argumentValuesAsStrings != null && argumentValuesAsStrings.size() > 0) {
argumentValuesAsObjects = new Object[argumentValuesAsStrings.size()];
for (int i = 0; i < argumentValuesAsStrings.size(); i++) {
AbstractDataType dataType = Checker.isEmpty(argumentNames)
? methodArguments.getArgument(i).getDataType()
: methodArguments.getArgument(argumentNames.get(i)).getDataType();
argumentValuesAsObjects[i] = dataType.convertFromStringToDataType(argumentValuesAsStrings.get(i));
}
}
return argumentValuesAsObjects;
}
private static Object[] setDefaultArgumentValues(MethodArguments methodArguments, Object[] requestArgumentValues, List<String> requestArgumentNames) {
// Get a copy of the argument values
Object[] argumentValues = methodArguments.getCopyOfArgumentDefaultValues();
// If no argument names were supplied
if (Checker.isEmpty(requestArgumentNames)) {
// If argument values where supplied
if (requestArgumentValues != null) {
//Overwrite the default argument values with the a many argument values as were present in the request
System.arraycopy(requestArgumentValues, 0, argumentValues, 0, requestArgumentValues.length);
}
}// else, i.e. argument names were supplied
else {
// Get the argument positions
int[] argumentPositions = methodArguments.getArgumentPositions(requestArgumentNames);
Object inputArgumentValue;
int positionInputArgument;
// Go through the arguments array as set values
for (int i = 0; i < requestArgumentNames.size(); i++) {
positionInputArgument = argumentPositions[i];
inputArgumentValue = requestArgumentValues[i];
argumentValues[positionInputArgument] = inputArgumentValue;
}
}
return argumentValues;
}
}
|
package com.backblaze.erasure;
/**
* Reed-Solomon Coding over 8-bit values.
*/
public class ReedSolomon {
private final int dataShardCount;
private final int parityShardCount;
private final int totalShardCount;
private final Matrix matrix;
private final CodingLoop codingLoop;
/**
* Rows from the matrix for encoding parity, each one as its own
* byte array to allow for efficient access while encoding.
*/
private final byte [] [] parityRows;
/**
* Creates a ReedSolomon codec with the default coding loop.
*/
public static ReedSolomon create(int dataShardCount, int parityShardCount) {
return new ReedSolomon(dataShardCount, parityShardCount, new InputOutputByteTableCodingLoop());
}
/**
* Initializes a new encoder/decoder, with a chosen coding loop.
*/
public ReedSolomon(int dataShardCount, int parityShardCount, CodingLoop codingLoop) {
// We can have at most 256 shards total, as any more would
// lead to duplicate rows in the Vandermonde matrix, which
// would then lead to duplicate rows in the built matrix
// below. Then any subset of the rows containing the duplicate
// rows would be singular.
if (256 < dataShardCount + parityShardCount) {
throw new IllegalArgumentException("too many shards - max is 256");
}
this.dataShardCount = dataShardCount;
this.parityShardCount = parityShardCount;
this.codingLoop = codingLoop;
this.totalShardCount = dataShardCount + parityShardCount;
matrix = buildMatrix(dataShardCount, this.totalShardCount);
parityRows = new byte [parityShardCount] [];
for (int i = 0; i < parityShardCount; i++) {
parityRows[i] = matrix.getRow(dataShardCount + i);
}
}
/**
* Returns the number of data shards.
*/
public int getDataShardCount() {
return dataShardCount;
}
/**
* Returns the number of parity shards.
*/
public int getParityShardCount() {
return parityShardCount;
}
/**
* Returns the total number of shards.
*/
public int getTotalShardCount() {
return totalShardCount;
}
/**
* Encodes parity for a set of data shards.
*
* @param shards An array containing data shards followed by parity shards.
* Each shard is a byte array, and they must all be the same
* size.
* @param offset The index of the first byte in each shard to encode.
* @param byteCount The number of bytes to encode in each shard.
*
*/
public void encodeParity(byte[][] shards, int offset, int byteCount) {
// Check arguments.
checkBuffersAndSizes(shards, offset, byteCount);
// Build the array of output buffers.
byte [] [] outputs = new byte [parityShardCount] [];
System.arraycopy(shards, dataShardCount, outputs, 0, parityShardCount);
// Do the coding.
codingLoop.codeSomeShards(
parityRows,
shards, dataShardCount,
outputs, parityShardCount,
offset, byteCount);
}
/**
* Returns true if the parity shards contain the right data.
*
* @param shards An array containing data shards followed by parity shards.
* Each shard is a byte array, and they must all be the same
* size.
* @param firstByte The index of the first byte in each shard to check.
* @param byteCount The number of bytes to check in each shard.
*/
public boolean isParityCorrect(byte[][] shards, int firstByte, int byteCount) {
// Check arguments.
checkBuffersAndSizes(shards, firstByte, byteCount);
// Build the array of buffers being checked.
byte [] [] toCheck = new byte [parityShardCount] [];
System.arraycopy(shards, dataShardCount, toCheck, 0, parityShardCount);
// Do the checking.
return codingLoop.checkSomeShards(
parityRows,
shards, dataShardCount,
toCheck, parityShardCount,
firstByte, byteCount,
null);
}
/**
* Returns true if the parity shards contain the right data.
*
* This method may be significantly faster than the one above that does
* not use a temporary buffer.
*
* @param shards An array containing data shards followed by parity shards.
* Each shard is a byte array, and they must all be the same
* size.
* @param firstByte The index of the first byte in each shard to check.
* @param byteCount The number of bytes to check in each shard.
* @param tempBuffer A temporary buffer (the same size as each of the
* shards) to use when computing parity.
*/
public boolean isParityCorrect(byte[][] shards, int firstByte, int byteCount, byte [] tempBuffer) {
// Check arguments.
checkBuffersAndSizes(shards, firstByte, byteCount);
if (tempBuffer.length < firstByte + byteCount) {
throw new IllegalArgumentException("tempBuffer is not big enough");
}
// Build the array of buffers being checked.
byte [] [] toCheck = new byte [parityShardCount] [];
System.arraycopy(shards, dataShardCount, toCheck, 0, parityShardCount);
// Do the checking.
return codingLoop.checkSomeShards(
parityRows,
shards, dataShardCount,
toCheck, parityShardCount,
firstByte, byteCount,
tempBuffer);
}
/**
* Given a list of shards, some of which contain data, fills in the
* ones that don't have data.
*
* Quickly does nothing if all of the shards are present.
*
* If any shards are missing (based on the flags in shardsPresent),
* the data in those shards is recomputed and filled in.
*/
public void decodeMissing(byte [] [] shards,
boolean [] shardPresent,
final int offset,
final int byteCount) {
// Check arguments.
checkBuffersAndSizes(shards, offset, byteCount);
// Quick check: are all of the shards present? If so, there's
// nothing to do.
int numberPresent = 0;
for (int i = 0; i < totalShardCount; i++) {
if (shardPresent[i]) {
numberPresent += 1;
}
}
if (numberPresent == totalShardCount) {
// Cool. All of the shards data data. We don't
// need to do anything.
return;
}
// More complete sanity check
if (numberPresent < dataShardCount) {
throw new IllegalArgumentException("Not enough shards present");
}
// Pull out the rows of the matrix that correspond to the
// shards that we have and build a square matrix. This
// matrix could be used to generate the shards that we have
// from the original data.
// Also, pull out an array holding just the shards that
// correspond to the rows of the submatrix. These shards
// will be the input to the decoding process that re-creates
// the missing data shards.
Matrix subMatrix = new Matrix(dataShardCount, dataShardCount);
byte [] [] subShards = new byte [dataShardCount] [];
{
int subMatrixRow = 0;
for (int matrixRow = 0; matrixRow < totalShardCount && subMatrixRow < dataShardCount; matrixRow++) {
if (shardPresent[matrixRow]) {
for (int c = 0; c < dataShardCount; c++) {
subMatrix.set(subMatrixRow, c, matrix.get(matrixRow, c));
}
subShards[subMatrixRow] = shards[matrixRow];
subMatrixRow += 1;
}
}
}
// Invert the matrix, so we can go from the encoded shards
// back to the original data. Then pull out the row that
// generates the shard that we want to decode. Note that
// since this matrix maps back to the orginal data, it can
// be used to create a data shard, but not a parity shard.
Matrix dataDecodeMatrix = subMatrix.invert();
// Re-create any data shards that were missing.
// The input to the coding is all of the shards we actually
// have, and the output is the missing data shards. The computation
// is done using the special decode matrix we just built.
byte [] [] outputs = new byte [parityShardCount] [];
byte [] [] matrixRows = new byte [parityShardCount] [];
int outputCount = 0;
for (int iShard = 0; iShard < dataShardCount; iShard++) {
if (!shardPresent[iShard]) {
outputs[outputCount] = shards[iShard];
matrixRows[outputCount] = dataDecodeMatrix.getRow(iShard);
outputCount += 1;
}
}
codingLoop.codeSomeShards(
matrixRows,
subShards, dataShardCount,
outputs, outputCount,
offset, byteCount);
// Now that we have all of the data shards intact, we can
// compute any of the parity that is missing.
// The input to the coding is ALL of the data shards, including
// any that we just calculated. The output is whichever of the
// data shards were missing.
outputCount = 0;
for (int iShard = dataShardCount; iShard < totalShardCount; iShard++) {
if (!shardPresent[iShard]) {
outputs[outputCount] = shards[iShard];
matrixRows[outputCount] = parityRows[iShard - dataShardCount];
outputCount += 1;
}
}
codingLoop.codeSomeShards(
matrixRows,
shards, dataShardCount,
outputs, outputCount,
offset, byteCount);
}
/**
* Checks the consistency of arguments passed to public methods.
*/
private void checkBuffersAndSizes(byte [] [] shards, int offset, int byteCount) {
// The number of buffers should be equal to the number of
// data shards plus the number of parity shards.
if (shards.length != totalShardCount) {
throw new IllegalArgumentException("wrong number of shards: " + shards.length);
}
// All of the shard buffers should be the same length.
int shardLength = shards[0].length;
for (int i = 1; i < shards.length; i++) {
if (shards[i].length != shardLength) {
throw new IllegalArgumentException("Shards are different sizes");
}
}
// The offset and byteCount must be non-negative and fit in the buffers.
if (offset < 0) {
throw new IllegalArgumentException("offset is negative: " + offset);
}
if (byteCount < 0) {
throw new IllegalArgumentException("byteCount is negative: " + byteCount);
}
if (shardLength < offset + byteCount) {
throw new IllegalArgumentException("buffers to small: " + byteCount + offset);
}
}
/**
* Create the matrix to use for encoding, given the number of
* data shards and the number of total shards.
*
* The top square of the matrix is guaranteed to be an identity
* matrix, which means that the data shards are unchanged after
* encoding.
*/
private static Matrix buildMatrix(int dataShards, int totalShards) {
// Start with a Vandermonde matrix. This matrix would work,
// in theory, but doesn't have the property that the data
// shards are unchanged after encoding.
Matrix vandermonde = vandermonde(totalShards, dataShards);
// Multiple by the inverse of the top square of the matrix.
// This will make the top square be the identity matrix, but
// preserve the property that any square subset of rows is
// invertible.
Matrix top = vandermonde.submatrix(0, 0, dataShards, dataShards);
return vandermonde.times(top.invert());
}
/**
* Create a Vandermonde matrix, which is guaranteed to have the
* property that any subset of rows that forms a square matrix
* is invertible.
*
* @param rows Number of rows in the result.
* @param cols Number of columns in the result.
* @return A Matrix.
*/
private static Matrix vandermonde(int rows, int cols) {
Matrix result = new Matrix(rows, cols);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
result.set(r, c, Galois.exp((byte) r, c));
}
}
return result;
}
}
|
package com.badlogic.gdx.utils;
import java.util.*;
import java.util.function.*;
/**
* Array utility functions.
* <p>
* Note: The functions to modify arrays are mostly written for convenience, not for efficiency. They should not be
* used in code sensitive to memory consumption or execution speed.
*/
public class ArrayUtils {
/**
* Convenience function to iterate an array.
*/
public static <T> void forEach(T[] array, Consumer<T> action) {
for (T t : array) {
action.accept(t);
}
}
/**
* Convenience function to iterate an array. Stops if user-supplied function returns False.
*/
public static <T> void forEachWhile(T[] array, Function<T, Boolean> action) {
for (T t : array) {
if (!action.apply(t)) {
break;
}
}
}
/**
* Iterates the array, and returns the first item which fulfills the user-defined comparison.
* <p>
* Returns null if no match is found.
*/
public static <T> T find(T[] array, Function<T, Boolean> match) {
for (T t : array) {
if (match.apply(t)) {
return t;
}
}
return null;
}
/**
* Iterates the array, and returns the index of the first item which fulfills the user-defined comparison.
* <p>
* Returns -1 if no match is found.
*/
public static <T> int findIndex(T[] array, Function<T, Boolean> match) {
for (int i = 0; i < array.length; i++) {
if (match.apply(array[i])) {
return i;
}
}
return -1;
}
/**
* Iterates the array, consuming items only which fulfill the user-defined comparison.
*/
public static <T> void findAll(T[] array, Function<T, Boolean> match, Consumer<T> action) {
for (T t : array) {
if (match.apply(t)) {
action.accept(t);
}
}
}
/**
* Appends an element to a copy of the given array.
*/
public static <T> T[] append(T[] array, T element) {
int len = array.length;
array = Arrays.copyOf(array, len + 1);
array[len] = element;
return array;
}
/**
* Returns a copy of the given array, with the element at the given index removed.
* <p>
* This version moves the last array element to the removed element's position.
*/
public static <T> T[] removeIndex(T[] array, int index) {
return removeIndex(array, index, false);
}
/**
* Returns a copy of the given array, with the element at the given index removed.
*/
public static <T> T[] removeIndex(T[] array, int index, boolean keepOrder) {
if (index != array.length - 1) {
if (keepOrder) {
System.arraycopy(array, index + 1, array, index, array.length - 2 - index);
} else {
array[index] = array[array.length - 1];
}
}
return Arrays.copyOf(array, array.length - 1);
}
/**
* Expands an existing two-dimensional array.
* <p>
* This is a very memory-inefficient operation.
*/
@SuppressWarnings("unchecked")
public static <T> T[][] expand(T[][] arrayOfArray, Class<T> clazz,
int lowerDim0, int upperDim0, int lowerDim1, int upperDim1) {
int columns = arrayOfArray.length + lowerDim0 + upperDim0;
int rows = arrayOfArray[0].length + lowerDim1 + upperDim1;
Object copy = java.lang.reflect.Array.newInstance(clazz, columns, rows);
T[][] dest = (T[][]) copy;
for (int i = lowerDim0; i < columns - upperDim0; i++) {
for (int j = lowerDim1; j < rows - upperDim1; j++) {
dest[i][j] = arrayOfArray[i - lowerDim0][j - lowerDim1];
}
}
return dest;
}
/**
* Combined check for null or empty array.
*/
public static <T> boolean isNullOrEmpty(T[] array) {
return array == null || array.length == 0;
}
/**
* Returns an {@link Iterable} interface wrapped around an array, in ascending order.
*/
public static <T> Iterable<T> asIterable(T[] array) {
return asIterable(array, false);
}
/**
* Returns an {@link Iterable} interface wrapped around an array, in ascending or descending order.
*
* <pre>
* {@code
* Object[] someArray = ...;
* ArrayUtils.asIterable(someArray, false).forEach(element -> {});
* }
* </pre>
*/
public static <T> Iterable<T> asIterable(T[] array, boolean descending) {
return () -> descending ? new DescendingArrayIterator<>(array) : new ArrayIterator<>(array);
}
/**
* Returns a second interface to the {@link Iterable} passed, in ascending order.
*/
@SuppressWarnings("unchecked")
public static <T> Iterable<T> asIterable(Iterable<T> iterable) {
return asIterable(iterable, false);
}
/**
* Returns a second interface to the {@link Iterable} passed.
* <p>
* The argument must be the result of a previous call to this function, or to
* {@link ArrayUtils#asIterable(Object[], boolean)}.
*/
@SuppressWarnings("unchecked")
public static <T> Iterable<T> asIterable(Iterable<T> iterable, boolean descending) {
if (iterable instanceof ArrayIterator<?>) {
return () -> descending
? new DescendingArrayIterator<>((AbstractArrayIterator<T>) iterable)
: new ArrayIterator<>((AbstractArrayIterator<T>) iterable);
}
throw new IllegalArgumentException("Iterable must be of equal type.");
}
private abstract static class AbstractArrayIterator<T> implements Iterator<T> {
protected final T[] array;
protected int index = 0;
AbstractArrayIterator(T[] array) {
this.array = array;
}
}
private static class ArrayIterator<T> extends AbstractArrayIterator<T> {
ArrayIterator(T[] array) {
super(array);
}
ArrayIterator(AbstractArrayIterator<T> other) {
super(other.array);
}
@Override
public boolean hasNext() {
return index < array.length;
}
@Override
public T next() {
return array[index++];
}
}
private static class DescendingArrayIterator<T> extends AbstractArrayIterator<T> {
DescendingArrayIterator(T[] array) {
super(array);
index = array.length - 1;
}
DescendingArrayIterator(AbstractArrayIterator<T> other) {
super(other.array);
index = other.array.length - 1;
}
@Override
public boolean hasNext() {
return index >= 0;
}
@Override
public T next() {
return array[index
}
}
/**
* Returns a {@link Collection} interface wrapped around an array.
* <p>
* The collection returned does not support any operation manipulating the array. Its main purpose (and
* difference to {@link ArrayUtils#asIterable(Object[])}) is to expose the {@link Collection#size()} function.
*/
public static <T> Collection<T> asCollection(T[] array) {
return new ArrayCollection<>(array);
}
/**
* Returns a second interface to the {@link Collection} passed.
* <p>
* The argument must be the result of a previous call to this function, or to
* {@link ArrayUtils#asCollection(Object[])}.
*/
public static <T> Collection<T> asCollection(Collection<T> collection) {
if (collection instanceof ArrayCollection<?>) {
return new ArrayCollection<>((ArrayCollection<T>) collection);
}
throw new IllegalArgumentException("Collection must be of equal type.");
}
private static class ArrayCollection<T> extends AbstractCollection<T> {
private final T[] array;
ArrayCollection(T[] array) {
this.array = array;
}
ArrayCollection(ArrayCollection<T> other) {
this.array = other.array;
}
@Override
public Iterator<T> iterator() {
return new ArrayIterator<>(array);
}
@Override
public int size() {
return array.length;
}
}
}
|
package com.brewerydb.api;
import com.brewerydb.api.config.Configuration;
import com.brewerydb.api.exception.BreweryDBException;
import com.brewerydb.api.exception.MissingApiKeyException;
import com.brewerydb.api.request.ApiRequest;
import com.brewerydb.api.request.beer.AddBeerRequest;
import com.brewerydb.api.request.beer.GetBeerRequest;
import com.brewerydb.api.request.beer.GetBeersRequest;
import com.brewerydb.api.request.beer.UpdateBeerRequest;
import com.brewerydb.api.request.brewery.GetBreweriesRequest;
import com.brewerydb.api.request.brewery.GetBreweryRequest;
import com.brewerydb.api.request.feature.GetFeaturesRequest;
import com.brewerydb.api.result.GetRandomBeerResult;
import com.brewerydb.api.result.Result;
import com.brewerydb.api.result.beer.AddBeerResult;
import com.brewerydb.api.result.beer.DeleteBeerResult;
import com.brewerydb.api.result.beer.GetBeerResult;
import com.brewerydb.api.result.beer.GetBeersResult;
import com.brewerydb.api.result.beer.UpdateBeerResult;
import com.brewerydb.api.result.brewery.GetBreweriesResult;
import com.brewerydb.api.result.brewery.GetBreweryResult;
import com.brewerydb.api.result.feature.FeaturedResult;
import com.brewerydb.api.result.feature.FeaturesResult;
import com.google.gson.Gson;
import com.ning.http.client.AsyncCompletionHandler;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.Request;
import com.ning.http.client.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class BreweryDBClient {
private static final Logger LOGGER = LoggerFactory.getLogger(BreweryDBClient.class);
private static final String RATELIMIT_REMAINING_HEADER = "X-Ratelimit-Remaining";
private final String apiKey;
private final Gson gson = new Gson();
/**
* Constructor for {@link BreweryDBClient}.
*
* @param apiKey The API key provided by BreweryDB.
*/
public BreweryDBClient(String apiKey) {
if (apiKey == null || apiKey.trim().equals("")) {
throw new MissingApiKeyException("An API key is required to call the BreweryDB API. Obtain your key at http:
}
this.apiKey = apiKey;
}
/**
* Returns a list of beers matching a criteria.
*
* @param request The request parameters for this call.
* @return {@link GetBeersResult} - The {@link Result} containing a list of beers.
*/
public GetBeersResult getBeers(GetBeersRequest request) {
return waitFor(getBeersAsync(request));
}
/**
* The asynchronous version of {@link #getBeers(GetBeersRequest)}.
*/
public Future<GetBeersResult> getBeersAsync(GetBeersRequest request) {
return requestAsync(RequestMethod.GET, Configuration.BEERS_ENDPOINT, request, GetBeersResult.class);
}
/**
* Returns a single beer by its ID.
*
* @param id The ID of the beer to retrieve.
* @return {@link GetBeerResult} - The {@link Result} containing the beer.
*/
public GetBeerResult getBeer(String id) {
return waitFor(getBeerAsync(id));
}
/**
* The asynchronous version of {@link #getBeer(String)}.
*/
public Future<GetBeerResult> getBeerAsync(String id) {
return getBeerAsync(id, null);
}
/**
* Returns a single beer by its ID and request parameters.
*
* @param id The ID of the beer to retrieve.
* @param request The request parameters for this call.
* @return {@link GetBeerResult} - The {@link Result} containing the beer.
*/
public GetBeerResult getBeer(String id, GetBeerRequest request) {
return waitFor(getBeerAsync(id, request));
}
/**
* The asynchronous version of {@link #getBeer(String, GetBeerRequest)}.
*/
public Future<GetBeerResult> getBeerAsync(String id, GetBeerRequest request) {
if (id == null) {
throw new IllegalArgumentException("ID parameter is required to retrieve a beer.");
}
return requestAsync(RequestMethod.GET, Configuration.BEER_ENDPOINT + "/" + id, request, GetBeerResult.class);
}
/**
* Requests a new beer to be created in the API.
*
* @param request The request parameters for this call.
* @return {@link AddBeerResult} - The {@link Result} containing the message response from the API.
*/
public AddBeerResult addBeer(AddBeerRequest request) {
return waitFor(addBeerAsync(request));
}
/**
* The asynchronous version of {@link #addBeer(AddBeerRequest)}.
*/
public Future<AddBeerResult> addBeerAsync(AddBeerRequest request) {
if (request == null) {
throw new IllegalArgumentException("Request parameter is required to add a beer.");
}
return requestAsync(RequestMethod.POST, Configuration.BEERS_ENDPOINT, request, AddBeerResult.class);
}
/**
* Requests that a beer's properties be updated in the API.
*
* @param id The ID of the beer to update.
* @param request The request parameters for this call.
* @return {@link UpdateBeerResult} - The {@link Result} containing the message response from the API.
*/
public UpdateBeerResult updateBeer(String id, UpdateBeerRequest request) {
return waitFor(updateBeerAsync(id, request));
}
/**
* The asynchronous version of {@link #updateBeer(String, UpdateBeerRequest)}.
*/
public Future<UpdateBeerResult> updateBeerAsync(String id, UpdateBeerRequest request) {
if (id == null) {
throw new IllegalArgumentException("ID parameter is required to update a beer.");
}
return requestAsync(RequestMethod.PUT, Configuration.BEER_ENDPOINT + "/" + id, request, UpdateBeerResult.class);
}
/**
* Requests that a beer be deleted from the API.
*
* @param id The ID of the beer to request deletion for.
* @return {@link DeleteBeerResult} - The {@link Result} containing the message response from the API.
*/
public DeleteBeerResult deleteBeer(String id) {
return waitFor(deleteBeerAsync(id));
}
/**
* The asynchronous version of {@link ##deleteBeer(String)}.
*/
public Future<DeleteBeerResult> deleteBeerAsync(String id) {
if (id == null) {
throw new IllegalArgumentException("ID parameter is required to delete a beer.");
}
return requestAsync(RequestMethod.DELETE, Configuration.BEER_ENDPOINT + "/" + id, null, DeleteBeerResult.class);
}
/**
* Returns a random beer.
*
* @return {@link GetRandomBeerResult} - The {@link Result} containing a random beer.
*/
public GetRandomBeerResult getRandomBeer() {
return waitFor(getRandomBeerAsync());
}
/**
* The asynchronous version of {@link #getRandomBeer()}.
*/
public Future<GetRandomBeerResult> getRandomBeerAsync() {
return requestAsync(RequestMethod.GET, Configuration.RANDOM_BEER_ENDPOINT, null, GetRandomBeerResult.class);
}
/**
* Returns a list of breweries.
*
* @param request The request parameters for this call.
* @return {@link GetBreweriesResult} - The {@link Result} containing the list of breweries.
*/
public GetBreweriesResult getBreweries(GetBreweriesRequest request) {
return waitFor(getBreweriesAsync(request));
}
/**
* The asynchronous version of {@link #getBreweries(GetBreweriesRequest)}.
*/
public Future<GetBreweriesResult> getBreweriesAsync(GetBreweriesRequest query) {
return requestAsync(RequestMethod.GET, Configuration.BREWERIES_ENDPOINT, query, GetBreweriesResult.class);
}
/**
* Returns a single brewery by ID.
*
* @param id The ID of the brewery to retrieve.
* @return {@link GetBreweryResult} - The {@link Result} containing the single brewery.
*/
public GetBreweryResult getBrewery(String id) {
return waitFor(getBreweryAsync(id));
}
/**
* The asynchronous version of {@link #getBrewery(String)}.
*/
public Future<GetBreweryResult> getBreweryAsync(String id) {
return getBreweryAsync(id, null);
}
/**
* Returns a brewery based on ID and other parameters.
*
* @param id The ID of the brewery.
* @param request The request parameters.
* @return {@link GetBreweryRequest} - The {@link Result} containing the single brewery.
*/
public GetBreweryResult getBrewery(String id, GetBreweryRequest request) {
return waitFor(getBreweryAsync(id, request));
}
/**
* The asynchronous version of {@link #getBrewery(String, GetBreweryRequest)}.
*/
public Future<GetBreweryResult> getBreweryAsync(String id, GetBreweryRequest query) {
if (id == null) {
throw new IllegalArgumentException("ID parameter is required to retrieve a brewery.");
}
return requestAsync(RequestMethod.GET, Configuration.BREWERY_ENDPOINT + "/" + id, query, GetBreweryResult.class);
}
/**
* Returns the current featured beer and brewery.
*
* @return {@link FeaturedResult} - The {@link Result} containing the featured brewery and beer.
*/
public FeaturedResult getFeatured() {
return waitFor(getFeaturedAsync());
}
/**
* The asynchronous version of {@link #getFeatured()}.
*/
public Future<FeaturedResult> getFeaturedAsync() {
return requestAsync(RequestMethod.GET, Configuration.FEATURED_ENDPOINT, null, FeaturedResult.class);
}
/**
* Returns a list of all features.
*
* @return {@link FeaturesResult} - The {@link Result} containing all features.
*/
public FeaturesResult getFeatures() {
return waitFor(getFeaturesAsync());
}
/**
* The asynchronous version of {@link #getFeatures()}.
*/
public Future<FeaturesResult> getFeaturesAsync() {
return getFeaturesAsync(null);
}
/**
* Returns a list of all features with filtering.
*
* @param query The parameters to filter by.
* @return {@link FeaturesResult} - The {@link Result} containing all matching features.
*/
public FeaturesResult getFeatures(GetFeaturesRequest query) {
return waitFor(getFeaturesAsync(query));
}
/**
* The asynchronous version of {@link #getFeatures(GetFeaturesRequest)}.
*/
public Future<FeaturesResult> getFeaturesAsync(GetFeaturesRequest query) {
return requestAsync(RequestMethod.GET, Configuration.FEATURES_ENDPOINT, query, FeaturesResult.class);
}
private enum RequestMethod {
GET, POST, PUT, DELETE;
}
private <T> T waitFor(Future<T> future) {
try {
return future.get();
} catch (InterruptedException e) {
throw new BreweryDBException(e.getMessage());
} catch (ExecutionException e) {
throw new BreweryDBException(e.getMessage());
}
}
private <T extends Result> Future<T> requestAsync(final RequestMethod method, final String endpoint, final ApiRequest request, final Class<T> clazz) {
AsyncHttpClient client = new AsyncHttpClient();
AsyncHttpClient.BoundRequestBuilder builder;
switch (method) {
case GET:
builder = client.prepareGet(endpoint);
break;
case POST:
builder = client.preparePost(endpoint);
break;
case PUT:
builder = client.preparePut(endpoint);
break;
case DELETE:
builder = client.prepareDelete(endpoint);
break;
default:
throw new IllegalStateException(method.name() + " has not been implemented");
}
addCommonParameters(builder);
if (method == RequestMethod.GET) {
if (request != null) {
for (String key : request.getParams().keySet()) {
String value = request.getParams().get(key);
LOGGER.debug("Adding request parameter: {}={}", key, value);
builder.addQueryParam(key, value);
}
}
} else if (method == RequestMethod.POST || method == RequestMethod.PUT) {
if (request != null) {
for (String key : request.getParams().keySet()) {
String value = request.getParams().get(key);
LOGGER.debug("Adding form parameter: {}={}", key, value);
builder.addFormParam(key, value);
}
}
}
LOGGER.debug("Performing {} request to endpoint {}", method.name(), endpoint);
return performRequestAsync(client, builder.build(), clazz);
}
protected <T extends Result> Future<T> performRequestAsync(AsyncHttpClient client, Request request, final Class<T> clazz) {
return client.executeRequest(request, new AsyncCompletionHandler<T>() {
@Override
public T onCompleted(Response response) throws Exception {
LOGGER.debug("Rate limit remaining: {}" + response.getHeader(RATELIMIT_REMAINING_HEADER));
T result = gson.fromJson(response.getContentType(), clazz);
validateResult(result);
return result;
}
});
}
private void addCommonParameters(AsyncHttpClient.BoundRequestBuilder builder) {
builder
.setFollowRedirects(true)
.addQueryParam("key", apiKey)
.addQueryParam("format", "json");
}
protected <T extends Result> void validateResult(T result) {
if (!result.wasSuccessful()) {
throw new BreweryDBException(result.getErrorMessage());
}
}
}
|
package com.deathrayresearch.outlier;
import com.deathrayresearch.outlier.columns.Column;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import org.apache.commons.lang3.StringUtils;
import org.roaringbitmap.RoaringBitmap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
/**
* An un-materialized view on an underlying Table
*/
public class View implements Relation {
private String name;
private Relation table;
private IntArrayList columnIds = new IntArrayList();
private final RoaringBitmap rowMap;
private final int mask[];
private final String id = UUID.randomUUID().toString();
public View(Relation table, String... columnName) {
this.table = table;
for (String col : columnName) {
columnIds.add(table.columnIndex(col));
}
rowMap = new RoaringBitmap();
rowMap.add(0, table.rowCount());
mask = rowMap.toArray();
}
public View(Table table, int headRows) {
this.table = table;
for (String col : table.columnNames()) {
columnIds.add(table.columnIndex(col));
}
rowMap = new RoaringBitmap();
rowMap.add(0, headRows);
mask = rowMap.toArray();
}
public View(View view, int headRows) {
this.table = view;
columnIds = view.columnIds.clone();
int i = 0;
Iterator<Integer> it = view.rowMap.iterator();
rowMap = new RoaringBitmap();
while (i < headRows && it.hasNext()) {
rowMap.add(it.next());
i++;
}
mask = rowMap.toArray();
}
public View(Relation table, List<Column> columnSelection, RoaringBitmap rowSelection) {
this.rowMap = rowSelection;
this.table = table;
for (Column aColumnSelection : columnSelection) {
this.columnIds.add(table.columnIndex(aColumnSelection));
}
mask = rowMap.toArray();
}
public View(Relation table, List<Column> columnSelection) {
this.rowMap = new RoaringBitmap();
this.table = table;
for (Column aColumnSelection : columnSelection) {
this.columnIds.add(table.columnIndex(aColumnSelection));
}
mask = rowMap.toArray();
}
public View where(RoaringBitmap bitmap) {
rowMap.and(bitmap);
return this;
}
@Override
public Column column(int columnIndex) {
return table.column(columnIds.getInt(columnIndex));
}
@Override
public int columnCount() {
return columnIds.size();
}
@Override
public int rowCount() {
return rowMap.getCardinality();
}
@Override
public List<Column> columns() {
List<Column> columns = new ArrayList<>();
for (int i = 0; i < columnCount(); i++) {
columns.add(column(i));
}
return columns;
}
@Override
public int columnIndex(Column column) {
int columnIndex = -1;
for (int i = 0; i < columnIds.size(); i++) {
int viewIndex = columnIds.getInt(i);
if (column(i).equals(column)) {
columnIndex = viewIndex;
break;
}
}
if (columnIndex == -1) {
throw new IllegalArgumentException(String.format("Column %s is not present in view %s", column.name(), name()));
}
return columnIndex;
}
@Override
public String get(int c, int r) {
return table.get(c, r);
}
@Override
public void addColumn(Column column) {
}
@Override
public String name() {
return name;
}
@Override
public Relation emptyCopy() {
return null;
}
@Override
public void clear() {
}
@Override
public String id() {
return id;
}
@Override
public List<String> columnNames() {
List<String> names = new ArrayList<>();
for (Integer columnId : columnIds) {
names.add(table.column(columnId).name());
}
return names;
}
@Override
public int row(int r) {
return mask[r];
}
/**
* Adds the given index to the rowmap for this view.
* @param index an index representing a row in the backing table
*/
public void addIndex(int index) {
this.rowMap.add(index);
}
@Override
public void removeColumns(Column... columns) {
for (Column c : columns) {
columnIds.removeInt(columnIndex(c));
}
}
public View head(int nRows) {
View view = new View(this, Math.min(nRows, rowCount()));
view.setName(name);
return view;
}
@Override
public void setName(String name) {
this.name = name;
}
public String print() {
StringBuilder buf = new StringBuilder();
int[] colWidths = colWidths();
buf.append(name()).append('\n');
List<String> names = this.columnNames();
for (int colNum = 0; colNum < columnCount(); colNum++) {
buf.append(
StringUtils.rightPad(
StringUtils.defaultString(String.valueOf(names.get(colNum))), colWidths[colNum]));
buf.append(' ');
}
buf.append('\n');
for (int r = 0; r < rowCount(); r++) {
for (int i = 0; i < columnCount(); i++) {
int c = columnIds.getInt(i);
String cell = StringUtils.rightPad(get(c, row(r)), colWidths[i]);
buf.append(cell);
buf.append(' ');
}
buf.append('\n');
}
return buf.toString();
}
/**
* Returns an array of column widths for printing tables
*/
public int[] colWidths() {
int cols = columnCount();
int[] widths = new int[cols];
List<String> columnNames = columnNames();
for (int i = 0; i < columnCount(); i++) {
widths[i] = columnNames.get(i).length();
}
for (int rowNum = 0; rowNum < rowCount(); rowNum++) {
for (int colNum = 0; colNum < cols; colNum++) {
int c = columnIds.getInt(colNum);
widths[colNum]
= Math.max(widths[colNum], StringUtils.length(get(c, rowNum)));
}
}
return widths;
}
}
|
package com.jaamsim.input;
import com.jaamsim.basicsim.Entity;
import com.jaamsim.input.ExpParser.Expression;
import com.jaamsim.ui.LogBox;
public class ExpressionInput extends Input<ExpParser.Expression> {
private Entity thisEnt;
public ExpressionInput(String key, String cat, ExpParser.Expression def) {
super(key, cat, def);
}
public void setEntity(Entity ent) {
thisEnt = ent;
}
@Override
public void parse(KeywordIndex kw)
throws InputErrorException {
Input.assertCount(kw, 1);
try {
Expression exp = ExpParser.parseExpression(ExpEvaluator.getParseContext(), kw.getArg(0));
// Test whether the expression can be evaluated
ExpValidator.validateExpression(exp, thisEnt);
// Save the expression
value = exp;
} catch (ExpError e) {
LogBox.logException(e);
throw new InputErrorException(e.toString());
}
}
}
|
package com.lagodiuk.nn;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
@XmlType(name = "basic-threshold-functions")
@XmlEnum
public enum ThresholdFunction {
@XmlEnumValue("LINEAR")
LINEAR {
@Override
public double calculate(double value, List<Double> params) {
double a = params.get(0);
double b = params.get(1);
return (a * value) + b;
};
@Override
public List<Double> getDefaultParams() {
double a = 1;
double b = 0;
List<Double> ret = new LinkedList<Double>();
ret.add(a);
ret.add(b);
return ret;
}
},
@XmlEnumValue("SIGN")
SIGN {
@Override
public double calculate(double value, List<Double> params) {
double threshold = params.get(0);
if (value > threshold) {
return 1;
} else {
return 0;
}
};
@Override
public List<Double> getDefaultParams() {
double threshold = 0;
List<Double> ret = new LinkedList<Double>();
ret.add(threshold);
return ret;
}
},
@XmlEnumValue("SIGMA")
SIGMA {
@Override
public double calculate(double value, List<Double> params) {
double a = params.get(0);
double b = params.get(1);
double c = params.get(2);
return a / (b + Math.expm1(-value * c) + 1);
}
@Override
public List<Double> getDefaultParams() {
double a = 1;
double b = 1;
double c = 1;
List<Double> ret = new ArrayList<Double>(3);
ret.add(a);
ret.add(b);
ret.add(c);
return ret;
}
},
@XmlEnumValue("RADIAL")
RADIAL {
@Override
public double calculate(double value, List<Double> params) {
double a = params.get(0);
return Math.exp((-value * value) / (a * a));
}
@Override
public List<Double> getDefaultParams() {
double a = 1;
List<Double> ret = new ArrayList<Double>(3);
ret.add(a);
return ret;
}
};
private static final Random random = new Random();
public static ThresholdFunction getRandomFunction() {
ThresholdFunction[] allFunctions = values();
return allFunctions[random.nextInt(allFunctions.length)];
}
public double calculate(double value, List<Double> params) {
// Stub
return 0;
}
public List<Double> getDefaultParams() {
// Stub
return Collections.emptyList();
}
}
|
package com.maxmind.geoip2;
import com.maxmind.db.*;
import com.maxmind.db.Reader.FileMode;
import com.maxmind.geoip2.exception.AddressNotFoundException;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.*;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
/**
* <p>
* The class {@code DatabaseReader} provides a reader for the GeoIP2 database
* format.
* </p>
* <h2>Usage</h2>
* <p>
* To use the database API, you must create a new {@code DatabaseReader} using
* the {@code DatabaseReader.Builder}. You must provide the {@code Builder}
* constructor either an {@code InputStream} or {@code File} for your GeoIP2
* database. You may also specify the {@code fileMode} and the {@code locales}
* fallback order using the methods on the {@code Builder} object.
* </p>
* <p>
* After you have created the {@code DatabaseReader}, you may then call one of
* the appropriate methods, e.g., {@code city} or {@code tryCity}, for your
* database. These methods take the IP address to be looked up. The methods
* with the "try" prefix return an {@code Optional} object, which will be
* empty if the value is not present in the database. The method without the
* prefix will throw an {@code AddressNotFoundException} if the address is
* not in the database. If you are looking up many IPs that are not contained
* in the database, the "try" method will be slightly faster as they do not
* need to construct and throw an exception. These methods otherwise behave
* the same.
* </p>
* <p>
* If the lookup succeeds, the method call will return a response class for
* the GeoIP2 lookup. The class in turn contains multiple record classes,
* each of which represents part of the data returned by the database.
* </p>
* <p>
* We recommend reusing the {@code DatabaseReader} object rather than creating
* a new one for each lookup. The creation of this object is relatively
* expensive as it must read in metadata for the file. It is safe to share the
* object across threads.
* </p>
* <h3>Caching</h3>
* <p>
* The database API supports pluggable caching (by default, no caching is
* performed). A simple implementation is provided by
* {@code com.maxmind.db.CHMCache}. Using this cache, lookup performance is
* significantly improved at the cost of a small (~2MB) memory overhead.
* </p>
*/
public class DatabaseReader implements DatabaseProvider, Closeable {
private final Reader reader;
private final List<String> locales;
private final int databaseType;
private enum DatabaseType {
ANONYMOUS_IP,
ASN,
CITY,
CONNECTION_TYPE,
COUNTRY,
DOMAIN,
ENTERPRISE,
ISP;
final int type;
DatabaseType() {
type = 1 << this.ordinal();
}
}
private DatabaseReader(Builder builder)
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
if (builder.stream != null) {
this.reader = new Reader(builder.stream, builder.cache);
} else if (builder.database != null) {
this.reader = new Reader(builder.database, builder.mode, builder.cache);
} else {
// This should never happen. If it does, review the Builder class
// constructors for errors.
throw new IllegalArgumentException(
"Unsupported Builder configuration: expected either File or URL");
}
this.locales = builder.locales;
databaseType = getDatabaseType();
}
private int getDatabaseType() {
String databaseType = this.getMetadata().getDatabaseType();
int type = 0;
if (databaseType.contains("GeoIP2-Anonymous-IP")) {
type |= DatabaseType.ANONYMOUS_IP.type;
}
if (databaseType.contains("GeoLite2-ASN")) {
type |= DatabaseType.ASN.type;
}
if (databaseType.contains("City")) {
type |= DatabaseType.CITY.type | DatabaseType.COUNTRY.type;
}
if (databaseType.contains("GeoIP2-Connection-Type")) {
type |= DatabaseType.CONNECTION_TYPE.type;
}
if (databaseType.contains("Country")) {
type |= DatabaseType.COUNTRY.type;
}
if (databaseType.contains("GeoIP2-Domain")) {
type |= DatabaseType.DOMAIN.type;
}
if (databaseType.contains("Enterprise")) {
type |= DatabaseType.ENTERPRISE.type | DatabaseType.CITY.type | DatabaseType.COUNTRY.type;
}
if (databaseType.contains("GeoIP2-ISP")) {
type |= DatabaseType.ISP.type;
}
if (type == 0) {
// XXX - exception type
throw new UnsupportedOperationException(
"Invalid attempt to open an unknown database type: " + databaseType);
}
return type;
}
/**
* <p>
* Constructs a Builder for the {@code DatabaseReader}. The file passed to
* it must be a valid GeoIP2 database file.
* </p>
* <p>
* {@code Builder} creates instances of {@code DatabaseReader}
* from values set by the methods.
* </p>
* <p>
* Only the values set in the {@code Builder} constructor are required.
* </p>
*/
public static final class Builder {
final File database;
final InputStream stream;
List<String> locales = Collections.singletonList("en");
FileMode mode = FileMode.MEMORY_MAPPED;
NodeCache cache = NoCache.getInstance();
/**
* @param stream the stream containing the GeoIP2 database to use.
*/
public Builder(InputStream stream) {
this.stream = stream;
this.database = null;
}
/**
* @param database the GeoIP2 database file to use.
*/
public Builder(File database) {
this.database = database;
this.stream = null;
}
/**
* @param val List of locale codes to use in name property from most
* preferred to least preferred.
* @return Builder object
*/
public Builder locales(List<String> val) {
this.locales = val;
return this;
}
/**
* @param cache backing cache instance
* @return Builder object
*/
public Builder withCache(NodeCache cache) {
this.cache = cache;
return this;
}
public Builder fileMode(FileMode val) {
if (this.stream != null && FileMode.MEMORY != val) {
throw new IllegalArgumentException(
"Only FileMode.MEMORY is supported when using an InputStream.");
}
this.mode = val;
return this;
}
/**
* @return an instance of {@code DatabaseReader} created from the
* fields set on this builder.
* @throws IOException if there is an error reading the database
*/
public DatabaseReader build()
throws IOException,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
return new DatabaseReader(this);
}
}
static final class LookupResult<T> {
final T model;
final String ipAddress;
final Network network;
LookupResult(T model, String ipAddress, Network network) {
this.model = model;
this.ipAddress = ipAddress;
this.network = network;
}
T getModel() {
return this.model;
}
String getIpAddress() {
return this.ipAddress;
}
Network getNetwork() {
return this.network;
}
}
/**
* @param ipAddress IPv4 or IPv6 address to lookup.
* @param cls The class to deserialize to.
* @param expectedType The expected database type.
* @return A LookupResult<T> object with the data for the IP address
* @throws IOException if there is an error opening or reading from the file.
*/
private <T> LookupResult<T> get(InetAddress ipAddress, Class<T> cls,
DatabaseType expectedType)
throws IOException,
AddressNotFoundException,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
if ((databaseType & expectedType.type) == 0) {
String caller = Thread.currentThread().getStackTrace()[3]
.getMethodName();
throw new UnsupportedOperationException(
"Invalid attempt to open a " + getMetadata().getDatabaseType()
+ " database using the " + caller + " method");
}
// We are using the fully qualified name as otherwise it is ambiguous
// on Java 14 due to the new java.lang.Record.
com.maxmind.db.Record<T> record = reader.getRecord(ipAddress, cls);
T o = record.getData();
return new LookupResult<>(o, ipAddress.getHostAddress(), record.getNetwork());
}
/**
* <p>
* Closes the database.
* </p>
* <p>
* If you are using {@code FileMode.MEMORY_MAPPED}, this will
* <em>not</em> unmap the underlying file due to a limitation in Java's
* {@code MappedByteBuffer}. It will however set the reference to
* the buffer to {@code null}, allowing the garbage collector to
* collect it.
* </p>
*
* @throws IOException if an I/O error occurs.
*/
@Override
public void close() throws IOException {
this.reader.close();
}
@Override
public CountryResponse country(InetAddress ipAddress)
throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
Optional<CountryResponse> r = getCountry(ipAddress);
if (!r.isPresent()) {
throw new AddressNotFoundException("The address "
+ ipAddress.getHostAddress() + " is not in the database.");
}
return r.get();
}
@Override
public Optional<CountryResponse> tryCountry(InetAddress ipAddress)
throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
return getCountry(ipAddress);
}
private Optional<CountryResponse> getCountry(
InetAddress ipAddress
) throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
LookupResult<CountryDatabaseModel> result = this.get(
ipAddress,
CountryDatabaseModel.class,
DatabaseType.COUNTRY
);
CountryDatabaseModel model = result.getModel();
if (model == null) {
return Optional.empty();
}
return Optional.of(
new CountryResponse(
model,
result.getIpAddress(),
result.getNetwork(),
locales
)
);
}
@Override
public CityResponse city(InetAddress ipAddress)
throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
Optional<CityResponse> r = getCity(ipAddress);
if (!r.isPresent()) {
throw new AddressNotFoundException("The address "
+ ipAddress.getHostAddress() + " is not in the database.");
}
return r.get();
}
@Override
public Optional<CityResponse> tryCity(InetAddress ipAddress)
throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
return getCity(ipAddress);
}
private Optional<CityResponse> getCity(
InetAddress ipAddress
) throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
LookupResult<CityDatabaseModel> result = this.get(
ipAddress,
CityDatabaseModel.class,
DatabaseType.CITY
);
CityDatabaseModel model = result.getModel();
if (model == null) {
return Optional.empty();
}
return Optional.of(
new CityResponse(
model,
result.getIpAddress(),
result.getNetwork(),
locales
)
);
}
/**
* Look up an IP address in a GeoIP2 Anonymous IP.
*
* @param ipAddress IPv4 or IPv6 address to lookup.
* @return a AnonymousIpResponse for the requested IP address.
* @throws GeoIp2Exception if there is an error looking up the IP
* @throws IOException if there is an IO error
*/
@Override
public AnonymousIpResponse anonymousIp(InetAddress ipAddress)
throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
Optional<AnonymousIpResponse> r = getAnonymousIp(ipAddress);
if (!r.isPresent()) {
throw new AddressNotFoundException("The address "
+ ipAddress.getHostAddress() + " is not in the database.");
}
return r.get();
}
@Override
public Optional<AnonymousIpResponse> tryAnonymousIp(InetAddress ipAddress)
throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
return getAnonymousIp(ipAddress);
}
private Optional<AnonymousIpResponse> getAnonymousIp(
InetAddress ipAddress
) throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
LookupResult<AnonymousIpDatabaseModel> result = this.get(
ipAddress,
AnonymousIpDatabaseModel.class,
DatabaseType.ANONYMOUS_IP
);
AnonymousIpDatabaseModel model = result.getModel();
if (model == null) {
return Optional.empty();
}
return Optional.of(
new AnonymousIpResponse(
model,
result.getIpAddress(),
result.getNetwork()
)
);
}
/**
* Look up an IP address in a GeoLite2 ASN database.
*
* @param ipAddress IPv4 or IPv6 address to lookup.
* @return an AsnResponse for the requested IP address.
* @throws GeoIp2Exception if there is an error looking up the IP
* @throws IOException if there is an IO error
*/
@Override
public AsnResponse asn(InetAddress ipAddress)
throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
Optional<AsnResponse> r = getAsn(ipAddress);
if (!r.isPresent()) {
throw new AddressNotFoundException("The address "
+ ipAddress.getHostAddress() + " is not in the database.");
}
return r.get();
}
@Override
public Optional<AsnResponse> tryAsn(InetAddress ipAddress)
throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
return getAsn(ipAddress);
}
private Optional<AsnResponse> getAsn(InetAddress ipAddress)
throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
LookupResult<AsnDatabaseModel> result = this.get(
ipAddress,
AsnDatabaseModel.class,
DatabaseType.ASN
);
AsnDatabaseModel model = result.getModel();
if (model == null) {
return Optional.empty();
}
return Optional.of(
new AsnResponse(
model,
result.getIpAddress(),
result.getNetwork()
)
);
}
/**
* Look up an IP address in a GeoIP2 Connection Type database.
*
* @param ipAddress IPv4 or IPv6 address to lookup.
* @return a ConnectTypeResponse for the requested IP address.
* @throws GeoIp2Exception if there is an error looking up the IP
* @throws IOException if there is an IO error
*/
@Override
public ConnectionTypeResponse connectionType(InetAddress ipAddress)
throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
Optional<ConnectionTypeResponse> r = getConnectionType(ipAddress);
if (!r.isPresent()) {
throw new AddressNotFoundException("The address "
+ ipAddress.getHostAddress() + " is not in the database.");
}
return r.get();
}
@Override
public Optional<ConnectionTypeResponse> tryConnectionType(InetAddress ipAddress)
throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
return getConnectionType(ipAddress);
}
private Optional<ConnectionTypeResponse> getConnectionType(
InetAddress ipAddress
) throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
LookupResult<ConnectionTypeDatabaseModel> result = this.get(
ipAddress,
ConnectionTypeDatabaseModel.class,
DatabaseType.CONNECTION_TYPE
);
ConnectionTypeDatabaseModel model = result.getModel();
if (model == null) {
return Optional.empty();
}
return Optional.of(
new ConnectionTypeResponse(
model,
result.getIpAddress(),
result.getNetwork()
)
);
}
/**
* Look up an IP address in a GeoIP2 Domain database.
*
* @param ipAddress IPv4 or IPv6 address to lookup.
* @return a DomainResponse for the requested IP address.
* @throws GeoIp2Exception if there is an error looking up the IP
* @throws IOException if there is an IO error
*/
@Override
public DomainResponse domain(InetAddress ipAddress)
throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
Optional<DomainResponse> r = getDomain(ipAddress);
if (!r.isPresent()) {
throw new AddressNotFoundException("The address "
+ ipAddress.getHostAddress() + " is not in the database.");
}
return r.get();
}
@Override
public Optional<DomainResponse> tryDomain(InetAddress ipAddress)
throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
return getDomain(ipAddress);
}
private Optional<DomainResponse> getDomain(
InetAddress ipAddress
) throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
LookupResult<DomainDatabaseModel> result = this.get(
ipAddress,
DomainDatabaseModel.class,
DatabaseType.DOMAIN
);
DomainDatabaseModel model = result.getModel();
if (model == null) {
return Optional.empty();
}
return Optional.of(
new DomainResponse(
model,
result.getIpAddress(),
result.getNetwork()
)
);
}
/**
* Look up an IP address in a GeoIP2 Enterprise database.
*
* @param ipAddress IPv4 or IPv6 address to lookup.
* @return an EnterpriseResponse for the requested IP address.
* @throws GeoIp2Exception if there is an error looking up the IP
* @throws IOException if there is an IO error
*/
@Override
public EnterpriseResponse enterprise(InetAddress ipAddress)
throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
Optional<EnterpriseResponse> r = getEnterprise(ipAddress);
if (!r.isPresent()) {
throw new AddressNotFoundException("The address "
+ ipAddress.getHostAddress() + " is not in the database.");
}
return r.get();
}
@Override
public Optional<EnterpriseResponse> tryEnterprise(InetAddress ipAddress)
throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
return getEnterprise(ipAddress);
}
private Optional<EnterpriseResponse> getEnterprise(
InetAddress ipAddress
) throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
LookupResult<CityDatabaseModel> result = this.get(
ipAddress,
CityDatabaseModel.class,
DatabaseType.ENTERPRISE
);
CityDatabaseModel model = result.getModel();
if (model == null) {
return Optional.empty();
}
return Optional.of(
new EnterpriseResponse(
model,
result.getIpAddress(),
result.getNetwork(),
locales
)
);
}
/**
* Look up an IP address in a GeoIP2 ISP database.
*
* @param ipAddress IPv4 or IPv6 address to lookup.
* @return an IspResponse for the requested IP address.
* @throws GeoIp2Exception if there is an error looking up the IP
* @throws IOException if there is an IO error
*/
@Override
public IspResponse isp(InetAddress ipAddress)
throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
Optional<IspResponse> r = getIsp(ipAddress);
if (!r.isPresent()) {
throw new AddressNotFoundException("The address "
+ ipAddress.getHostAddress() + " is not in the database.");
}
return r.get();
}
@Override
public Optional<IspResponse> tryIsp(InetAddress ipAddress)
throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
return getIsp(ipAddress);
}
private Optional<IspResponse> getIsp(
InetAddress ipAddress
) throws IOException,
GeoIp2Exception,
InstantiationException,
IllegalAccessException,
InvocationTargetException,
NoSuchMethodException {
LookupResult<IspDatabaseModel> result = this.get(
ipAddress,
IspDatabaseModel.class,
DatabaseType.ISP
);
IspDatabaseModel model = result.getModel();
if (model == null) {
return Optional.empty();
}
return Optional.of(
new IspResponse(
model,
result.getIpAddress(),
result.getNetwork()
)
);
}
/**
* @return the metadata for the open MaxMind DB file.
*/
public Metadata getMetadata() {
return this.reader.getMetadata();
}
}
|
package com.orctom.mojo.was;
import com.orctom.mojo.was.model.WebSphereModel;
import com.orctom.mojo.was.service.WebSphereServiceFactory;
import com.orctom.mojo.was.utils.AntTaskUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.configuration.PlexusConfiguration;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
@Mojo(name = "deploy", defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST, requiresDirectInvocation = true, threadSafe = true)
public class WASDeployMojo extends AbstractWASMojo {
@Parameter
protected boolean parallel;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
getLog().info(Constants.PLUGIN_ID + " - deploy");
Set<WebSphereModel> models = getWebSphereModels();
if (models.isEmpty()) {
getLog().info("[SKIPPED] empty target server configured, please check your configuration");
return;
}
if (parallel) {
ExecutorService executor = Executors.newFixedThreadPool(models.size());
for (final WebSphereModel model : models) {
executor.execute(new Runnable() {
@Override
public void run() {
execute(model);
}
});
}
executor.shutdown();
try {
executor.awaitTermination(20, TimeUnit.MINUTES);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
for (WebSphereModel model : models) {
execute(model);
}
}
}
private void execute(WebSphereModel model) {
getLog().info("============================================================");
getLog().info("[DEPLOY] " + model.getHost() + " " + model.getApplicationName());
getLog().info("============================================================");
executeAntTasks(model, super.preSteps);
getLog().info("====================== deploy ========================");
WebSphereServiceFactory.getService(mode, model, project.getBuild().getOutputDirectory()).deploy();
executeAntTasks(model, super.postSteps);
}
private void executeAntTasks(WebSphereModel model, PlexusConfiguration[] targets) {
for (PlexusConfiguration target : targets) {
try {
AntTaskUtils.execute(model, target, project, projectHelper, pluginArtifacts, getLog());
} catch (IOException e) {
e.printStackTrace();
} catch (MojoExecutionException e) {
e.printStackTrace();
}
}
}
}
|
package com.paymill.services;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.MultivaluedMap;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.paymill.context.PaymillContext;
import com.paymill.exceptions.PaymillException;
import com.paymill.models.PaymillList;
import com.paymill.models.SnakeCase;
import com.paymill.models.Updateable;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;
final class RestfulUtils {
private final static String ENDPOINT = "https://api.paymill.com/v2";
static <T> PaymillList<T> list( String path, Object filter, Object order, Integer count, Integer offset, Class<?> clazz, Client httpClient ) {
MultivaluedMap<String, String> params = RestfulUtils.prepareFilterParameters( filter );
String param = RestfulUtils.prepareOrderParameter( order );
if( StringUtils.isNotBlank( param ) && !StringUtils.startsWith( param, "_" ) ) {
params.add( "order", param );
}
if( count != null && count > 0 ) {
params.add( "count", String.valueOf( count ) );
}
if( offset != null && offset >= 0 ) {
params.add( "offset", String.valueOf( offset ) );
}
return RestfulUtils.deserializeList( RestfulUtils.get( path, params, httpClient ), clazz );
}
static <T> T show( String path, T target, Class<?> clazz, Client httpClient ) {
String id = RestfulUtils.getIdByReflection( target );
T source = RestfulUtils.deserializeObject( RestfulUtils.get( path + "/" + id, httpClient ), clazz );
return RestfulUtils.refreshInstance( source, target );
}
static <T> T create( String path, MultivaluedMap<String, String> params, Class<T> clazz, Client httpClient ) {
return RestfulUtils.deserializeObject( RestfulUtils.post( path, params, httpClient ), clazz );
}
static <T> T update( String path, T target, Class<?> clazz, Client httpClient ) {
MultivaluedMap<String, String> params = RestfulUtils.prepareEditableParameters( target );
String id = RestfulUtils.getIdByReflection( target );
T source = RestfulUtils.deserializeObject( RestfulUtils.put( path + "/" + id, params, httpClient ), clazz );
return RestfulUtils.refreshInstance( source, target );
}
static <T> T delete( String path, T target, Class<?> clazz, Client httpClient ) {
String id = RestfulUtils.getIdByReflection( target );
return RestfulUtils.deserializeObject( RestfulUtils.delete( path + "/" + id, httpClient ), clazz );
}
private static String getIdByReflection( Object instance ) {
if( instance == null )
throw new RuntimeException( "Can not obtain Id from null" );
try {
Field field = instance.getClass().getDeclaredField( "id" );
field.setAccessible( true );
String id = String.valueOf( field.get( instance ) );
ValidationUtils.validatesId( id );
return id;
} catch( Exception exc ) {
throw new RuntimeException( exc );
}
}
@SuppressWarnings( "unchecked" )
private static <T> T deserializeObject( String content, Class<?> clazz ) {
try {
JsonNode wrappedNode = PaymillContext.PARSER.readValue( content, JsonNode.class );
if( wrappedNode.has( "data" ) ) {
JsonNode dataNode = wrappedNode.get( "data" );
if( !dataNode.isArray() ) {
return (T) PaymillContext.PARSER.readValue( dataNode.toString(), clazz );
}
}
if( wrappedNode.has( "error" ) ) {
throw new PaymillException( wrappedNode.get( "error" ).toString() );
}
} catch( IOException exc ) {
throw new RuntimeException( exc );
}
return null;
}
@SuppressWarnings( "unchecked" )
private static <T> PaymillList<T> deserializeList( String content, Class<?> clazz ) {
try {
JsonNode wrappedNode = PaymillContext.PARSER.readValue( content, JsonNode.class );
PaymillList<T> wrapper = PaymillContext.PARSER.readValue( wrappedNode.toString(), PaymillList.class );
if( wrappedNode.has( "data" ) ) {
JsonNode dataNode = wrappedNode.get( "data" );
if( dataNode.isArray() ) {
List<T> objects = new ArrayList<T>();
for( Object object : PaymillContext.PARSER.readValue( wrappedNode.toString(), PaymillList.class ).getData() ) {
try {
objects.add( (T) PaymillContext.PARSER.readValue( PaymillContext.PARSER.writeValueAsString( object ), clazz ) );
} catch( Exception exc ) {
throw new RuntimeException( exc );
}
}
wrapper.setData( objects );
return wrapper;
}
}
if( wrappedNode.has( "error" ) ) {
throw new PaymillException( wrappedNode.get( "error" ).toString() );
}
} catch( IOException exc ) {
throw new RuntimeException( exc );
}
return null;
}
private static MultivaluedMap<String, String> prepareEditableParameters( Object instance ) {
MultivaluedMap<String, String> params = new MultivaluedMapImpl();
for( Field field : instance.getClass().getDeclaredFields() ) {
Updateable updateable = field.getAnnotation( Updateable.class );
if( updateable != null ) {
try {
field.setAccessible( true );
Object value = field.get( instance );
if( value != null ) {
Class<?> clazz = value.getClass();
if( ClassUtils.isPrimitiveOrWrapper( clazz ) || ClassUtils.getSimpleName( clazz ).equals( "String" ) ) {
params.add( updateable.value(), String.valueOf( field.get( instance ) ) );
} else {
params.add( updateable.value(), String.valueOf( RestfulUtils.getIdByReflection( field.get( instance ) ) ) );
}
}
} catch( Exception exc ) {
throw new RuntimeException( exc );
}
}
}
return params;
}
private static String get( String path, Client httpClient ) {
WebResource webResource = httpClient.resource( RestfulUtils.ENDPOINT + path );
ClientResponse response = webResource.get( ClientResponse.class );
return response.getEntity( String.class );
}
private static String get( String path, MultivaluedMap<String, String> params, Client httpClient ) {
WebResource webResource = httpClient.resource( RestfulUtils.ENDPOINT + path ).queryParams( params );
ClientResponse response = webResource.get( ClientResponse.class );
return response.getEntity( String.class );
}
private static String post( String path, MultivaluedMap<String, String> params, Client httpClient ) {
WebResource webResource = httpClient.resource( RestfulUtils.ENDPOINT + path );
ClientResponse response = webResource.post( ClientResponse.class, params );
return response.getEntity( String.class );
}
private static String put( String path, MultivaluedMap<String, String> params, Client httpClient ) {
WebResource webResource = httpClient.resource( RestfulUtils.ENDPOINT + path );
ClientResponse response = webResource.put( ClientResponse.class, params );
return response.getEntity( String.class );
}
private static String delete( String path, Client httpClient ) {
WebResource webResource = httpClient.resource( RestfulUtils.ENDPOINT + path );
ClientResponse response = webResource.delete( ClientResponse.class );
return response.getEntity( String.class );
}
private static MultivaluedMap<String, String> prepareFilterParameters( Object instance ) {
MultivaluedMap<String, String> params = new MultivaluedMapImpl();
if( instance == null )
return params;
try {
for( Field field : instance.getClass().getDeclaredFields() ) {
field.setAccessible( true );
Object value = field.get( instance );
if( value != null ) {
params.add( field.getAnnotation( SnakeCase.class ).value(), String.valueOf( value ) );
}
}
} catch( Exception exc ) {
throw new RuntimeException( exc );
}
return params;
}
private static String prepareOrderParameter( Object instance ) {
if( instance == null )
return StringUtils.EMPTY;
String order = StringUtils.EMPTY;
String sortEntry = StringUtils.EMPTY;
try {
for( Field field : instance.getClass().getDeclaredFields() ) {
field.setAccessible( true );
if( field.getBoolean( instance ) ) {
SnakeCase annotation = field.getAnnotation( SnakeCase.class );
if( annotation.order() ) {
order += "_" + annotation.value();
} else {
sortEntry = annotation.value();
}
}
}
} catch( Exception exc ) {
throw new RuntimeException( exc );
}
return sortEntry + order;
}
private static <T> T refreshInstance( T source, T target ) {
try {
BeanUtils.copyProperties( target, source );
} catch( Exception exc ) {
throw new RuntimeException( exc );
}
return target;
}
}
|
package com.publicuhc;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.publicuhc.commands.CommandModule;
import com.publicuhc.commands.routing.Router;
import com.publicuhc.configuration.Configurator;
import com.publicuhc.configuration.ConfigurationModule;
import com.publicuhc.translate.Translate;
import com.publicuhc.translate.TranslateModule;
import org.bukkit.Server;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginLoader;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public abstract class FrameworkJavaPlugin extends JavaPlugin {
private Configurator m_configurator;
private Translate m_translate;
private Router m_router;
/**
* This method is intended for unit testing purposes. Its existence may be temporary.
* @see org.bukkit.plugin.java.JavaPlugin
*/
protected FrameworkJavaPlugin(PluginLoader loader, Server server, PluginDescriptionFile pdf, File file1, File file2) {
super(loader, server, pdf, file1, file2);
}
@Override
public final void onLoad() {
List<AbstractModule> modules = initialModules();
if(modules == null) {
modules = new ArrayList<AbstractModule>();
}
final Plugin plugin = this;
modules.add(new AbstractModule() {
@Override
protected void configure() {
bind(Plugin.class).toInstance(plugin);
}
});
if(initUseDefaultBindings()){
modules.add(new CommandModule());
modules.add(new ConfigurationModule());
modules.add(new TranslateModule());
}
Injector injector = Guice.createInjector(modules);
injector.injectMembers(this);
onFrameworkLoad();
}
/**
* Called when the framework is loaded
*/
public void onFrameworkLoad() {
}
/**
* Return a list of extra modules to initialize DI with.
* Override this method to change the extra modules to load with.
* @return the list of modules
*/
public List<AbstractModule> initialModules() {
return null;
}
/**
* If returns true will include default modules on init.
* If false you must specify all the bindings for the framework
* @return whether to use the defaults or not
*/
public boolean initUseDefaultBindings() {
return true;
}
/**
* Set the router by injection
* @param router the router object
*/
@Inject
private void setRouter(Router router) {
m_router = router;
}
/**
* Set the configurator by injection
* @param configurator the configurator object
*/
@Inject
private void setConfigurator(Configurator configurator) {
m_configurator = configurator;
}
/**
* Set the translate by injection
* @param translate the translate object
*/
@Inject
private void setTranslate(Translate translate) {
m_translate = translate;
}
/**
* <b>ONLY USE THIS AFTER onLoad HAS BEEN CALLED. (onFrameworkLoad and later) otherwise it will return null</b>
* @return the router object
*/
public Router getRouter() {
return m_router;
}
/**
* <b>ONLY USE THIS AFTER onLoad HAS BEEN CALLED. (onFrameworkLoad and later) otherwise it will return null</b>
* @return the configurator object
*/
public Configurator getConfigurator() {
return m_configurator;
}
/**
* <b>ONLY USE THIS AFTER onEnable HAS BEEN CALLED. (onFrameworkLoad and later) otherwise it will return null</b>
* @return the translate object
*/
public Translate getTranslate() {
return m_translate;
}
}
|
package com.thalmic.myo.wobble;
import com.thalmic.myo.AbstractDeviceListener;
import com.thalmic.myo.Myo;
import com.thalmic.myo.Pose;
import com.thalmic.myo.Quaternion;
import com.thalmic.myo.enums.*;
public class OurDevList extends AbstractDeviceListener {
private static final int SCALE = 17; //number of subdivisions of range of position output
private double rollW;
private double pitchW;
private double yawW;
private Pose currentPose;
private Arm whichArm;
public OurDevList() {
rollW = 0;
pitchW = 0;
yawW = 0;
currentPose = new Pose();
}
@Override
public void onOrientationData(Myo myo, long timestamp, Quaternion rotation) {
Quaternion normalized = rotation.normalized();
double roll = Math.atan2(2.0f * (normalized.getW() * normalized.getX() + normalized.getY() * normalized.getZ()), 1.0f - 2.0f * (normalized.getX() * normalized.getX() + normalized.getY() * normalized.getY()));
double pitch = Math.asin(2.0f * (normalized.getW() * normalized.getY() - normalized.getZ() * normalized.getX()));
double yaw = Math.atan2(2.0f * (normalized.getW() * normalized.getZ() + normalized.getX() * normalized.getY()), 1.0f - 2.0f * (normalized.getY() * normalized.getY() + normalized.getZ() * normalized.getZ()));
rollW = ((roll + Math.PI) / (Math.PI * 2.0) * SCALE);
pitchW = ((pitch + Math.PI / 2.0) / Math.PI * SCALE);
yawW = ((yaw + Math.PI) / (Math.PI * 2.0) * SCALE);
}
@Override
public void onPose(Myo myo, long timestamp, Pose pose) {
currentPose = pose;
if (currentPose.getType() == PoseType.FIST) {
myo.vibrate(VibrationType.VIBRATION_MEDIUM);
}
}
@Override
public void onArmSync(Myo myo, long timestamp, Arm arm, XDirection xDirection, float rotation, WarmupState warmupState) {
whichArm = arm;
}
@Override
public void onArmUnsync(Myo myo, long timestamp) {
whichArm = null;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("\r");
String xDisplay = String.format("[%s%s]", repeatCharacter('*', (int) rollW), repeatCharacter(' ', (int) (SCALE - rollW)));
String yDisplay = String.format("[%s%s]", repeatCharacter('*', (int) pitchW), repeatCharacter(' ', (int) (SCALE - pitchW)));
String zDisplay = String.format("[%s%s]", repeatCharacter('*', (int) yawW), repeatCharacter(' ', (int) (SCALE - yawW)));
String armString = null;
if (whichArm != null) {
armString = String.format("[%s]", whichArm == Arm.ARM_LEFT ? "L" : "R");
} else {
armString = String.format("[?]");
}
String poseString = null;
if (currentPose != null) {
String poseTypeString = currentPose.getType().toString();
poseString = String.format("[%s%" + (SCALE - poseTypeString.length()) + "s]", poseTypeString, " ");
} else {
poseString = String.format("[%14s]", " ");
}
builder.append(xDisplay);
builder.append(yDisplay);
builder.append(zDisplay);
builder.append(armString);
builder.append(poseString);
return "hey";//builder.toString();
}
private String repeatCharacter(char character, int numOfTimes) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < numOfTimes; i++) {
builder.append(character);
}
return builder.toString();
}
public double getPitchW(){return pitchW;}
}
|
package com.wizzardo.http;
import com.wizzardo.http.html.HtmlBuilder;
import com.wizzardo.http.html.Tag;
import com.wizzardo.http.request.Header;
import com.wizzardo.http.request.Request;
import com.wizzardo.http.response.RangeResponseHelper;
import com.wizzardo.http.response.Response;
import com.wizzardo.http.response.Status;
import com.wizzardo.tools.misc.DateIso8601;
import com.wizzardo.tools.misc.Unchecked;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import static com.wizzardo.http.html.HtmlBuilder.*;
public class FileTreeHandler<T extends FileTreeHandler.HandlerContext> implements Handler {
protected static final int SIZE_GB = 1024 * 1024 * 1024;
protected static final int SIZE_MB = 1024 * 1024;
protected static final int SIZE_KB = 1024;
protected static final String ORDER_ASC = "asc";
protected static final String ORDER_DESC = "desc";
private String prefix;
private String workDirPath;
private File workDir;
protected boolean showFolder = true;
public FileTreeHandler(File workDir, String prefix) {
if (prefix.endsWith("/"))
prefix = prefix.substring(0, prefix.length() - 1);
if (!prefix.isEmpty() && !prefix.startsWith("/"))
prefix = "/" + prefix;
this.workDir = workDir;
this.prefix = prefix;
workDirPath = getCanonicalPath(workDir);
}
public FileTreeHandler(String workDir, String prefix) {
this(new File(workDir), prefix);
}
@Override
public Response handle(Request request, Response response) {
String path = request.path().toString();
if (!path.startsWith(prefix))
return response.setStatus(Status._400).setBody("path must starts with prefix '" + prefix + "'");
if (!prefix.isEmpty())
path = path.substring(prefix.length(), path.length());
File file = new File(workDir, decodePath(path));
String canonicalPath = getCanonicalPath(file);
if (!canonicalPath.startsWith(workDirPath))
return response.setStatus(Status._403).setBody(path + " is forbidden");
if (!file.exists())
return response.setStatus(Status._404).setBody(path + " not found");
if (!file.canRead())
return response.setStatus(Status._403).setBody(path + " is forbidden");
if (file.isDirectory())
if (showFolder)
return response.appendHeader(Header.KV_CONTENT_TYPE_HTML_UTF8).setBody(renderDirectory(request, file));
else
return response.setStatus(Status._403).setBody(path + " is forbidden");
return RangeResponseHelper.makeRangeResponse(request, response, file);
}
public FileTreeHandler<T> setShowFolder(boolean showFolder) {
this.showFolder = showFolder;
return this;
}
protected String getCanonicalPath(File file) {
try {
return file.getCanonicalPath();
} catch (IOException e) {
throw Unchecked.rethrow(e);
}
}
protected Tag createHeader(File dir, Tag holder) {
renderFolderPath(dir, holder);
return holder;
}
protected Tag createTableHeader(String path, String sort, String order) {
return tr()
.add(th().add(a().href(path + "?sort=name&order=" + ("name".equals(sort) ? (ORDER_DESC.equals(order) ? ORDER_ASC : ORDER_DESC) : ORDER_ASC))
.text("Name"))
)
.add(th().add(a().href(path + "?sort=modified&order=" + ("modified".equals(sort) ? (ORDER_DESC.equals(order) ? ORDER_ASC : ORDER_DESC) : ORDER_DESC))
.text("Last modified"))
)
.add(th().add(a().href(path + "?sort=size&order=" + ("size".equals(sort) ? (ORDER_DESC.equals(order) ? ORDER_ASC : ORDER_DESC) : ORDER_DESC))
.text("Size"))
)
;
}
protected StringBuilder renderFolderPath(File dir, Tag holder) {
if (dir.equals(workDir)) {
StringBuilder s = new StringBuilder();
holder.add(a().href("/").text("root: "));
s.append(prefix).append("/");
holder.add(a().href(prefix + "/").text(prefix)).text("/");
return s;
}
if (dir.getPath().endsWith("/"))
return renderFolderPath(dir.getParentFile(), holder);
StringBuilder path = renderFolderPath(dir.getParentFile(), holder).append(dir.getName()).append("/");
holder.add(a().href(path.toString()).text(dir.getName())).text("/");
return path;
}
private Tag renderDirectory(Request request, File dir) {
String path = prefix + getCanonicalPath(dir).substring(workDirPath.length());
File[] files = dir.listFiles();
String sort = request.paramWithDefault("sort", "name");
String order = request.paramWithDefault("order", "asc");
int orderInt = order.equals("asc") ? 1 : -1;
int sortInt = sort.equals("modified") ? 3 : sort.equals("size") ? 2 : 1;
Arrays.sort(files, (o1, o2) -> {
if (o1.isDirectory() && !o2.isDirectory())
return -1;
if (o2.isDirectory() && !o1.isDirectory())
return 1;
if (sortInt == 3) {
int result = Long.compare(o1.lastModified(), o2.lastModified());
if (result != 0)
return result * orderInt;
}
if (sortInt == 2) {
int result = Long.compare(o1.length(), o2.length());
if (result != 0)
return result * orderInt;
}
return o1.getName().compareTo(o2.getName()) * orderInt;
});
if (!path.endsWith("/"))
path += '/';
T handlerContext = createHandlerContext(path, request);
return render(path, dir, files, sort, order, handlerContext);
}
protected Tag render(String path, File dir, File[] files, String sort, String order, T handlerContext) {
HtmlBuilder html = new HtmlBuilder();
html.add(header().add(Meta.charset("utf-8").add(title(path))));
html.add(body()
.add(createHeader(dir, h(1)))
.add(table()
.attr("border", "0")
.add(createTableHeader(path, sort, order))
.each(files, (file, table) -> {
String url = generateUrl(file, handlerContext);
table.add(tr()
.add(td().add(a().href(url).text(file.getName() + (file.isDirectory() ? "/" : ""))))
.add(td().text(DateIso8601.format(new Date(file.lastModified()))))
.add(td().attr("align", "right").text(formatFileSize(file.length())))
).text("\n");
return null;
}))
);
return html;
}
protected T createHandlerContext(String path, Request request) {
return (T) new HandlerContext(path);
}
protected String generateUrl(File file, T handlerContext) {
return encodeName(file.getName()) + (file.isDirectory() ? "/" : "");
}
private String encodeName(String name) {
return Unchecked.call(() -> URLEncoder.encode(name, "utf-8").replace("+", "%20"));
}
private String decodePath(String path) {
return Unchecked.call(() -> URLDecoder.decode(path, "utf-8"));
}
protected static class HandlerContext {
protected final String path;
public HandlerContext(String path) {
this.path = path;
}
}
protected String formatFileSize(long l) {
if (l >= SIZE_GB)
return l / SIZE_GB + "G";
if (l >= SIZE_MB)
return l / SIZE_MB + "M";
if (l >= SIZE_KB)
return l / SIZE_KB + "K";
return String.valueOf(l);
}
}
|
package com.wmjmc.reactspeech;
import android.app.Activity;
import android.content.Intent;
import android.speech.RecognizerIntent;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import com.wmjmc.reactspeech.LocaleConstants;
public class VoiceModule extends ReactContextBaseJavaModule implements ActivityEventListener {
static final int REQUEST_SPEECH_ACTIVITY = 1;
final ReactApplicationContext reactContext;
private Promise mVoicepromise;
public VoiceModule(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
this.reactContext.addActivityEventListener(this);
}
@Override
public String getName() {
return "SpeechAndroid";
}
@Override
public Map<String, Object> getConstants() {
return Constants.getConstants();
}
@ReactMethod
public void startSpeech(String prompt, String locale, final Promise promise) {
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
promise.reject(ErrorConstants.E_ACTIVITY_DOES_NOT_EXIST);
return;
}
mVoicepromise = promise;
final Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, getLocale(locale));
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getPrompt(prompt));
if (intent.resolveActivity(this.reactContext.getPackageManager()) != null) {
try{
this.reactContext.startActivityForResult(intent, REQUEST_SPEECH_ACTIVITY, null);
}catch(Exception ex){
mVoicepromise.reject(ErrorConstants.E_FAILED_TO_SHOW_VOICE);
mVoicepromise = null;
}
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (mVoicepromise == null) {
return;
}
switch (resultCode){
case Activity.RESULT_OK:
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mVoicepromise.resolve(result.get(0));
mVoicepromise = null;
break;
case Activity.RESULT_CANCELED:
mVoicepromise.reject(ErrorConstants.E_VOICE_CANCELLED);
mVoicepromise = null;
break;
case RecognizerIntent.RESULT_AUDIO_ERROR:
mVoicepromise.reject(ErrorConstants.E_AUDIO_ERROR);
mVoicepromise = null;
break;
case RecognizerIntent.RESULT_NETWORK_ERROR:
mVoicepromise.reject(ErrorConstants.E_NETWORK_ERROR);
mVoicepromise = null;
break;
case RecognizerIntent.RESULT_NO_MATCH:
mVoicepromise.reject(ErrorConstants.E_NO_MATCH);
mVoicepromise = null;
break;
case RecognizerIntent.RESULT_SERVER_ERROR:
mVoicepromise.reject(ErrorConstants.E_SERVER_ERROR);
mVoicepromise = null;
break;
}
}
private String getPrompt(String prompt){
if(prompt != null && !prompt.equals("")){
return prompt;
}
return "Say something";
}
private String getLocale(String locale){
if(locale != null && !locale.equals("")){
return locale;
}
return Locale.getDefault().toString();
}
}
|
package cz.req.ax.builders;
import com.vaadin.ui.MenuBar;
public class MenuBarBuilder extends ComponentBuilder<MenuBar, MenuBarBuilder> {
public MenuBarBuilder() {
super(new MenuBar(), true);
}
public MenuBarBuilder(MenuBar target, boolean useDefaults) {
super(target, useDefaults);
}
public MenuBarBuilder html() {
target.setHtmlContentAllowed(true);
return this;
}
public MenuBarBuilder autoOpen(boolean autoOpen) {
target.setAutoOpen(autoOpen);
return this;
}
public MenuBarBuilder autoOpen() {
return autoOpen(true);
}
public MenuItemBuilder item() {
return new MenuItemBuilder(target);
}
public MenuItemBuilder item(String caption) {
return item().caption(caption);
}
public MenuBuilder menu() {
return new MenuBuilder(target);
}
public MenuBuilder menu(String caption) {
return menu().caption(caption);
}
public MenuBarBuilder link() {
return style("link");
}
public MenuBarBuilder small() {
return style("small");
}
public MenuBarBuilder borderless() {
return style("borderless");
}
}
|
package de.hbz.lobid.helper;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.openrdf.model.BNode;
import org.openrdf.model.Graph;
import org.openrdf.model.Statement;
import org.openrdf.rio.RDFFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jan Schnasse
* @author Pascal Christoph (dr0i)
*/
public class JsonConverter {
final static Logger logger = LoggerFactory.getLogger(JsonConverter.class);
String first = "http://www.w3.org/1999/02/22-rdf-syntax-ns#first";
String rest = "http://www.w3.org/1999/02/22-rdf-syntax-ns#rest";
String nil = "http://www.w3.org/1999/02/22-rdf-syntax-ns#nil";
String contributorOrder = "http://purl.org/lobid/lv#contributorOrder";
String subjectOrder = "http://purl.org/lobid/lv#subjectOrder";
Set<Statement> all = new HashSet<>();
public Map<String, Object> convert(InputStream in, RDFFormat format,
String uri) {
Graph g = RdfUtils.readRdfToGraph(in, format, uri);
collect(g);
Map<String, Object> result = createMap(g, uri);
result.put("@context", Globals.etikette.context.get("@context"));
return result;
}
private Map<String, Object> createMap(Graph g, String uri) {
Map<String, Object> jsonResult = new TreeMap<>();
Iterator<Statement> i = g.iterator();
jsonResult.put("@id", uri);
while (i.hasNext()) {
Statement s = i.next();
Etikett e = Globals.etikette.getEtikett(s.getPredicate().stringValue());
if (uri.equals(s.getSubject().stringValue())) {
createObject(jsonResult, s, e);
}
}
return jsonResult;
}
private void createObject(Map<String, Object> jsonResult, Statement s,
Etikett e) {
String key = e.name;
if (s.getObject() instanceof org.openrdf.model.Literal) {
addLiteralToJsonResult(jsonResult, key, s.getObject().stringValue());
}
if (s.getObject() instanceof org.openrdf.model.BNode) {
if (contributorOrder.equals(s.getPredicate().stringValue())
|| subjectOrder.equals(s.getPredicate().stringValue())) {
addListToJsonResult(jsonResult, key, ((BNode) s.getObject()).getID());
}
} else {
addObjectToJsonResult(jsonResult, key, s.getObject().stringValue());
}
}
private void addListToJsonResult(Map<String, Object> jsonResult, String key,
String id) {
logger.info("Create list for " + key + " pointing to " + id);
jsonResult.put(key, traversList(id, first, new ArrayList<>()));
}
/**
* The property "first" has always exactly one property "rest", which itself
* may point to a another "first" node. At the end of that chain the "rest"
* node has the value "nil".
*
* @param uri
* @param property
* @param orderedList
* @return the ordered list
*/
private List<String> traversList(String uri, String property,
List<String> orderedList) {
for (Statement s : find(uri)) {
if (uri.equals(s.getSubject().stringValue())
&& property.equals(s.getPredicate().stringValue())) {
if (property.equals(first)) {
orderedList.add(s.getObject().stringValue());
traverseList(s.getSubject().stringValue(), orderedList, s, "data",
rest);
} else if (property.equals(rest)) {
traverseList(s.getObject().stringValue(), orderedList, s, "node",
first);
}
}
}
return orderedList;
}
private void traverseList(String uri, List<String> orderedList, Statement s,
String message, String property) {
logger.debug("Find next " + message + ": " + uri);
all.remove(s.getSubject());
traversList(uri, property, orderedList);
}
private void addObjectToJsonResult(Map<String, Object> jsonResult, String key,
String uri) {
if (jsonResult.containsKey(key)) {
@SuppressWarnings("unchecked")
Set<Map<String, Object>> literals =
(Set<Map<String, Object>>) jsonResult.get(key);
literals.add(createObject(uri));
} else {
Set<Map<String, Object>> literals = new HashSet<>();
literals.add(createObject(uri));
jsonResult.put(key, literals);
}
}
private Map<String, Object> createObject(String uri) {
Map<String, Object> newObject = new TreeMap<>();
if (uri != null) {
newObject.put("@id", uri);
// newObject.put("prefLabel",
// Globals.etikette.getEtikett(uri).label);
}
for (Statement s : find(uri)) {
Etikett e = Globals.etikette.getEtikett(s.getPredicate().stringValue());
if (s.getObject() instanceof org.openrdf.model.Literal) {
newObject.put(e.name, s.getObject().stringValue());
} else {
createObject(newObject, s, e);
}
}
return newObject;
}
private Set<Statement> find(String uri) {
Set<Statement> result = new HashSet<>();
for (Statement i : all) {
if (uri.equals(i.getSubject().stringValue()))
result.add(i);
}
return result;
}
private static void addLiteralToJsonResult(
final Map<String, Object> jsonResult, final String key,
final String value) {
if (jsonResult.containsKey(key)) {
@SuppressWarnings("unchecked")
Set<String> literals = (Set<String>) jsonResult.get(key);
literals.add(value);
} else {
Set<String> literals = new HashSet<>();
literals.add(value);
jsonResult.put(key, literals);
}
}
private void collect(Graph g) {
Iterator<Statement> i = g.iterator();
while (i.hasNext()) {
Statement s = i.next();
all.add(s);
}
}
}
|
package de.skuzzle.jeve;
/**
* RegistrationEvents are created when adding or removing a {@link Listener} from an
* {@link EventProvider}.
*
* @author Simon Taddiken
*/
public class RegistrationEvent extends Event<EventProvider> {
/** The class for which the listener has been added or removed */
private final Class<? extends Listener> cls;
/**
* Creates a new RegistrationEvent.
* @param source The EventProvider for which a Listener as added or removed.
* @param cls The class for which the Listener was added ore removed.
*/
RegistrationEvent(EventProvider source, Class<? extends Listener> cls) {
super(source);
this.cls = cls;
}
/**
* Gets the class for which the Listener has been added or removed.
*
* @return The event class.
*/
public Class<? extends Listener> getEventClass() {
return this.cls;
}
}
|
package de.vogel612.helper.ui;
import static de.vogel612.helper.data.util.DataUtilities.FILENAME_PATTERN;
import de.vogel612.helper.data.util.DataUtilities;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* View to select a set of Resx-Files and locales.
*/
public class ResxChooser {
private final JFrame window = new JFrame("Translation Helper - File and Locale chooser");
private final JFileChooser fileChooser = new JFileChooser();
private final Set<String> localeOptionCache = new HashSet<>();
private final JButton rightLocaleChange = new JButton("change");
private final JLabel rightLocaleLbl = new JLabel();
private String rightLocale;
private final JButton leftLocaleChange = new JButton("change");
private final JLabel leftLocaleLbl = new JLabel();
private String leftLocale;
private final JButton chooseFileset = new JButton("Choose");
private final JLabel filesetLbl = new JLabel();
private Path fileset;
private final JButton submit = new JButton("Okay");
private final Set<Consumer<ResxChooserEvent>> resxChoiceCompletionListener = new HashSet<>();
public ResxChooser() {
window.setLayout(new GridBagLayout());
final Dimension size = new Dimension(500, 400);
window.setMinimumSize(size);
window.setSize(size);
GridBagConstraints labelConstraints = new GridBagConstraints();
labelConstraints.fill = GridBagConstraints.BOTH;
labelConstraints.gridx = 0;
labelConstraints.gridy = 0;
labelConstraints.weightx = 0.7;
GridBagConstraints buttonConstraints = new GridBagConstraints();
buttonConstraints.fill = GridBagConstraints.BOTH;
buttonConstraints.gridx = 1;
buttonConstraints.gridy = 0;
buttonConstraints.insets = new Insets(20,20,20,20);
buttonConstraints.weightx = 0.3;
buttonConstraints.anchor = GridBagConstraints.EAST;
window.add(leftLocaleLbl, labelConstraints);
window.add(leftLocaleChange, buttonConstraints);
labelConstraints.gridy = 1;
buttonConstraints.gridy = 1;
window.add(rightLocaleLbl, labelConstraints);
window.add(rightLocaleChange, buttonConstraints);
labelConstraints.gridy = 2;
buttonConstraints.gridy = 2;
window.add(filesetLbl, labelConstraints);
window.add(chooseFileset, buttonConstraints);
buttonConstraints.gridy = 3;
window.add(submit, buttonConstraints);
// unit-test related
submit.setName("submit");
chooseFileset.setName("fileset");
rightLocaleChange.setName("right");
leftLocaleChange.setName("left");
fileChooser.setFileFilter(new FileNameExtensionFilter("Resx files", "resx"));
fileChooser.setMultiSelectionEnabled(false);
fileChooser.setDialogTitle("Choose a resx file kind to translate");
fileChooser.setCurrentDirectory(Paths.get(".").toFile());
fileChooser.setMinimumSize(SwingOverviewView.MINIMUM_WINDOW_SIZE);
fileChooser.setSize(SwingOverviewView.MINIMUM_WINDOW_SIZE);
submit.addActionListener(e -> {
if (fileset != null && leftLocale != null && rightLocale != null) {
final ResxChooserEvent event = new ResxChooserEvent(this);
resxChoiceCompletionListener.forEach(c -> c.accept(event));
}
});
rightLocaleChange.addActionListener(e -> {
rightLocale = chooseLocale();
rightLocaleLbl.setText("RIGHT: " + rightLocale);
});
leftLocaleChange.addActionListener(e -> {
leftLocale = chooseLocale();
leftLocaleLbl.setText("LEFT: " + leftLocale);
});
chooseFileset.addActionListener(e -> {
int ret = fileChooser.showOpenDialog(null);
if (ret == JFileChooser.APPROVE_OPTION) {
fileset = fileChooser.getSelectedFile().toPath();
onFilesetChange();
}
});
}
public void setFileset(Path fileset) {
if (fileset == null) {
throw new IllegalArgumentException();
}
this.fileset = fileset;
onFilesetChange();
}
private void onFilesetChange() {
final Matcher filesetMatcher = FILENAME_PATTERN.matcher(fileset.getFileName().toString());
if (filesetMatcher.matches()) { // should always be true
final String filesetName = filesetMatcher.group(1);
filesetLbl.setText(filesetName); // group is not optional
try (final Stream<Path> filesetFiles = DataUtilities.streamFileset(fileset.getParent(), filesetName)) {
localeOptionCache.clear();
localeOptionCache.addAll(filesetFiles.map(
DataUtilities::parseLocale).collect(
Collectors.toSet()));
// drop locales we cannot have anymore...
if (!localeOptionCache.contains(leftLocale)) {
leftLocale = null;
leftLocaleLbl.setText("(none)");
}
if (!localeOptionCache.contains(rightLocale)) {
rightLocale = null;
rightLocaleLbl.setText("(none)");
}
} catch (IOException e1) {
// FIXME handle
e1.printStackTrace();
}
}
}
private String chooseLocale() {
final String[] localeChoices = localeOptionCache.toArray(new String[localeOptionCache.size()]);
int result = JOptionPane.showOptionDialog(window,
"Choose a locale",
"",
JOptionPane.DEFAULT_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
localeChoices,
localeChoices[0]);
return localeChoices[result];
}
public void hide() {
window.setVisible(false);
}
public void show() {
window.setVisible(true);
}
public void addCompletionListener(Consumer<ResxChooserEvent> listener) {
resxChoiceCompletionListener.add(listener);
}
/**
* An event signaling the choice of fileset and locale is completed
*/
public static class ResxChooserEvent {
private final Path fileset;
private final String rightLocale;
private final String leftLocale;
public ResxChooserEvent(ResxChooser c) {
this.leftLocale = c.leftLocale;
this.rightLocale = c.rightLocale;
this.fileset = c.fileset;
}
public String getLeftLocale() {
return leftLocale;
}
public String getRightLocale() {
return rightLocale;
}
public Path getFileset() {
return fileset;
}
}
}
|
package dmax.words.ui.cards;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import dmax.words.DataSource;
import dmax.words.R;
import dmax.words.domain.Language;
import dmax.words.ui.Util;
import dmax.words.ui.detail.LinkDetailFragment;
import dmax.words.ui.MainActivity;
import dmax.words.ui.cards.CardsPagerAdapter.CardViewHolder;
public class CardsFragment extends Fragment implements View.OnClickListener {
private static final int DURATION = 250;
private View emptyView;
private ViewPager pager;
private CardsPagerAdapter adapter;
private LanguageSwitcher switcher;
private boolean removing;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MainActivity activity = getCastedActivity();
DataSource dataSource = activity.getDataSource();
this.switcher = new LanguageSwitcher(this, dataSource.getSelectedLanguage());
this.adapter = new CardsPagerAdapter(activity, dataSource);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.f_wordslist, container, false);
emptyView = root.findViewById(R.id.empty_view);
pager = (ViewPager) root.findViewById(R.id.pager);
ImageButton add = (ImageButton) root.findViewById(R.id.add);
add.setOnClickListener(this);
View panel = Util.createDarkThemedView(getActivity(), R.layout.v_languages_panel);
root.addView(panel, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
switcher.init(panel);
if (adapter.getCount() > 0) {
showCards();
}
return root;
}
@Override
public void onStart() {
super.onStart();
ActionBar actionBar = getActivity().getActionBar();
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setTitle(null);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
actionBar.setCustomView(switcher.createActionBar());
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.word_list, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
removeCurrentCard();
return true;
case R.id.edit:
editCurrentCard();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
openDetailedFragment(null);
}
public void updateLanguage(Language language) {
getDataSource().setSelectedLanguage(language);
adapter.onLanguageChanged();
}
public void showCards() {
getDataSource().reset();
emptyView.setVisibility(View.GONE);
pager.setVisibility(View.VISIBLE);
pager.setAdapter(adapter);
}
private MainActivity getCastedActivity() {
return (MainActivity) getActivity();
}
private DataSource getDataSource() {
return getCastedActivity().getDataSource();
}
private void editCurrentCard() {
int id = pager.getCurrentItem();
CardView cardView = (CardView) pager.findViewById(id).findViewById(R.id.card);
CardViewHolder holder = (CardViewHolder) cardView.getTag();
Bundle params = new Bundle();
params.putSerializable(LinkDetailFragment.KEY_ORIGINAL, holder.originalWord);
params.putSerializable(LinkDetailFragment.KEY_TRANSLATION, holder.translationWord);
params.putSerializable(LinkDetailFragment.KEY_LINK, holder.link);
openDetailedFragment(params);
}
private void removeCurrentCard() {
if (removing) return;
final int id = pager.getCurrentItem();
CardView cardView = (CardView) pager.findViewById(id).findViewById(R.id.card);
CardViewHolder holder = (CardViewHolder) cardView.getTag();
Animator transition = prepareCollapseTransition(cardView);
transition.addListener(new PageRemover(id, holder));
transition.start();
removing = true;
}
private Animator prepareCollapseTransition(View v) {
Animator vertical = ObjectAnimator.ofFloat(v, "scaleY", 1f, 0);
Animator horizontal = ObjectAnimator.ofFloat(v, "scaleX", 1f, 0);
AnimatorSet set = new AnimatorSet();
set.playTogether(vertical, horizontal);
set.setDuration(DURATION);
return set;
}
private void openDetailedFragment(Bundle params) {
LinkDetailFragment fragment = new LinkDetailFragment();
fragment.setArguments(params);
getFragmentManager().beginTransaction()
.setCustomAnimations(R.animator.slide_up, 0, 0, R.animator.slide_down)
.replace(R.id.container, fragment)
.addToBackStack(null)
.commit();
}
private class PageRemover extends AnimatorListenerAdapter implements ViewPager.OnPageChangeListener {
private int pageToRemove;
private int pageToShowBeforeRemoving;
private int pageToShowAfterRemoving;
private CardViewHolder holder;
private PageRemover(int pageToRemove, CardViewHolder holder) {
this.pageToRemove = pageToRemove;
this.holder = holder;
}
@Override
public void onAnimationEnd(Animator animation) {
if (adapter.getCount() > 1) {
showNextPage();
} else {
hidePager();
removeItem();
}
}
private void showNextPage() {
boolean pageOnRightExist = pageToRemove != adapter.getCount() - 1;
pageToShowBeforeRemoving = pageOnRightExist
? pageToRemove + 1
: pageToRemove - 1;
pageToShowAfterRemoving = pageOnRightExist
? pageToShowBeforeRemoving - 1
: pageToShowBeforeRemoving;
pager.setCurrentItem(pageToShowBeforeRemoving, true);
pager.setOnPageChangeListener(this);
}
private void hidePager() {
pager.setVisibility(View.INVISIBLE);
emptyView.setVisibility(View.VISIBLE);
}
private void removeItem() {
getDataSource().removeWords(holder.link, holder.originalWord, holder.translationWord);
adapter.notifyDataSetChanged();
}
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE && pager.getCurrentItem() == pageToShowBeforeRemoving) {
pager.setOnPageChangeListener(null);
removeItem();
pager.setCurrentItem(pageToShowAfterRemoving, false);
removing = false;
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
@Override
public void onPageSelected(int position) {}
}
}
|
package edu.ufl.cise.cnt5106c;
import edu.ufl.cise.cnt5106c.conf.CommonProperties;
import edu.ufl.cise.cnt5106c.conf.RemotePeerInfo;
import edu.ufl.cise.cnt5106c.log.EventLogger;
import edu.ufl.cise.cnt5106c.log.LogHelper;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Giacomo Benincasa (giacomo@cise.ufl.edu)
*/
public class PeerManager implements Runnable {
class OptimisticUnchoker extends Thread {
private final int _numberOfOptimisticallyUnchokedNeighbors;
private final int _optimisticUnchokingInterval;
private final List<RemotePeerInfo> _chokedNeighbors = new ArrayList<>();
final Collection<RemotePeerInfo> _optmisticallyUnchokedPeers =
Collections.newSetFromMap(new ConcurrentHashMap<RemotePeerInfo, Boolean>());
OptimisticUnchoker(Properties conf) {
super("OptimisticUnchoker");
_numberOfOptimisticallyUnchokedNeighbors = 1;
_optimisticUnchokingInterval = Integer.parseInt(
conf.getProperty(CommonProperties.NumberOfPreferredNeighbors.toString())) * 1000;
}
synchronized void setChokedNeighbors(Collection<RemotePeerInfo> chokedNeighbors) {
_chokedNeighbors.clear();
_chokedNeighbors.addAll(chokedNeighbors);
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(_optimisticUnchokingInterval);
} catch (InterruptedException ex) {
}
synchronized (this) {
// Randomly shuffle the remaining neighbors, and select some to optimistically unchoke
if (!_chokedNeighbors.isEmpty()) {
Collections.shuffle(_chokedNeighbors);
_optmisticallyUnchokedPeers.addAll(_chokedNeighbors.subList(0,
Math.min(_numberOfOptimisticallyUnchokedNeighbors, _chokedNeighbors.size())));
}
}
if (_optmisticallyUnchokedPeers.size() > 0) {
_eventLogger.changeOfOptimisticallyUnchokedNeighbors(LogHelper.getPeerIdsAsString (_optmisticallyUnchokedPeers));
}
for (PeerManagerListener listener : _listeners) {
listener.unchockedPeers(RemotePeerInfo.toIdSet(_optmisticallyUnchokedPeers));
}
}
}
}
private final int _numberOfPreferredNeighbors;
private final int _unchokingInterval;
private final int _bitmapsize;
private final EventLogger _eventLogger;
private final List<RemotePeerInfo> _peers = new ArrayList<>();
private final Collection<RemotePeerInfo> _preferredPeers = new HashSet<>();
private final OptimisticUnchoker _optUnchoker;
private final Collection<PeerManagerListener> _listeners = new LinkedList<>();
private final AtomicBoolean _randomlySelectPreferred = new AtomicBoolean(false);
PeerManager(int peerId, Collection<RemotePeerInfo> peers, int bitmapsize, Properties conf) {
_peers.addAll(peers);
_numberOfPreferredNeighbors = Integer.parseInt(
conf.getProperty(CommonProperties.NumberOfPreferredNeighbors.toString()));
_unchokingInterval = Integer.parseInt(
conf.getProperty(CommonProperties.UnchokingInterval.toString())) * 1000;
_optUnchoker = new OptimisticUnchoker(conf);
_bitmapsize = bitmapsize;
_eventLogger = new EventLogger (peerId);
}
synchronized void addInterestPeer(int remotePeerId) {
RemotePeerInfo peer = searchPeer(remotePeerId);
if (peer != null) {
peer.setInterested();
}
}
synchronized List<RemotePeerInfo> getInterestedPeers() {
ArrayList<RemotePeerInfo> interestedPeers = new ArrayList<>();
for (RemotePeerInfo peer : _peers){
if(peer.isInterested()){
interestedPeers.add(peer);
}
}
return interestedPeers;
}
synchronized boolean isInteresting(int peerId, BitSet bitset) {
RemotePeerInfo peer = searchPeer(peerId);
if (peer != null) {
BitSet pBitset = (BitSet) peer._receivedParts.clone();
pBitset.andNot(bitset);
return ! pBitset.isEmpty();
}
return false;
}
synchronized void receivedPart(int peerId, int size) {
RemotePeerInfo peer = searchPeer(peerId);
if (peer != null) {
peer._bytesDownloadedFrom += size;
}
}
synchronized boolean canUploadToPeer(int peerId) {
RemotePeerInfo peerInfo = new RemotePeerInfo(peerId);
return (_preferredPeers.contains(peerInfo) ||
_optUnchoker._optmisticallyUnchokedPeers.contains(peerInfo));
}
synchronized void fileCompleted() {
_randomlySelectPreferred.set (true);
}
synchronized void bitfieldArrived(int peerId, BitSet bitfield) {
RemotePeerInfo peer = searchPeer(peerId);
if (peer != null) {
peer._receivedParts = bitfield;
}
neighborsCompletedDownload();
}
synchronized void haveArrived(int peerId, int partId) {
RemotePeerInfo peer = searchPeer(peerId);
if (peer != null) {
peer._receivedParts.set(partId);
}
neighborsCompletedDownload();
}
synchronized BitSet getReceivedParts(int peerId) {
RemotePeerInfo peer = searchPeer(peerId);
if (peer != null) {
return (BitSet) peer._receivedParts.clone();
}
return new BitSet(); // empry bit set
}
synchronized private RemotePeerInfo searchPeer(int peerId) {
for (RemotePeerInfo peer : _peers) {
if (peer.getPeerId() == peerId) {
return peer;
}
}
LogHelper.getLogger().severe("Peer " + peerId + " not found");
return null;
}
synchronized private void neighborsCompletedDownload() {
for (RemotePeerInfo peer : _peers) {
if (peer._receivedParts.cardinality() < _bitmapsize) {
// at least one neighbor has not completed
LogHelper.getLogger().debug("Peer " + peer.getPeerId() + " has not completed yet");
return;
}
}
for (PeerManagerListener listener : _listeners) {
listener.neighborsCompletedDownload();
}
}
public synchronized void registerListener(PeerManagerListener listener) {
_listeners.add(listener);
}
@Override
public void run() {
// At the beginning all the neighbors are choked, because the peer has not
// recieved anything from anyone
_optUnchoker.start();
while (true) {
try {
Thread.sleep(_unchokingInterval);
} catch (InterruptedException ex) {
}
synchronized (this) {
List<RemotePeerInfo> interestedPeers = getInterestedPeers();
LogHelper.getLogger().severe(new StringBuilder("Interested peers: ")
.append(LogHelper.getPeerIdsAsString(interestedPeers)).toString());
if (_randomlySelectPreferred.get()) {
// Randomly shuffle the neighbors
LogHelper.getLogger().debug("selecting preferred peers randomly");
Collections.shuffle(interestedPeers);
}
else {
// Sort the peers in order of preference
Collections.sort(interestedPeers, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
RemotePeerInfo ri1 = (RemotePeerInfo) (o1);
RemotePeerInfo ri2 = (RemotePeerInfo) (o2);
// Sort in decreasing order
return (ri2._bytesDownloadedFrom - ri1._bytesDownloadedFrom);
}
});
}
// Reset downloaded bytes
for (RemotePeerInfo peer : _peers) {
peer._bytesDownloadedFrom = 0;
}
// Select the highest ranked neighbors as "preferred"
_preferredPeers.clear();
_preferredPeers.addAll(interestedPeers.subList(0, Math.min(_numberOfPreferredNeighbors, interestedPeers.size())));
if (_preferredPeers.size() > 0) {
_eventLogger.changeOfPrefereedNeighbors(LogHelper.getPeerIdsAsString (_preferredPeers));
}
Collection<RemotePeerInfo> chokedPeers = new LinkedList<>(interestedPeers);
chokedPeers.removeAll(_preferredPeers);
interestedPeers.removeAll(_preferredPeers);
for (PeerManagerListener listener : _listeners) {
listener.chockedPeers(RemotePeerInfo.toIdSet(chokedPeers));
listener.unchockedPeers(RemotePeerInfo.toIdSet(_preferredPeers));
}
// Select the remaining neighbors for choking
if (_numberOfPreferredNeighbors >= interestedPeers.size()) {
_optUnchoker.setChokedNeighbors(new ArrayList<RemotePeerInfo>());
}
else {
_optUnchoker.setChokedNeighbors(interestedPeers.subList(_numberOfPreferredNeighbors, interestedPeers.size()));
}
}
}
}
}
|
package es.icane.metadatos;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import com.sun.jersey.api.client.*;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import es.icane.metadatos.dto.TimeSeriesDTO;
import es.icane.metadatos.model.*;
/**
* Metadata Client is used for accessing ICANE's Web Service methods.
* <p/>
* In a production environment, only uriTags should be used in all methods
* (instead of numeric id's).
*
* @author Alejandro Villar <contacto@alejandro-villar.es>
*/
public class MetadataClient {
private final String baseUrl;
// Constants
private final MediaType defaultMediaType = MediaType.APPLICATION_XML_TYPE;
private Client jerseyClient;
private ClientConfig clientConfig;
private WebResource webResource;
private long connectionTimeout;
/**
* Constructor.
*
* @param baseUrl base URL for the Web Service
*/
public MetadataClient(String baseUrl) {
this.baseUrl = baseUrl;
clientConfig = new DefaultClientConfig();
clientConfig.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, 10000);
jerseyClient = Client.create(clientConfig);
webResource = jerseyClient.resource(baseUrl);
}
/**
* Returns this client's base URL.
*
* @return this client's base URL.
*/
public String getBaseUrl() {
return baseUrl;
}
/**
* Returns this client's connection timeout, in milliseconds.
* <p/>
* The client will wait this long before timing out when connecting to the Web Service.
*
* @return this client's connection timeout, in milliseconds
*/
public long getConnectionTimeout() {
return connectionTimeout;
}
/**
* Sets the connection timeout for this client.
* <p/>
* The client will wait this long before timing out when connecting to the Web Service.
*
* @param connectionTimeout the new connection timeout, in milliseconds
* @return
*/
public MetadataClient setConnectionTimeout(long connectionTimeout) {
if (connectionTimeout < 0) {
throw new IllegalArgumentException("connectionTimeout must be non-negative");
}
clientConfig.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, connectionTimeout);
this.connectionTimeout = connectionTimeout;
return this;
}
/*
* Time Series methods
*/
/**
* Retrieve a TimeSeries object by its section, subsection and category.
*
* @param category the TimeSeries category's uriTag
* @param section the TimeSeries section's uriTag
* @param subsection the TimeSeries subsection's uriTag
* @param idOrUriTag either the String value of the TimeSeries numeric id
* @return the TimeSeries object
* @throws SeriesNotFoundException
*/
public TimeSeries getTimeSeries(String category, String section, String subsection,
String idOrUriTag) throws SeriesNotFoundException {
try {
return webResource.path(category).path(section).path(subsection).path(idOrUriTag)
.accept(defaultMediaType).get(TimeSeries.class);
} catch (UniformInterfaceException e) {
throw new SeriesNotFoundException(e);
}
}
/**
* Retrieve a TimeSeries object by its section, subsection and category, including inactive series.
*
* @param category the TimeSeries category's uriTag
* @param section the TimeSeries section's uriTag
* @param subsection the TimeSeries subsection's uriTag
* @param idOrUriTag either the String value of the TimeSeries numeric id
* @param inactive if set to true, inactive series will be retrieved too
* @return the TimeSeries object
* @throws SeriesNotFoundException
*/
public TimeSeries getTimeSeries(String category, String section, String subsection, String idOrUriTag,
Boolean inactive) throws SeriesNotFoundException {
try {
MultivaluedMap queryParams = new MultivaluedMapImpl();
queryParams.add("inactive", inactive.toString());
return webResource.path(category).path(section).path(subsection).path(idOrUriTag)
.queryParams(queryParams).accept(defaultMediaType).get(TimeSeries.class);
} catch (UniformInterfaceException e) {
throw new SeriesNotFoundException(e);
}
}
/**
* Retrieve a TimeSeries object by its section, subsection and category.
*
* @param category the TimeSeries category
* @param section the TimeSeries section
* @param subsection the TimeSeries subsection
* @param idOrUriTag either the String value of the TimeSeries numeric id
* @return the TimeSeries object
* @throws SeriesNotFoundException
*/
public TimeSeries getTimeSeries(Category category, Section section,
Subsection subsection, String idOrUriTag) throws SeriesNotFoundException {
try {
return webResource.path(category.getUriTag()).path(section.getUriTag())
.path(subsection.getUriTag()).path(idOrUriTag).accept(defaultMediaType).get(TimeSeries.class);
} catch (UniformInterfaceException e) {
throw new SeriesNotFoundException(e);
}
}
/**
* Returns a TimeSeries, given its numeric id.
* <p/>
* This method is not guaranteed to work in a production environment.
*
* @param timeSeriesId the numeric id of the TimeSeries
* @return the TimeSeries object with that id
* @throws SeriesNotFoundException
*/
public TimeSeries getTimeSeries(int timeSeriesId) throws SeriesNotFoundException {
try {
return webResource.path("time-series").path(String.valueOf(timeSeriesId))
.accept(defaultMediaType).get(TimeSeries.class);
} catch (UniformInterfaceException e) {
throw new SeriesNotFoundException(e);
}
}
/**
* Returns a TimeSeries, given its URI tag.
*
* @param uriTag the URI tag of the TimeSeries
* @return the TimeSeries object with that URI tag
* @throws SeriesNotFoundException
*/
public TimeSeries getTimeSeries(String uriTag) throws SeriesNotFoundException {
try {
return webResource.path("time-series").path(uriTag).accept(defaultMediaType).get(TimeSeries.class);
} catch (UniformInterfaceException e) {
throw new SeriesNotFoundException(e);
}
}
public List<TimeSeries> getTimeSeriesBySectionAndCategory(String category, String section)
throws SeriesNotFoundException {
GenericType<List<TimeSeries>> genericType = new GenericType<List<TimeSeries>>() {
};
try {
return webResource.path(category).path(section).path("time-series-list").
accept(defaultMediaType).get(genericType);
} catch (UniformInterfaceException e) {
throw new SeriesNotFoundException(e);
}
}
public List<TimeSeries> getTimeSeriesList(Category category, Section section) throws SeriesNotFoundException {
GenericType<List<TimeSeries>> genericType = new GenericType<List<TimeSeries>>() {
};
try {
return webResource.path(category.getUriTag()).path(section.getUriTag())
.path("time-series-list").accept(defaultMediaType).get(genericType);
} catch (UniformInterfaceException e) {
throw new SeriesNotFoundException(e);
}
}
public List<TimeSeries> getTimeSeriesBySubsection(String section, String subsection) throws SeriesNotFoundException {
GenericType<List<TimeSeries>> genericType = new GenericType<List<TimeSeries>>() {
};
try {
return webResource.path(section).path(subsection)
.path("time-series-list").accept(defaultMediaType).get(genericType);
} catch (UniformInterfaceException e) {
throw new SeriesNotFoundException(e);
}
}
public List<TimeSeries> getTimeSeriesList(Section section, Subsection subsection) throws SeriesNotFoundException {
GenericType<List<TimeSeries>> genericType = new GenericType<List<TimeSeries>>() {
};
List<TimeSeries> timeSeriesList = new ArrayList<TimeSeries>();
for (Category category : getCategories()) {
timeSeriesList.addAll(getTimeSeriesList(category, section, subsection));
}
return timeSeriesList;
}
/**
* Get a List of all the time series belonging to a given category.
*
* @param category the category's uriTag
* @return a List with all the time series matching the criteria
* @throws SeriesNotFoundException
*/
public List<TimeSeries> getTimeSeriesByCategory(String category) throws SeriesNotFoundException {
GenericType<List<TimeSeries>> genericType = new GenericType<List<TimeSeries>>() {
};
try {
return webResource.path(category).path("time-series-list").accept(defaultMediaType).get(genericType);
} catch (UniformInterfaceException e) {
throw new SeriesNotFoundException(e);
}
}
/**
* Get a List of all the time series belonging to a given section, subsection and category.
*
* @param category the category
* @param section the section
* @param subsection the subsection
* @return a List with all the time series matching the criteria
* @throws SeriesNotFoundException
*/
public List<TimeSeries> getTimeSeriesList(Category category, Section section, Subsection subsection)
throws SeriesNotFoundException {
GenericType<List<TimeSeries>> genericType = new GenericType<List<TimeSeries>>() {
};
try {
return webResource.path(category.getUriTag()).path(section.getUriTag())
.path(subsection.getUriTag()).path("time-series-list").accept(defaultMediaType).get(genericType);
} catch (UniformInterfaceException e) {
throw new SeriesNotFoundException(e);
}
}
/**
* Get a List of all the time series belonging to a given section, subsection and category (by their uriTags).
*
* @param category the category's uriTag
* @param section the section's uriTag
* @param subsection the subsection's uriTag
* @return a List with all the time series matching the criteria
* @throws SeriesNotFoundException
*/
public List<TimeSeries> getTimeSeriesList(String category, String section, String subsection)
throws SeriesNotFoundException {
GenericType<List<TimeSeries>> genericType = new GenericType<List<TimeSeries>>() {
};
try {
return webResource.path(category).path(section).path(subsection)
.path("time-series-list").accept(defaultMediaType).get(genericType);
} catch (UniformInterfaceException e) {
throw new SeriesNotFoundException(e);
}
}
/**
* Get a List of all the time series belonging to a given dataset.
*
* @param dataSet the dataset
* @return a List with all the time series matching the criteria
* @throws SeriesNotFoundException
*/
public List<TimeSeries> getTimeSeriesList(DataSet dataSet) throws SeriesNotFoundException {
GenericType<List<TimeSeries>> genericType = new GenericType<List<TimeSeries>>() {
};
try {
return webResource.path("data-set").path(dataSet.getUriTag())
.path("time-series-list").accept(defaultMediaType).get(genericType);
} catch (UniformInterfaceException e) {
throw new SeriesNotFoundException(e);
}
}
/**
* Get a List of all the time series belonging to a given dataset (by its uriTag).
*
* @param dataSet the subsection's dataset
* @return a List with all the time series matching the criteria
* @throws SeriesNotFoundException
*/
public List<TimeSeries> getTimeSeriesList(String dataSet) throws SeriesNotFoundException {
GenericType<List<TimeSeries>> genericType = new GenericType<List<TimeSeries>>() {
};
try {
return webResource.path("data-set").path(dataSet)
.path("time-series-list").accept(defaultMediaType).get(genericType);
} catch (UniformInterfaceException e) {
throw new SeriesNotFoundException(e);
}
}
/**
* Get the parent of a given TimeSeries
*
* @param timeSeries the TimeSeries whose parent to retrieve
* @return its parent TimeSeries
* @throws SeriesNotFoundException
*/
public TimeSeries getParent(TimeSeries timeSeries) throws SeriesNotFoundException {
try {
return webResource.path(timeSeries.getCategory().getUriTag()).path(timeSeries.getSubsection()
.getSection().getUriTag()).path(timeSeries.getSubsection().getUriTag())
.path(timeSeries.getUriTag()).path("parent").accept(defaultMediaType).get(TimeSeries.class);
} catch (UniformInterfaceException e) {
throw new SeriesNotFoundException(e);
}
}
/**
* Get all the ancestors of a given TimeSeries
*
* @param timeSeries the TimeSeries whose ancestors to retrieve
* @return a List with all its ancestors
* @throws SeriesNotFoundException
*/
public List<TimeSeries> getAncestors(TimeSeries timeSeries) throws SeriesNotFoundException {
GenericType<List<TimeSeries>> genericType = new GenericType<List<TimeSeries>>() {
};
try {
return webResource.path(timeSeries.getCategory().getUriTag()).path(timeSeries.getSubsection()
.getSection().getUriTag()).path(timeSeries.getSubsection().getUriTag())
.path(timeSeries.getUriTag()).path("parents").accept(defaultMediaType).get(genericType);
} catch (UniformInterfaceException e) {
throw new SeriesNotFoundException(e);
}
}
// Section methods
/**
* Retrieves a List of all the Sections.
*
* @return a List of all the available Sections
*/
public List<Section> getSections() {
GenericType<List<Section>> genericType = new GenericType<List<Section>>() {
};
return webResource.path("sections").accept(defaultMediaType).get(genericType);
}
/**
* Get a Map of all the sections, keyed by uriTag.
*
* @return a Map with all the sections
*/
public Map<String, Section> getSectionMap() {
List<Section> sections = getSections();
Map<String, Section> sectionMap = new LinkedHashMap<String, Section>();
for (Section s : sections) {
sectionMap.put(s.getUriTag(), s);
}
return sectionMap;
}
/**
* Retrieves a Section by its URI tag.
*
* @param uriTag the Section's URI tag to search for
* @return the corresponding Section
* @throws SectionNotFoundException
*/
public Section getSection(String uriTag) throws SectionNotFoundException {
try {
return webResource.path("section").path(uriTag).accept(defaultMediaType).get(Section.class);
} catch (UniformInterfaceException e) {
throw new SectionNotFoundException();
}
}
/*
* Subsection methods
*/
/**
* Get a list of all the subsections of a given section.
*
* @param section the section's uriTag
* @return a list of its subsections
*/
public List<Subsection> getSubsections(String subSection) {
GenericType<List<Subsection>> genericType = new GenericType<List<Subsection>>() {
};
return webResource.path("section").path(subSection).path("subsections").accept(defaultMediaType).get(genericType);
}
/**
* Get a list of all the subsections of a given section.
*
* @param section the section
* @return a list of its subsections
*/
public List<Subsection> getSubsections(Section section) {
GenericType<List<Subsection>> genericType = new GenericType<List<Subsection>>() {
};
return webResource.path("section").path(section.getUriTag()).path("subsections")
.accept(defaultMediaType).get(genericType);
}
/**
* Get a map with all the subsections of a given section, keyed by uriTag.
*
* @param section the section's uriTag
* @return a Map containing all its subsections
*/
public Map<String, Subsection> getSubsectionMap(String section) {
List<Subsection> subsections = getSubsections(section);
Map<String, Subsection> subsectionMap = new LinkedHashMap<String, Subsection>();
for (Subsection s : subsections) {
subsectionMap.put(s.getUriTag(), s);
}
return subsectionMap;
}
/*
* Category methods
*/
/**
* Retrieves a List of all the categories.
*
* @return a List of all the available categories
*/
public List<Category> getCategories() {
GenericType<List<Category>> genericType = new GenericType<List<Category>>() {
};
return webResource.path("categories").accept(defaultMediaType).get(genericType);
}
/**
* Get a Map of all the categories, keyed by uriTag.
*
* @return a Map with all the sections
*/
public Map<String, Category> getCategoryMap() {
List<Category> categories = getCategories();
Map<String, Category> categoryMap = new LinkedHashMap<String, Category>();
for (Category s : categories) {
categoryMap.put(s.getUriTag(), s);
}
return categoryMap;
}
/**
* Retrieve a category by its uriTag.
*
* @param uriTag the uriTag of the Category
* @return
*/
public Category getCategory(String uriTag) throws CategoryNotFoundException {
try {
return webResource.path("category").path(uriTag).accept(defaultMediaType).get(Category.class);
} catch (UniformInterfaceException e) {
throw new CategoryNotFoundException();
}
}
/**
* Retrieve a subsection by its numeric id.
*
* @param subsectionId the numeric id of the subsection
* @return
*/
public Subsection getSubsection(int subsectionId) throws SubsectionNotFoundException {
try {
return webResource.path("subsection").path(String.valueOf(subsectionId))
.accept(defaultMediaType).get(Subsection.class);
} catch (UniformInterfaceException e) {
throw new SubsectionNotFoundException();
}
}
/*
* Reference area methods
*/
/**
* Retrieve a list of all the reference areas.
*
* @return a List with ReferenceArea objects
*/
public List<ReferenceArea> getReferenceAreas() {
GenericType<List<ReferenceArea>> genericType = new GenericType<List<ReferenceArea>>() {
};
return webResource.path("reference-areas").accept(defaultMediaType).get(genericType);
}
/**
* Retrieve a map of all the reference areas, keyed by uriTag.
*
* @return a Map of ReferenceArea objects, keyed by their uriTag
*/
public Map<String, ReferenceArea> getReferenceAreaMap() {
List<ReferenceArea> referenceAreas = getReferenceAreas();
Map<String, ReferenceArea> referenceAreaMap = new LinkedHashMap<String, ReferenceArea>();
for (ReferenceArea r : referenceAreas) {
referenceAreaMap.put(r.getUriTag(), r);
}
return referenceAreaMap;
}
/**
* Retrieve a ReferenceArea by its uriTag.
*
* @param uriTag the ReferenceArea's uriTag
* @return
*/
public ReferenceArea getReferenceArea(String uriTag) throws ReferenceAreaNotFoundException {
try {
return webResource.path("reference-area").path(uriTag)
.accept(defaultMediaType).get(ReferenceArea.class);
} catch (UniformInterfaceException e) {
throw new ReferenceAreaNotFoundException();
}
}
/*
* Data set methods
*/
/**
* Retrieve a list of all the data sets.
*
* @return a List with DataSet objects
*/
public List<DataSet> getDataSets() {
GenericType<List<DataSet>> genericType = new GenericType<List<DataSet>>() {
};
return webResource.path("data-sets").accept(defaultMediaType).get(genericType);
}
/**
* Retrieve a map of all the data sets, keyed by uriTag.
*
* @return a Map of DataSet objects, keyed by their uriTag
*/
public Map<String, DataSet> getDataSetMap() {
List<DataSet> dataSets = getDataSets();
Map<String, DataSet> dataSetMap = new LinkedHashMap<String, DataSet>();
for (DataSet r : dataSets) {
dataSetMap.put(r.getUriTag(), r);
}
return dataSetMap;
}
/**
* Retrieve a DataSet by its uriTag.
*
* @param uriTag the DataSet's uriTag
* @return
*/
public DataSet getDataSet(String uriTag) throws DataSetNotFoundException {
try {
return webResource.path("data-set").path(uriTag).accept(defaultMediaType).get(DataSet.class);
} catch (UniformInterfaceException e) {
throw new DataSetNotFoundException();
}
}
/*
* Periodicity methods
*/
/**
* Retrieve a list of all the data sets.
*
* @return a List with DataSet objects
*/
public List<Periodicity> getPeriodicities() {
GenericType<List<Periodicity>> genericType = new GenericType<List<Periodicity>>() {
};
return webResource.path("periodicities").accept(defaultMediaType).get(genericType);
}
/**
* Retrieve a Periodicity by its uriTag.
*
* @param uriTag the DataSet's uriTag
* @return
*/
public Periodicity getPeriodicity(String uriTag) throws PeriodicityNotFoundException {
try {
return webResource.path("periodicity").path(uriTag).accept(defaultMediaType).get(Periodicity.class);
} catch (UniformInterfaceException e) {
throw new PeriodicityNotFoundException();
}
}
/*
* TimePeriod methods
*/
/**
* Retrieve a list of all the sources.
*
* @return a List with Source objects
*/
public List<TimePeriod> getTimePeriods() {
GenericType<List<TimePeriod>> genericType = new GenericType<List<TimePeriod>>() {
};
return webResource.path("time-periods").accept(defaultMediaType).get(genericType);
}
/*
* NodeType methods
*/
/**
* Retrieve a list of all the sources.
*
* @return a List with Source objects
*/
public List<NodeType> getNodeTypes() {
GenericType<List<NodeType>> genericType = new GenericType<List<NodeType>>() {
};
return webResource.path("node-types").accept(defaultMediaType).get(genericType);
}
/*
* Data provider methods
*/
/**
* Retrieve a list of all the data providers.
*
* @return a List with DataProvider objects
*/
public List<DataProvider> getDataProviders() {
GenericType<List<DataProvider>> genericType = new GenericType<List<DataProvider>>() {
};
return webResource.path("data-providers").accept(defaultMediaType).get(genericType);
}
/**
* Update TimeSeries data from model object
*
* @param timeSeries a TimeSeries object with the data to update.
* @return a TimeSeries object
*/
public TimeSeries updateTimeSeries(TimeSeries timeSeries) {
TimeSeriesDTO timeSeriesDTO = new TimeSeriesDTO(timeSeries);
ClientResponse cr = webResource.path("time-series").type(defaultMediaType).accept(defaultMediaType).
put(ClientResponse.class, timeSeriesDTO);
return cr.getEntity(TimeSeries.class);
}
/**
* Retrieve a Measure by its id.
*
* @param id the Measure's id
* @return
*/
public Measure getMeasure(int id) throws MeasureNotFoundException {
try {
return webResource.path("measure").path(String.valueOf(id)).accept(defaultMediaType).get(Measure.class);
} catch (UniformInterfaceException e) {
throw new MeasureNotFoundException();
}
}
/**
* Update Measure data from model object
*
* @param measure a Measure object with the data to update.
* @return a Measure object
*/
public Measure updateMeasure(Measure measure) {
ClientResponse cr = webResource.path("measure").type(defaultMediaType).accept(defaultMediaType).
put(ClientResponse.class, measure);
return cr.getEntity(Measure.class);
}
/**
* Create Measure data from model object
*
* @param measure a Measure object with the data to create.
* @return a Measure object
*/
public Measure createMeasure(Measure measure) {
//TimeSeriesDTO timeSeriesDTO = new MeasureDTO(timeSeries);
ClientResponse cr = webResource.path("measure").type(defaultMediaType).accept(defaultMediaType).
post(ClientResponse.class, measure);
return cr.getEntity(Measure.class);
}
/**
* Delete Measure data from model object
*
* @param id the Measure's id
* @return a Measure object
*/
public void deleteMeasure(int id) throws MeasureNotFoundException {
try {
webResource.path("measure").path(String.valueOf(id)).type(defaultMediaType).accept(defaultMediaType).
delete(Measure.class);
}
catch (UniformInterfaceException e ) {
System.out.println(e.getResponse());
}
}
/**
* Retrieve a UnitOfMeasure by its id.
*
* @param id the UnitOfMeasure's id
* @return
*/
public UnitOfMeasure getUnitOfMeasure(int id) throws UnitOfMeasureNotFoundException {
try {
return webResource.path("unit-of-measure").path(String.valueOf(id)).accept(defaultMediaType).get(UnitOfMeasure.class);
} catch (UniformInterfaceException e) {
throw new UnitOfMeasureNotFoundException();
}
}
/*
* Unit of measure methods
*/
/**
* Retrieve a list of all the Units of measure.
*
* @return a List with UnitOfMeasure objects
*/
public List<UnitOfMeasure> getUnitsOfMeasure() {
GenericType<List<UnitOfMeasure>> genericType = new GenericType<List<UnitOfMeasure>>() {
};
return webResource.path("units-of-measure").accept(defaultMediaType).get(genericType);
}
/**
* Retrieve a Reference by its id.
*
* @param id the Reference's id
* @return
*/
public Reference getReference(int id) throws ReferenceNotFoundException {
try {
return webResource.path("reference").path(String.valueOf(id)).accept(defaultMediaType).get(Reference.class);
} catch (UniformInterfaceException e) {
throw new ReferenceNotFoundException();
}
}
/**
* Update Reference data from model object
*
* @param reference a Reference object with the data to update.
* @return a Reference object
*/
public Reference updateReference(Reference reference) {
ClientResponse cr = webResource.path("reference").type(defaultMediaType).accept(defaultMediaType).
put(ClientResponse.class, reference);
return cr.getEntity(Reference.class);
}
/**
* Create Reference data from model object
*
* @param reference a Reference object with the data to create.
* @return a Reference object
*/
public Reference createReference(Reference reference) {
//TimeSeriesDTO timeSeriesDTO = new ReferenceDTO(timeSeries);
ClientResponse cr = webResource.path("reference").type(defaultMediaType).accept(defaultMediaType).
post(ClientResponse.class, reference);
return cr.getEntity(Reference.class);
}
/**
* Delete Reference data from model object
*
* @param id the Reference's id
* @return a Reference object
*/
public void deleteReference(int id) throws ReferenceNotFoundException {
try {
webResource.path("reference").path(String.valueOf(id)).type(defaultMediaType).accept(defaultMediaType).
delete(Reference.class);
}
catch (UniformInterfaceException e ) {
System.out.println(e.getResponse());
}
}
/**
* Retrieve a Link by its id.
*
* @param id the Link's id
* @return
*/
public Link getLink(int id) throws LinkNotFoundException {
try {
return webResource.path("link").path(String.valueOf(id)).accept(defaultMediaType).get(Link.class);
} catch (UniformInterfaceException e) {
throw new LinkNotFoundException();
}
}
/**
* Update Link data from model object
*
* @param link a Link object with the data to update.
* @return a Link object
*/
public Link updateLink(Link link) {
ClientResponse cr = webResource.path("link").type(defaultMediaType).accept(defaultMediaType).
put(ClientResponse.class, link);
return cr.getEntity(Link.class);
}
/**
* Create Link data from model object
*
* @param link a Link object with the data to create.
* @return a Link object
*/
public Link createLink(Link link) {
//TimeSeriesDTO timeSeriesDTO = new LinkDTO(timeSeries);
ClientResponse cr = webResource.path("link").type(defaultMediaType).accept(defaultMediaType).
post(ClientResponse.class, link);
return cr.getEntity(Link.class);
}
/**
* Delete Link data from model object
*
* @param id the Link's id
* @return a Link object
*/
public void deleteLink(int id) throws LinkNotFoundException {
try {
webResource.path("link").path(String.valueOf(id)).type(defaultMediaType).accept(defaultMediaType).
delete(Link.class);
}
catch (UniformInterfaceException e ) {
System.out.println(e.getResponse());
}
}
/**
* Retrieve a LinkType by its id.
*
* @param id the LinkType's id
* @return
*/
public LinkType getLinkType(int id) throws LinkTypeNotFoundException {
try {
return webResource.path("link-type").path(String.valueOf(id)).accept(defaultMediaType).get(LinkType.class);
} catch (UniformInterfaceException e) {
throw new LinkTypeNotFoundException();
}
}
/**
* Retrieve a list of all the Link Types.
*
* @return a List with LinkType objects
*/
public List<LinkType> getLinkTypes() {
GenericType<List<LinkType>> genericType = new GenericType<List<LinkType>>() {
};
return webResource.path("link-types").accept(defaultMediaType).get(genericType);
}
}
|
package fr.insee.rmes.api.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class DateUtils {
public static DateTime getDateTimeFromString(String date) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy/MM/dd");
DateTime dt = formatter.parseDateTime(date);
return dt;
}
public static boolean isValidDate(String date) {
if (date == null || !date.matches("\\d{4}/[01]\\d/[0-3]\\d"))
return false;
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
try {
format.parse(date);
return true;
}
catch(ParseException e){
return false;
}
}
}
|
package hudson.plugins.ws_cleanup;
import hudson.FilePath.FileCallable;
import hudson.Util;
import hudson.model.BuildListener;
import hudson.plugins.ws_cleanup.Pattern.PatternType;
import hudson.remoting.VirtualChannel;
import hudson.slaves.EnvironmentVariablesNodeProperty;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.tools.ant.DirectoryScanner;
class Cleanup implements FileCallable<Object> {
private List<Pattern> patterns;
private final boolean deleteDirs;
private String delete_command = null;
private BuildListener listener = null;
public Cleanup(List<Pattern> patterns, boolean deleteDirs, EnvironmentVariablesNodeProperty environment, String command, BuildListener listener) {
this.deleteDirs = deleteDirs;
this.listener = listener;
this.patterns = (patterns == null || patterns.isEmpty()) ? null : patterns;
this.delete_command = (command == null || command.isEmpty()) ? null : command;
if(environment != null) {
this.delete_command = environment.getEnvVars().expand(command);
}
}
public boolean getDeleteDirs() {
return deleteDirs;
}
// Can't use FileCallable<Void> to return void
public Object invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
String temp_command = null;
if (delete_command != null && patterns == null) {
temp_command = delete_command.replaceAll("%s", StringEscapeUtils.escapeJava(f.getPath()));
this.listener.getLogger().println("Using command: " + temp_command);
List<String> list = new ArrayList<String>();
java.util.regex.Pattern p = java.util.regex.Pattern.compile("\"[^\"]+\"|\\S+");
java.util.regex.Matcher m = p.matcher(temp_command);
while(m.find()) {
list.add(m.group().replaceAll("%s", StringEscapeUtils.escapeJava(f.getPath())));
}
Process deletion_proc = new ProcessBuilder(list).start();
InputStream stream = deletion_proc.getErrorStream();
int b = stream.read();
while(b!=-1){
listener.getLogger().print(b);
b=stream.read();
}
return null;
} else {
if(patterns == null) {
patterns = new ArrayList<Pattern>();
patterns.add(new Pattern("**/*", PatternType.INCLUDE));
}
DirectoryScanner ds = new DirectoryScanner();
ds.setBasedir(f);
ArrayList<String> includes = new ArrayList<String>();
ArrayList<String> excludes = new ArrayList<String>();
for (Pattern pattern : patterns) {
if (pattern.getType() == PatternType.INCLUDE) {
includes.add(pattern.getPattern());
} else {
excludes.add(pattern.getPattern());
}
}
//if there is no include pattern, set up ** (all) as include
if (includes.isEmpty()) {
includes.add("**/*");
}
String[] includesArray = new String[(includes.size())];
String[] excludesArray = new String[excludes.size()];
includes.toArray(includesArray);
excludes.toArray(excludesArray);
ds.setIncludes(includesArray);
ds.setExcludes(excludesArray);
ds.scan();
int length = ds.getIncludedFilesCount();
if (deleteDirs) {
length += ds.getIncludedDirsCount();
}
String[] toDelete = new String[length];
System.arraycopy(ds.getIncludedFiles(), 0, toDelete, 0, ds.getIncludedFilesCount());
if (deleteDirs) {
System.arraycopy(ds.getIncludedDirectories(), 0, toDelete, ds.getIncludedFilesCount(), ds.getIncludedDirsCount());
}
for (String path : toDelete) {
if (delete_command != null) {
temp_command = delete_command.replaceAll("%s", "\"" + StringEscapeUtils.escapeJava((new File(f, path)).getPath()) + "\"");
this.listener.getLogger().println("Using command: " + temp_command);
List<String> list = new ArrayList<String>();
java.util.regex.Pattern p = java.util.regex.Pattern.compile("\"[^\"]+\"|\\S+");
java.util.regex.Matcher m = p.matcher(temp_command);
while(m.find()) {
list.add(m.group().replaceAll("%s", StringEscapeUtils.escapeJava(f.getPath())));
}
Process deletion_proc = new ProcessBuilder(list).start();
deletion_proc.waitFor();
} else {
Util.deleteRecursive(new File(f, path));
}
}
return null;
}
}
}
|
package io.yawp.repository.shields;
import io.yawp.repository.IdRef;
import java.util.List;
public abstract class Shield<T> extends ShieldBase<T> {
public void always() {
}
public void index(IdRef<?> parentId) {
}
public void show(IdRef<T> id) {
}
public void create(List<T> objects) {
}
public void update(IdRef<T> id, T object) {
}
public void destroy(IdRef<T> id) {
}
public void custom() {
}
}
|
package javax.time.calendar;
import java.io.Serializable;
import java.util.Map;
import javax.time.calendar.field.DayOfYear;
import javax.time.calendar.field.MonthOfYear;
import javax.time.calendar.field.WeekOfMonth;
import javax.time.calendar.field.WeekOfWeekyear;
import javax.time.calendar.field.Weekyear;
import javax.time.calendar.field.Year;
import javax.time.period.Periods;
/**
* The ISO8601 calendar system, which follows the rules of the current
* <i>de facto</i> world calendar.
* <p>
* ISOChronology follows the rules of the Gregorian calendar for all time.
* Thus, dates is the past, and particularly before 1583, may not correspond
* to historical documents.
* <p>
* ISOChronology is thread-safe and immutable.
*
* @author Michael Nascimento Santos
* @author Stephen Colebourne
*/
public final class ISOChronology implements Serializable {
/**
* The singleton instance of <code>ISOChronology</code>.
*/
public static final ISOChronology INSTANCE = new ISOChronology();
/**
* A serialization identifier for this class.
*/
private static final long serialVersionUID = 1L;
// /** Number of months in one year. */
// private static final int MONTHS_PER_YEAR = 12;
// /** Number of seconds in one day. */
// private static final int SECONDS_PER_DAY = 60 * 60 * 24;
// /** Number of seconds in one hour. */
// private static final int SECONDS_PER_HOUR = 60 * 60;
// /** Number of seconds in one minute. */
// private static final int SECONDS_PER_MINUTE = 60;
// /** The length of months in a standard year. */
// private static final int[] STANDARD_MONTH_LENGTHS = new int[] {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// /** The length of months in a leap year. */
// private static final int[] LEAP_MONTH_LENGTHS = new int[] {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// /** The start of months in a standard year. */
// private static final int[] STANDARD_MONTH_START = new int[] {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
// /** The start of months in a leap year. */
// private static final int[] LEAP_MONTH_START = new int[] {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335};
/**
* Restrictive constructor.
*/
private ISOChronology() {
}
/**
* Resolves singleton.
*
* @return the singleton instance
*/
private Object readResolve() {
return INSTANCE;
}
// /**
// * Checks if the specified year is a leap year.
// * <p>
// * ISO chronology leap years are every 4 years. A special rule applies
// * for years divisible by 100, which are only leap if also divisible by 400.
// *
// * @param year the year to check
// * @return true if the year is a leap year
// */
// private boolean isLeapYear(int year) {
// return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0);
/**
* Gets the name of the chronology.
*
* @return the name of the chronology, never null
*/
public String getName() {
return "ISO";
}
// /**
// * Gets the calendrical state from year, month, day.
// *
// * @param year the year
// * @param month the month of year
// * @param day the day of month
// * @return the state, never null
// */
// public CalendricalState stateFromYearMonthDay(int year, int month, int day) {
// year--;
// month--;
// day--;
// long epochMonths = year;
// epochMonths *= 13 + month;
// long epochSeconds = ((long) day) * 24 * 60 * 60;
// return new State(epochMonths, epochSeconds);
// /**
// * Validates the date from a year, month and day.
// *
// * @param year the year
// * @param monthOfYear the month of year
// * @param dayOfMonth the day of month
// * @return true if valid
// */
// public boolean validateDate(int year, int monthOfYear, int dayOfMonth) {
// if (year == Integer.MIN_VALUE) {
// return false;
// if (monthOfYear < 1 || monthOfYear > 12) {
// return false;
// if (dayOfMonth < 1 || dayOfMonth > 28) {
// int length = MonthOfYear.monthOfYear(monthOfYear).lengthInDays(Year.isoYear(year));
// if (dayOfMonth < 1 || dayOfMonth > length) {
// return false;
// return true;
// public void checkValidDate(Year year, MonthOfYear monthOfYear, DayOfMonth dayOfMonth) {
// if (year == null) {
// throw new NullPointerException("Year must not be null");
// if (monthOfYear == null) {
// throw new NullPointerException("MonthOfYear must not be null");
// if (dayOfMonth == null) {
// throw new NullPointerException("DayOfMonth must not be null");
// if (dayOfMonth.isValid(year, monthOfYear) == false) {
// public void checkValidDate(int year, int monthOfYear, int dayOfMonth) {
// if (year == Integer.MIN_VALUE) {
// if (monthOfYear < 1 || monthOfYear > 12) {
// if (dayOfMonth < 1 || dayOfMonth > 28) {
// int length = MonthOfYear.monthOfYear(monthOfYear).lengthInDays(Year.isoYear(year));
// if (dayOfMonth < 1 || dayOfMonth > length) {
// /**
// * Gets the day of year from a year, month and day.
// *
// * @param year the year, must be valid, must be valid
// * @param monthOfYear the month of year, from 1 to 12, must be valid
// * @return the length of the month in days
// */
// int getMonthLength(int year, int monthOfYear) {
// if (isLeapYear(year)) {
// return LEAP_MONTH_LENGTHS[monthOfYear - 1];
// } else {
// return STANDARD_MONTH_LENGTHS[monthOfYear - 1];
// /**
// * Gets the day of year from a year, month and day.
// *
// * @param year the year, must be valid, must be valid
// * @param monthOfYear the month of year, from 1 to 12, must be valid
// * @param dayOfMonth the day of month, from 1 to 31, must be valid
// * @return the day of year, from 1 to 366
// */
// int getDayOfYear(Year year, MonthOfYear monthOfYear, DayOfMonth dayOfMonth) {
// if (year.isLeap()) {
// return LEAP_MONTH_START[monthOfYear.ordinal()] + dayOfMonth.getValue();
// } else {
// return STANDARD_MONTH_START[monthOfYear.ordinal()] + dayOfMonth.getValue();
// /**
// * Gets the day of week from a year, month and day.
// *
// * @param year the year, must be valid, must be valid
// * @param monthOfYear the month of year, from 1 to 12, must be valid
// * @param dayOfMonth the day of month, from 1 to 31, must be valid
// * @return the day of week, from 1 to 7
// */
// int getDayOfWeek(int year, int monthOfYear, int dayOfMonth) {
// return 1;
// /**
// * Gets the calendrical state from year, month, day.
// *
// * @param year the year
// * @param month the month of year
// * @param day the day of month
// * @return the state, never null
// */
// public long convert(long amount, PeriodUnit fromUnit, PeriodUnit toUnit) {
// return 0;
/**
* Gets the rule for the year field in the ISO chronology.
*
* @return the rule for the year field, never null
*/
public DateTimeFieldRule year() {
return YearRule.INSTANCE;
}
/**
* Gets the rule for the month of year field in the ISO chronology.
*
* @return the rule for the month of year field, never null
*/
public DateTimeFieldRule monthOfYear() {
return MonthOfYearRule.INSTANCE;
}
/**
* Gets the rule for the day of month field in the ISO chronology.
*
* @return the rule for the day of month field, never null
*/
public DateTimeFieldRule dayOfMonth() {
return DayOfMonthRule.INSTANCE;
}
/**
* Gets the rule for the day of year field in the ISO chronology.
*
* @return the rule for the day of year field, never null
*/
public DateTimeFieldRule dayOfYear() {
return DayOfYearRule.INSTANCE;
}
/**
* Gets the rule for the week-based-year field in the ISO chronology.
*
* @return the rule for the week-based-year field, never null
*/
public DateTimeFieldRule weekyear() {
return WeekyearRule.INSTANCE;
}
/**
* Gets the rule for the week of week-based-year field in the ISO chronology.
*
* @return the rule for the week of week-based-year field, never null
*/
public DateTimeFieldRule weekOfWeekyear() {
return WeekOfWeekyearRule.INSTANCE;
}
/**
* Gets the rule for the day of week field.
*
* @return the rule for the day of week field, never null
*/
public DateTimeFieldRule dayOfWeek() {
return DayOfWeekRule.INSTANCE;
}
/**
* Gets the rule for the week of year field in the ISO chronology.
*
* @return the rule for the week of year field, never null
*/
public DateTimeFieldRule weekOfYear() {
return WeekOfYearRule.INSTANCE;
}
/**
* Gets the rule for the quarter of year field in the ISO chronology.
*
* @return the rule for the quarter of year field, never null
*/
public DateTimeFieldRule quarterOfYear() {
return QuarterOfYearRule.INSTANCE;
}
/**
* Gets the rule for the month of quarter field in the ISO chronology.
*
* @return the rule for the month of quarter field, never null
*/
public DateTimeFieldRule monthOfQuarter() {
return MonthOfQuarterRule.INSTANCE;
}
/**
* Gets the rule for the week of month field in the ISO chronology.
*
* @return the rule for the week of month field, never null
*/
public DateTimeFieldRule weekOfMonth() {
return WeekOfMonthRule.INSTANCE;
}
/**
* Gets the rule for the hour of day field.
*
* @return the rule for the hour of day field, never null
*/
public DateTimeFieldRule hourOfDay() {
return HourOfDayRule.INSTANCE;
}
/**
* Gets the rule for the minute of hour field.
*
* @return the rule for the minute of hour field, never null
*/
public DateTimeFieldRule minuteOfHour() {
return MinuteOfHourRule.INSTANCE;
}
/**
* Gets the rule for the second of minute field.
*
* @return the rule for the second of minute field, never null
*/
public DateTimeFieldRule secondOfMinute() {
return SecondOfMinuteRule.INSTANCE;
}
/**
* Gets the rule for the nano of second field.
*
* @return the rule for the nano of second field, never null
*/
public DateTimeFieldRule nanoOfSecond() {
return NanoOfSecondRule.INSTANCE;
}
/**
* A debugging description of this class.
*
* @return a string form for debugging, never null
*/
@Override
public String toString() {
return "ISOChronology";
}
/**
* Rule implementation.
*/
private static final class YearRule extends DateTimeFieldRule implements Serializable {
/** Singleton instance. */
private static final DateTimeFieldRule INSTANCE = new YearRule();
/** A serialization identifier for this class. */
private static final long serialVersionUID = 1L;
/** Constructor. */
private YearRule() {
super("Year", Periods.YEARS, Periods.FOREVER, Year.MIN_YEAR, Year.MAX_YEAR);
}
private Object readResolve() {
return INSTANCE;
}
/** {@inheritDoc} */
@Override
protected Integer extractValue(FlexiDateTime dateTime) {
return dateTime.getDate() != null ? dateTime.getDate().getYear().getValue() : null;
}
}
/**
* Rule implementation.
*/
private static final class MonthOfYearRule extends DateTimeFieldRule implements Serializable {
/** Singleton instance. */
private static final DateTimeFieldRule INSTANCE = new MonthOfYearRule();
/** A serialization identifier for this class. */
private static final long serialVersionUID = 1L;
/** Constructor. */
private MonthOfYearRule() {
super("MonthOfYear", Periods.MONTHS, Periods.YEARS, 1, 12);
}
private Object readResolve() {
return INSTANCE;
}
/** {@inheritDoc} */
@Override
protected Integer extractValue(FlexiDateTime dateTime) {
return dateTime.getDate() != null ? dateTime.getDate().getMonthOfYear().getValue() : null;
}
}
/**
* Rule implementation.
*/
private static final class DayOfMonthRule extends DateTimeFieldRule implements Serializable {
/** Singleton instance. */
private static final DateTimeFieldRule INSTANCE = new DayOfMonthRule();
/** A serialization identifier for this class. */
private static final long serialVersionUID = 1L;
/** Constructor. */
private DayOfMonthRule() {
super("DayOfMonth", Periods.DAYS, Periods.MONTHS, 1, 31);
}
private Object readResolve() {
return INSTANCE;
}
/** {@inheritDoc} */
@Override
public int getSmallestMaximumValue() {
return 28;
}
/** {@inheritDoc} */
@Override
protected Integer extractValue(FlexiDateTime dateTime) {
return dateTime.getDate() != null ? dateTime.getDate().getDayOfMonth().getValue() : null;
}
/** {@inheritDoc} */
@Override
protected FlexiDateTime mergeFields(FlexiDateTime dateTime) {
int domValue = dateTime.getValue(this);
if (dateTime.getDate() == null) {
Map<DateTimeFieldRule, Integer> map = dateTime.getFieldValueMap();
map.remove(this);
Integer year = map.remove(Year.rule());
Integer month = map.remove(MonthOfYear.rule());
if (year != null && month != null) {
LocalDate date = LocalDate.date(year, month, domValue);
return dateTime.withFieldValueMap(map).withDate(date);
}
}
return dateTime;
}
}
/**
* Rule implementation.
*/
private static final class DayOfYearRule extends DateTimeFieldRule implements Serializable {
/** Singleton instance. */
private static final DateTimeFieldRule INSTANCE = new DayOfYearRule();
/** A serialization identifier for this class. */
private static final long serialVersionUID = 1L;
/** Constructor. */
private DayOfYearRule() {
super("DayOfYear", Periods.DAYS, Periods.YEARS, 1, 366);
}
private Object readResolve() {
return INSTANCE;
}
/** {@inheritDoc} */
@Override
public int getSmallestMaximumValue() {
return 365;
}
/** {@inheritDoc} */
@Override
protected Integer extractValue(FlexiDateTime dateTime) {
return dateTime.getDate() != null ? dateTime.getDate().getDayOfYear().getValue() : null;
}
/** {@inheritDoc} */
@Override
protected FlexiDateTime mergeFields(FlexiDateTime dateTime) {
int doyValue = dateTime.getValue(this);
if (dateTime.getDate() == null) {
Map<DateTimeFieldRule, Integer> map = dateTime.getFieldValueMap();
map.remove(this);
Integer year = map.remove(Year.rule());
if (year != null) {
DayOfYear doy = DayOfYear.dayOfYear(doyValue);
LocalDate date = doy.createDate(Year.isoYear(year));
return dateTime.withFieldValueMap(map).withDate(date);
}
}
return dateTime;
}
}
/**
* Rule implementation.
*/
private static final class WeekyearRule extends DateTimeFieldRule implements Serializable {
/** Singleton instance. */
private static final DateTimeFieldRule INSTANCE = new WeekyearRule();
/** A serialization identifier for this class. */
private static final long serialVersionUID = 1L;
/** Constructor. */
private WeekyearRule() {
super("Weekyear", Periods.YEARS, Periods.FOREVER, Weekyear.MIN_YEAR, Weekyear.MAX_YEAR);
}
private Object readResolve() {
return INSTANCE;
}
/** {@inheritDoc} */
@Override
protected Integer extractValue(FlexiDateTime dateTime) {
return dateTime.getDate() != null ? Weekyear.weekyear(dateTime.getDate()).getValue() : null;
}
}
/**
* Rule implementation.
*/
private static final class WeekOfWeekyearRule extends DateTimeFieldRule implements Serializable {
/** Singleton instance. */
private static final DateTimeFieldRule INSTANCE = new WeekOfWeekyearRule();
/** A serialization identifier for this class. */
private static final long serialVersionUID = 1L;
/** Constructor. */
private WeekOfWeekyearRule() {
super("WeekOfWeekyear", Periods.WEEKS, Periods.YEARS, 1, 53);
}
private Object readResolve() {
return INSTANCE;
}
/** {@inheritDoc} */
@Override
public int getSmallestMaximumValue() {
return 52;
}
/** {@inheritDoc} */
@Override
protected Integer extractValue(FlexiDateTime dateTime) {
return dateTime.getDate() != null ? WeekOfWeekyear.weekOfWeekyear(dateTime.getDate()).getValue() : null;
}
}
/**
* Rule implementation.
*/
private static final class DayOfWeekRule extends DateTimeFieldRule implements Serializable {
/** Singleton instance. */
private static final DateTimeFieldRule INSTANCE = new DayOfWeekRule();
/** A serialization identifier for this class. */
private static final long serialVersionUID = 1L;
/** Constructor. */
private DayOfWeekRule() {
super("DayOfWeek", Periods.DAYS, Periods.WEEKS, 1, 7);
}
private Object readResolve() {
return INSTANCE;
}
/** {@inheritDoc} */
@Override
protected Integer extractValue(FlexiDateTime dateTime) {
return dateTime.getDate() != null ? dateTime.getDate().getDayOfWeek().getValue() : null;
}
}
/**
* Rule implementation.
*/
private static final class WeekOfYearRule extends DateTimeFieldRule implements Serializable {
/** Singleton instance. */
private static final DateTimeFieldRule INSTANCE = new WeekOfYearRule();
/** A serialization identifier for this class. */
private static final long serialVersionUID = 1L;
/** Constructor. */
private WeekOfYearRule() {
super("WeekOfYear", Periods.WEEKS, Periods.YEARS, 1, 53);
}
private Object readResolve() {
return INSTANCE;
}
/** {@inheritDoc} */
@Override
public int getSmallestMaximumValue() {
return 52;
}
/** {@inheritDoc} */
@Override
protected Integer extractValue(FlexiDateTime dateTime) {
LocalDate date = dateTime.getDate();
if (date != null) {
return ((date.getDayOfYear().getValue() - 1) % 7) + 1;
}
return null;
}
}
/**
* Rule implementation.
*/
private static final class QuarterOfYearRule extends DateTimeFieldRule implements Serializable {
/** Singleton instance. */
private static final DateTimeFieldRule INSTANCE = new QuarterOfYearRule();
/** A serialization identifier for this class. */
private static final long serialVersionUID = 1L;
/** Constructor. */
private QuarterOfYearRule() {
super("QuarterOfYear", Periods.WEEKS, Periods.YEARS, 1, 4);
}
private Object readResolve() {
return INSTANCE;
}
/** {@inheritDoc} */
@Override
protected Integer extractValue(FlexiDateTime dateTime) {
return dateTime.getDate() != null ? dateTime.getDate().getMonthOfYear().getQuarterOfYear().getValue() : null;
}
}
/**
* Rule implementation.
*/
private static final class MonthOfQuarterRule extends DateTimeFieldRule implements Serializable {
/** Singleton instance. */
private static final DateTimeFieldRule INSTANCE = new MonthOfQuarterRule();
/** A serialization identifier for this class. */
private static final long serialVersionUID = 1L;
/** Constructor. */
private MonthOfQuarterRule() {
super("MonthOfQuarter", Periods.WEEKS, Periods.YEARS, 1, 4);
}
private Object readResolve() {
return INSTANCE;
}
/** {@inheritDoc} */
@Override
protected Integer extractValue(FlexiDateTime dateTime) {
return dateTime.getDate() != null ? dateTime.getDate().getMonthOfYear().getMonthOfQuarter() : null;
}
/** {@inheritDoc} */
@Override
protected FlexiDateTime mergeFields(FlexiDateTime dateTime) {
int moq = dateTime.getValue(this);
if (dateTime.getDate() == null) {
Map<DateTimeFieldRule, Integer> map = dateTime.getFieldValueMap();
map.remove(this);
Integer qoyObj = map.remove(ISOChronology.INSTANCE.quarterOfYear());
if (qoyObj != null) {
int qoy = dateTime.getValue(ISOChronology.INSTANCE.quarterOfYear()); // cross-check value
int moy = (qoy - 1) * 3 + moq;
Integer existingMoy = map.get(MonthOfYear.rule());
if (existingMoy != null && existingMoy != moy) {
throw new IllegalCalendarFieldValueException(
"Merge of Month of Quarter and Quarter of Year created value " +
moy + " that does not match the existing Month of Year value " + existingMoy);
}
map.put(MonthOfYear.rule(), moy);
return dateTime.withFieldValueMap(map);
}
}
return dateTime;
}
}
/**
* Rule implementation.
*/
private static final class WeekOfMonthRule extends DateTimeFieldRule implements Serializable {
/** Singleton instance. */
private static final DateTimeFieldRule INSTANCE = new WeekOfMonthRule();
/** A serialization identifier for this class. */
private static final long serialVersionUID = 1L;
/** Constructor. */
private WeekOfMonthRule() {
super("WeekOfMonth", Periods.WEEKS, Periods.YEARS, 1, 5);
}
private Object readResolve() {
return INSTANCE;
}
/** {@inheritDoc} */
@Override
public int getSmallestMaximumValue() {
return 4;
}
/** {@inheritDoc} */
@Override
protected Integer extractValue(FlexiDateTime dateTime) {
return dateTime.getDate() != null ? WeekOfMonth.weekOfMonth(dateTime.getDate()).getValue() : null;
}
}
/**
* Rule implementation.
*/
private static final class HourOfDayRule extends DateTimeFieldRule implements Serializable {
/** Singleton instance. */
private static final DateTimeFieldRule INSTANCE = new HourOfDayRule();
/** A serialization identifier for this class. */
private static final long serialVersionUID = 1L;
/** Constructor. */
private HourOfDayRule() {
super("HourOfDay", Periods.HOURS, Periods.DAYS, 0, 23);
}
private Object readResolve() {
return INSTANCE;
}
/** {@inheritDoc} */
@Override
protected Integer extractValue(FlexiDateTime dateTime) {
return dateTime.getTime() != null ? dateTime.getTime().getHourOfDay().getValue() : null;
}
/** {@inheritDoc} */
@Override
protected FlexiDateTime mergeFields(FlexiDateTime dateTime) {
int hour = dateTime.getValue(this);
if (dateTime.getTime() == null) {
Map<DateTimeFieldRule, Integer> map = dateTime.getFieldValueMap();
map.remove(this);
Integer minute = map.remove(ISOChronology.INSTANCE.minuteOfHour());
Integer second = map.remove(ISOChronology.INSTANCE.secondOfMinute());
Integer nano = map.remove(ISOChronology.INSTANCE.nanoOfSecond());
LocalTime time = LocalTime.time(hour, minute == null ? 0 : minute,
second == null ? 0 : second, nano == null ? 0 : nano);
return dateTime.withFieldValueMap(map).withTime(time);
}
return dateTime;
}
}
/**
* Rule implementation.
*/
private static final class MinuteOfHourRule extends DateTimeFieldRule implements Serializable {
/** Singleton instance. */
private static final DateTimeFieldRule INSTANCE = new MinuteOfHourRule();
/** A serialization identifier for this class. */
private static final long serialVersionUID = 1L;
/** Constructor. */
private MinuteOfHourRule() {
super("MinuteOfHour", Periods.MINUTES, Periods.HOURS, 0, 59);
}
private Object readResolve() {
return INSTANCE;
}
/** {@inheritDoc} */
@Override
protected Integer extractValue(FlexiDateTime dateTime) {
return dateTime.getTime() != null ? dateTime.getTime().getMinuteOfHour().getValue() : null;
}
}
/**
* Rule implementation.
*/
private static final class SecondOfMinuteRule extends DateTimeFieldRule implements Serializable {
/** Singleton instance. */
private static final DateTimeFieldRule INSTANCE = new SecondOfMinuteRule();
/** A serialization identifier for this class. */
private static final long serialVersionUID = 1L;
/** Constructor. */
private SecondOfMinuteRule() {
super("SecondOfMinute", Periods.SECONDS, Periods.MINUTES, 0, 59);
}
private Object readResolve() {
return INSTANCE;
}
/** {@inheritDoc} */
@Override
protected Integer extractValue(FlexiDateTime dateTime) {
return dateTime.getTime() != null ? dateTime.getTime().getSecondOfMinute().getValue() : null;
}
}
/**
* Rule implementation.
*/
private static final class NanoOfSecondRule extends DateTimeFieldRule implements Serializable {
/** Singleton instance. */
private static final DateTimeFieldRule INSTANCE = new NanoOfSecondRule();
/** A serialization identifier for this class. */
private static final long serialVersionUID = 1L;
/** Constructor. */
private NanoOfSecondRule() {
super("NanoOfSecond", Periods.NANOS, Periods.SECONDS, 0, 999999999);
}
private Object readResolve() {
return INSTANCE;
}
/** {@inheritDoc} */
@Override
protected Integer extractValue(FlexiDateTime dateTime) {
return dateTime.getTime() != null ? dateTime.getTime().getNanoOfSecond().getValue() : null;
}
}
// /**
// * Rule implementation.
// */
// private static enum Rule implements Serializable {
// /** Year instance. */
// YEAR("Year", Periods.YEARS, Periods.FOREVER, Year.MIN_YEAR, Year.MAX_YEAR),
// /** Year instance. */
// MONTH_OF_YEAR("MonthOfYear", Periods.MONTHS, Periods.YEARS, 1, 12),
// /** Year instance. */
// DAY_OF_MONTH("DayOfMonth", Periods.DAYS, Periods.MONTHS, 1, 31);
// /** The name of the rule, not null. */
// private final String name;
// /** The period unit, not null. */
// private final PeriodUnit periodUnit;
// /** The period range, not null. */
// private final PeriodUnit periodRange;
// /** The minimum value for the field. */
// private final int minimumValue;
// /** The maximum value for the field. */
// private final int maximumValue;
// /**
// * Constructor.
// *
// * @param name the name of the type, not null
// * @param periodUnit the period unit, not null
// * @param periodRange the period range, not null
// * @param minimumValue the minimum value
// * @param maximumValue the minimum value
// */
// private Rule(
// String name,
// PeriodUnit periodUnit,
// PeriodUnit periodRange,
// int minimumValue,
// int maximumValue) {
// this.name = name;
// this.periodUnit = periodUnit;
// this.periodRange = periodRange;
// this.minimumValue = minimumValue;
// this.maximumValue = maximumValue;
// /**
// * Gets the name of the time field type.
// * <p>
// * Subclasses should use the form 'UnitOfRange' whenever possible.
// *
// * @return the name of the time field type, never null
// */
// public String getName() {
// return name;
// /**
// * Gets the period unit, which the element which alters within the range.
// * <p>
// * In the phrase 'hour of day', the unit is the hour.
// *
// * @return the rule for the unit period, never null
// */
// public PeriodUnit getPeriodUnit() {
// return periodUnit;
// /**
// * Gets the period range, which the field is bound by.
// * <p>
// * In the phrase 'hour of day', the range is the day.
// *
// * @return the rule for the range period, never null
// */
// public PeriodUnit getPeriodRange() {
// return periodRange;
// /**
// * Checks if the this field is supported using calendrical data that is
// * completely specified by the unit and range.
// * <p>
// * For example, a date object has a unit of days and a range of forever.
// * If this field is for hour of day, then that cannot be supported by the
// * unit and range from a date object.
// *
// * @param unit the unit to check, not null
// * @param range the range to check, not null
// * @return true if the field is supported
// */
// public boolean isSupported(PeriodUnit unit, PeriodUnit range) {
// return (periodUnit.compareTo(unit) >= 0) &&
// (periodRange.compareTo(range) < 0);
// /**
// * Gets the value of this field.
// *
// * @param dateTime the date time, not null
// * @return the value of the field
// * @throws UnsupportedCalendarFieldException if the value cannot be extracted
// */
// public int getValue(FlexiDateTime dateTime) {
// switch (this) {
// case YEAR:
// return dateTime.getDate().getYear().getValue();
// default:
// throw new UnsupportedCalendarFieldException(this, "FlexiDateTime");
// public void checkValue(int value) {
// if (value < getMinimumValue() || value > getMaximumValue()) {
// /**
// * Is the set of values, from the minimum value to the maximum, a fixed
// * set, or does it vary according to other fields.
// *
// * @return true if the set of values is fixed
// */
// public boolean isFixedValueSet() {
// return getMaximumValue() == getSmallestMaximumValue() &&
// getMinimumValue() == getLargestMinimumValue();
// /**
// * Gets the minimum value that the field can take.
// *
// * @return the minimum value for this field
// */
// public int getMinimumValue() {
// return minimumValue;
// /**
// * Gets the largest possible minimum value that the field can take.
// *
// * @return the largest possible minimum value for this field
// */
// public int getLargestMinimumValue() {
// return getMinimumValue();
//// /**
//// * Gets the minimum value that the field can take using the specified
//// * calendrical information to refine the accuracy of the response.
//// *
//// * @param calendricalContext context datetime, null returns getMinimumValue()
//// * @return the minimum value of the field given the context
//// */
//// public int getMinimumValue(Calendrical calendricalContext) {
//// return getMinimumValue();
//// /**
//// * Gets the largest possible minimum value that the field can take using
//// * the specified calendrical information to refine the accuracy of the response.
//// *
//// * @param calendricalContext context datetime, null returns getLargestMinimumValue()
//// * @return the largest possible minimum value of the field given the context
//// */
//// public int getLargestMinimumValue(Calendrical calendricalContext) {
//// if (calendricalContext == null) {
//// return getLargestMinimumValue();
//// return getMinimumValue(calendricalContext);
// /**
// * Gets the maximum value that the field can take.
// *
// * @return the maximum value for this field
// */
// public int getMaximumValue() {
// return maximumValue;
// /**
// * Gets the smallest possible maximum value that the field can take.
// *
// * @return the smallest possible maximum value for this field
// */
// public int getSmallestMaximumValue() {
// return getMaximumValue();
//// /**
//// * Gets the maximum value that the field can take using the specified
//// * calendrical information to refine the accuracy of the response.
//// *
//// * @param calendricalContext context datetime, null returns getMaximumValue()
//// * @return the maximum value of the field given the context
//// */
//// public int getMaximumValue(Calendrical calendricalContext) {
//// return getMaximumValue();
//// /**
//// * Gets the smallest possible maximum value that the field can take using
//// * the specified calendrical information to refine the accuracy of the response.
//// *
//// * @param calendricalContext context datetime, null returns getSmallestMaximumValue()
//// * @return the smallest possible maximum value of the field given the context
//// */
//// public int getSmallestMaximumValue(Calendrical calendricalContext) {
//// if (calendricalContext == null) {
//// return getSmallestMaximumValue();
//// return getMaximumValue(calendricalContext);
//// /**
//// * Checks whether a given calendrical is supported or not.
//// *
//// * @param calState the calendar state to check, not null
//// * @throws UnsupportedCalendarFieldException if the field is unsupported
//// */
//// protected void checkSupported(CalendricalState calState) {
//// if (calState.getPeriodUnit().compareTo(getPeriodUnit()) > 0 ||
//// calState.getPeriodRange().compareTo(getPeriodRange()) < 0) {
//// throw new UnsupportedCalendarFieldException("Calendar field " + getName() + " cannot be queried");
// /**
// * Compares this TimeFieldRule to another based on the period unit
// * followed by the period range.
// * <p>
// * The period unit is compared first, so MinuteOfHour will be less than
// * HourOfDay, which will be less than DayOfWeek. When the period unit is
// * the same, the period range is compared, so DayOfWeek is less than
// * DayOfMonth, which is less than DayOfYear.
// *
// * @param other the other type to compare to, not null
// * @return the comparator result, negative if less, postive if greater, zero if equal
// * @throws NullPointerException if other is null
// */
// public int compareTo(DateTimeFieldRule other) {
// int cmp = this.getPeriodUnit().compareTo(other.getPeriodUnit());
// if (cmp != 0) {
// return cmp;
// return this.getPeriodRange().compareTo(other.getPeriodRange());
// /**
// * Returns a string representation of the rule.
// *
// * @return a description of the rule
// */
// @Override
// public String toString() {
// return getName();
}
|
package mingzuozhibi.config;
import mingzuozhibi.persist.disc.Disc;
import mingzuozhibi.persist.disc.Sakura;
import mingzuozhibi.service.AmazonDiscSpider;
import mingzuozhibi.service.AmazonNewDiscSpider;
import mingzuozhibi.service.ScheduleMission;
import mingzuozhibi.support.Dao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Comparator;
import static java.util.Comparator.comparing;
import static java.util.Comparator.nullsFirst;
@Service
@RestController
public class AutoRunConfig {
public static final Logger LOGGER = LoggerFactory.getLogger(AutoRunConfig.class);
@Autowired
private ScheduleMission scheduleMission;
@Autowired
private AmazonDiscSpider amazonDiscSpider;
@Autowired
private AmazonNewDiscSpider amazonNewDiscSpider;
@Value("${BCLOUD_IP}")
private String japanServerIp;
/**
* call by MzzbServerApplication
*/
public void runOnStartupServer() {
scheduleMission.removeExpiredAutoLoginData();
scheduleMission.recordDiscsRankAndComputePt();
}
@Scheduled(cron = "0 2 * * * ?")
public void runOnEveryHour() {
LOGGER.info("");
scheduleMission.removeExpiredAutoLoginData();
scheduleMission.recordDiscsRankAndComputePt();
LOGGER.info("");
}
@GetMapping("/requestNewDiscs")
@Scheduled(cron = "0 0,20 0/6 * * ?")
public void fetchNewDiscs() {
amazonNewDiscSpider.fetchFromJapan(japanServerIp);
}
@GetMapping("/requestDiscRanks")
@Scheduled(cron = "0 4/5 * * * ?")
public void fetchDiscRanks() {
new Thread(() -> {
amazonDiscSpider.fetchFromBCloud();
}).start();
}
}
|
package mytown.protection.segment;
import com.google.common.reflect.TypeToken;
import com.google.gson.*;
import com.google.gson.internal.LazilyParsedNumber;
import myessentials.entities.Volume;
import myessentials.json.SerializerTemplate;
import mytown.MyTown;
import mytown.new_datasource.MyTownUniverse;
import mytown.entities.*;
import mytown.entities.flag.FlagType;
import mytown.protection.ProtectionManager;
import mytown.protection.segment.enums.BlockType;
import mytown.protection.segment.enums.EntityType;
import mytown.protection.segment.enums.ItemType;
import mytown.protection.segment.enums.Priority;
import mytown.protection.segment.getter.Getter;
import mytown.util.exceptions.ConditionException;
import mytown.util.exceptions.GetterException;
import mytown.util.exceptions.ProtectionParseException;
import net.minecraft.entity.player.EntityPlayer;
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.lang.reflect.Type;
import java.util.*;
/**
* A part of the protection that protects against a specific thing.
*/
public abstract class Segment {
protected boolean isDisabled = false;
protected Priority priority = Priority.NORMAL;
protected Class<?> checkClass;
protected Condition condition;
protected final List<FlagType<Boolean>> flags = new ArrayList<FlagType<Boolean>>();
protected final Getter.Container getters = new Getter.Container();
public boolean isDisabled() {
return isDisabled;
}
public boolean shouldCheckType(Class<?> clazz) {
return checkClass.isAssignableFrom(clazz);
}
public Class<?> getCheckClass() {
return this.checkClass;
}
public Priority getPriority() {
return this.priority;
}
public Resident getOwner(Object object) {
try {
EntityPlayer player = getters.contains("owner") ? (EntityPlayer) getters.get("owner").invoke(EntityPlayer.class, object, object) : null;
if(player == null)
return null;
return MyTownUniverse.instance.getOrMakeResident(player);
} catch (GetterException ex) {
try {
String username = getters.contains("owner") ? (String) getters.get("owner").invoke(String.class, object, object) : null;
if (username == null)
return null;
return MyTownUniverse.instance.getOrMakeResident(username);
} catch (GetterException ex2) {
try {
UUID uuid = getters.contains("owner") ? (UUID) getters.get("owner").invoke(UUID.class, object, object) : null;
if (uuid == null)
return null;
return MyTownUniverse.instance.getOrMakeResident(uuid);
} catch (GetterException ex3) {
return null;
}
}
}
}
protected boolean hasPermissionAtLocation(Resident res, int dim, int x, int y, int z) {
for(FlagType<Boolean> flagType : flags) {
if(!ProtectionManager.hasPermission(res, flagType, dim, x, y, z)) {
return false;
}
}
return true;
}
protected boolean hasPermissionAtLocation(Resident res, int dim, Volume volume) {
for (FlagType<Boolean> flagType : flags) {
if(!ProtectionManager.hasPermission(res, flagType, dim, volume)) {
return false;
}
}
return true;
}
protected boolean shouldCheck(Object object) {
try {
if (condition != null && !condition.execute(object, getters)) {
return false;
}
} catch (GetterException ex) {
MyTown.instance.LOG.error("Encountered error when checking condition for {}", checkClass.getSimpleName());
MyTown.instance.LOG.error(ExceptionUtils.getStackTrace(ex));
disable();
} catch (ConditionException ex) {
MyTown.instance.LOG.error("Encountered error when checking condition for {}", checkClass.getSimpleName());
MyTown.instance.LOG.error(ExceptionUtils.getStackTrace(ex));
disable();
}
return true;
}
protected int getRange(Object object) {
try {
return getters.contains("range") ? ((LazilyParsedNumber) getters.get("range").invoke(LazilyParsedNumber.class, object, object)).intValue() : 0;
} catch (GetterException ex) {
return 0;
}
}
protected void disable() {
MyTown.instance.LOG.error("Disabling segment for {}", checkClass.getName());
MyTown.instance.LOG.info("Reload protections to enable it again.");
this.isDisabled = true;
}
public static class Serializer extends SerializerTemplate<Segment> {
@Override
public void register(GsonBuilder builder) {
builder.registerTypeAdapter(Segment.class, this);
new Getter.Serializer().register(builder);
new Volume.Serializer().register(builder);
new FlagType.Serializer().register(builder);
}
@Override
public JsonElement serialize(Segment segment, Type typeOfSrc, JsonSerializationContext context) {
JsonObject json = new JsonObject();
json.addProperty("class", segment.checkClass.getName());
if(segment instanceof SegmentBlock) {
json.addProperty("type", "block");
serializeBlock((SegmentBlock) segment, json, context);
} else if(segment instanceof SegmentEntity) {
json.addProperty("type", "entity");
serializeEntity((SegmentEntity) segment, json, context);
} else if(segment instanceof SegmentItem) {
json.addProperty("type", "item");
serializeItem((SegmentItem) segment, json, context);
} else if(segment instanceof SegmentTileEntity) {
json.addProperty("type", "tileEntity");
serializeTileEntity((SegmentTileEntity) segment, json, context);
}
json.add("flags", serializeAsElementOrArray(segment.flags, context));
if(segment.condition != null) {
json.addProperty("condition", segment.condition.toString());
}
if(segment.priority != Priority.NORMAL) {
json.addProperty("priority", segment.priority.toString());
}
for(Getter getter : segment.getters) {
json.add(getter.getName(), context.serialize(getter, Getter.class));
}
return json;
}
private <T> JsonElement serializeAsElementOrArray(List<T> items, JsonSerializationContext context) {
if(items.isEmpty()) {
return null;
}
if(items.size() == 1) {
return context.serialize(items.get(0));
} else {
return context.serialize(items);
}
}
private void serializeBlock(SegmentBlock segment, JsonObject json, JsonSerializationContext context) {
json.add("actions", serializeAsElementOrArray(segment.types, context));
json.addProperty("meta", segment.getMeta());
if(segment.clientUpdate != null) {
JsonObject jsonUpdate = new JsonObject();
jsonUpdate.add("coords", context.serialize(segment.clientUpdate.relativeCoords));
json.add("clientUpdate", jsonUpdate);
}
}
private void serializeEntity(SegmentEntity segment, JsonObject json, JsonSerializationContext context) {
json.add("actions", serializeAsElementOrArray(segment.types, context));
}
private void serializeItem(SegmentItem segment, JsonObject json, JsonSerializationContext context) {
json.add("actions", serializeAsElementOrArray(segment.types, context));
json.addProperty("isAdjacent", segment.isAdjacent);
if(segment.clientUpdate != null) {
JsonObject jsonUpdate = new JsonObject();
jsonUpdate.add("coords", context.serialize(segment.clientUpdate.relativeCoords));
jsonUpdate.addProperty("directional", segment.directionalClientUpdate);
json.add("clientUpdate", jsonUpdate);
}
}
private void serializeTileEntity(SegmentTileEntity segment, JsonObject json, JsonSerializationContext context) {
json.addProperty("retainsOwner", segment.retainsOwner);
}
@Override
public Segment deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if(!json.getAsJsonObject().has("class") || !json.getAsJsonObject().has("type") || !json.getAsJsonObject().has("flags")) {
throw new ProtectionParseException("One of the segments is invalid");
}
JsonObject jsonObject = json.getAsJsonObject();
String type = jsonObject.get("type").getAsString();
jsonObject.remove("type");
Segment segment = null;
if("block".equals(type)) {
segment = deserializeBlock(jsonObject, context);
} else if("entity".equals(type)) {
segment = deserializeEntity(jsonObject, context);
} else if("item".equals(type)) {
segment = deserializeItem(jsonObject, context);
} else if("tileEntity".equals(type)) {
segment = deserializeTileEntity(jsonObject, context);
}
if(segment == null) {
throw new ProtectionParseException("Identifier type is invalid");
}
String classString = jsonObject.get("class").getAsString();
try {
segment.checkClass = Class.forName(classString);
} catch (ClassNotFoundException ex) {
throw new ProtectionParseException("Invalid class identifier: " + classString);
}
jsonObject.remove("class");
segment.flags.addAll(deserializeAsArray(jsonObject.get("flags"), context, new TypeToken<FlagType<Boolean>>() {}, new TypeToken<List<FlagType<Boolean>>>() {}.getType()));
jsonObject.remove("flags");
if(jsonObject.has("condition")) {
segment.condition = new Condition(jsonObject.get("condition").getAsString());
jsonObject.remove("condition");
}
if(jsonObject.has("priority")) {
segment.priority = Priority.valueOf(jsonObject.get("priority").getAsString());
jsonObject.remove("priority");
}
for(Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
Getter getter = context.deserialize(entry.getValue(), Getter.class);
getter.setName(entry.getKey());
segment.getters.add(getter);
}
return segment;
}
private <T> List<T> deserializeAsArray(JsonElement json, JsonDeserializationContext context, TypeToken<T> typeToken, Type listOfT) {
if(json.isJsonPrimitive()) {
List<T> list = new ArrayList<T>();
list.add((T) context.deserialize(json, typeToken.getType()));
return list;
} else {
return context.deserialize(json, listOfT);
}
}
private SegmentBlock deserializeBlock(JsonObject json, JsonDeserializationContext context) {
if(!json.has("actions")) {
throw new ProtectionParseException("Missing actions identifier");
}
SegmentBlock segment = new SegmentBlock();
segment.types.addAll(deserializeAsArray(json.get("actions"), context, new TypeToken<BlockType>() {}, new TypeToken<List<BlockType>>() {}.getType()));
json.remove("actions");
if(json.has("meta")) {
segment.meta = json.get("meta").getAsInt();
json.remove("meta");
}
if(json.has("clientUpdate")) {
segment.clientUpdate = new ClientBlockUpdate((Volume) context.deserialize(json.get("clientUpdate").getAsJsonObject().get("coords"), Volume.class));
json.remove("clientUpdate");
}
return segment;
}
private SegmentEntity deserializeEntity(JsonObject json, JsonDeserializationContext context) {
if(!json.has("actions")) {
throw new ProtectionParseException("Missing actions identifier");
}
SegmentEntity segment = new SegmentEntity();
segment.types.addAll(deserializeAsArray(json.get("actions"), context, new TypeToken<EntityType>() {}, new TypeToken<List<EntityType>>() {}.getType()));
json.remove("actions");
return segment;
}
private SegmentItem deserializeItem(JsonObject json, JsonDeserializationContext context) {
if(!json.has("actions")) {
throw new ProtectionParseException("Missing actions identifier");
}
SegmentItem segment = new SegmentItem();
segment.types.addAll(deserializeAsArray(json.get("actions"), context, new TypeToken<ItemType>() {}, new TypeToken<List<ItemType>>() {}.getType()));
json.remove("actions");
if(json.has("isAdjacent")) {
segment.isAdjacent = json.get("isAdjacent").getAsBoolean();
json.remove("isAdjacent");
}
if(json.has("clientUpdate")) {
JsonObject jsonClientUpdate = json.get("clientUpdate").getAsJsonObject();
segment.clientUpdate = new ClientBlockUpdate((Volume) context.deserialize(jsonClientUpdate.get("coords"), Volume.class));
if(jsonClientUpdate.has("directional")) {
segment.directionalClientUpdate = jsonClientUpdate.get("directional").getAsBoolean();
}
json.remove("clientUpdate");
}
return segment;
}
private SegmentTileEntity deserializeTileEntity(JsonObject json, JsonDeserializationContext context) {
SegmentTileEntity segment = new SegmentTileEntity();
segment.retainsOwner = json.getAsJsonObject().get("retainsOwner").getAsBoolean();
json.remove("retainsOwner");
return segment;
}
private Object getObjectFromPrimitive(JsonPrimitive json) {
if(json.isBoolean()) {
return json.getAsBoolean();
} else if(json.isString()) {
return json.getAsString();
} else if(json.isNumber()) {
return json.getAsNumber();
}
return null;
}
}
public static class Container<T extends Segment> extends ArrayList<T> {
public List<T> get(Class<?> clazz) {
List<T> usableSegments = new ArrayList<T>();
for(Segment segment : this) {
if(!segment.isDisabled() && segment.shouldCheckType(clazz)) {
usableSegments.add((T)segment);
}
}
if(usableSegments.size() > 1) {
Priority highestPriority = Priority.LOWEST;
for(Segment segment : usableSegments) {
if(highestPriority.ordinal() < segment.getPriority().ordinal()) {
highestPriority = segment.getPriority();
}
}
for(Iterator<T> it = usableSegments.iterator(); it.hasNext();) {
Segment segment = it.next();
if(segment.getPriority() != highestPriority) {
it.remove();
}
}
}
return usableSegments;
}
}
}
|
package net.common.utils.config;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class MapConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(MapConfig.class);
private String confPath;
/**
* int,name,
*
* @param name
* @param config
* @param defaultValue
* @return
*/
public static int getInt(@Nonnull String name, @Nullable Map<String, String> config, int defaultValue) {
Preconditions.checkArgument(name != null, "name");
if (config == null) {
return defaultValue;
}
String s = config.get(name);
if (s == null) {
return defaultValue;
}
return Integer.parseInt(s);
}
/**
* byte,name,
*
* @param name
* @param config
* @param defaultValue
* @return
*/
public static byte getByte(@Nonnull String name, @Nullable Map<String, String> config, byte defaultValue) {
Preconditions.checkArgument(name != null, "name");
if (config == null) {
return defaultValue;
}
String s = config.get(name);
if (s == null) {
return defaultValue;
}
return Byte.parseByte(s);
}
/**
* long,name,
*
* @param name
* @param config
* @param defaultValue
* @return
*/
public static long getLong(@Nonnull String name, @Nullable Map<String, String> config, long defaultValue) {
Preconditions.checkArgument(name != null, "name");
if (config == null) {
return defaultValue;
}
String s = config.get(name);
if (s == null) {
return defaultValue;
}
return Long.parseLong(s);
}
/**
* String,name,
*
* @param name
* @param config
* @param defaultValue
* @return
*/
public static String getString(@Nonnull String name, @Nullable Map<String, String> config, String defaultValue) {
Preconditions.checkArgument(name != null, "name");
if (config == null) {
return defaultValue;
}
String s = config.get(name);
if (s == null) {
return defaultValue;
}
return s;
}
/**
* boolean,name,<code>defaultValue</code>
*
* @param name
* @param config
* @param defaultValue
* @return
*/
public static boolean getBoolean(@Nonnull String name, @Nullable Map<String, String> config, boolean defaultValue) {
Preconditions.checkArgument(name != null, "name");
if (config == null) {
return defaultValue;
}
String s = config.get(name);
if (s == null) {
return defaultValue;
}
return Boolean.valueOf(s);
}
public static ImmutableMap<String, String> parseConf(String confPath) {
Map<String, String> all = Maps.newHashMap();
if (confPath != null) {
String[] appConfs = confPath.split(",");
List<String> configList = Lists.newArrayList();
for (final String conf : appConfs) {
if (configList.contains(conf)) {
LOGGER.warn("Found duplicate same config file name: {} ", conf);
continue;
}
configList.add(conf);
LOGGER.info("Load config from " + conf);
Map<String, String> confMap = XmlProp.loadFromXml(conf);
if (confMap != null) {
Set<Map.Entry<String, String>> entries = confMap.entrySet();
for (Map.Entry<String, String> entry : entries) {
String key = entry.getKey();
String s = all.get(key);
if (s != null) {
LOGGER.warn("Found duplicate key {}:{},will be overrided by new value{},config:{}", new Object[]{key, s, entry.getValue(), conf});
}
all.put(key, entry.getValue());
}
}
}
}
return ImmutableMap.<String, String>builder().putAll(all).build();
}
public String getConfPath() {
return confPath;
}
public void setConfPath(String confPath) {
this.confPath = confPath;
}
}
|
package net.malisis.core.util;
/**
* MouseButton
*
* @author PaleoCrafter
*/
public enum MouseButton
{
LEFT(0), RIGHT(1), MIDDLE(2), UNKNOWN(-1);
public static MouseButton[] DEFAULT = { LEFT, RIGHT, MIDDLE };
private int code;
private MouseButton(int code)
{
this.code = code;
}
/**
* Gets the code for this {@link MouseButton}.
*
* @return the code
*/
public int getCode()
{
return code;
}
/**
* Gets the {@link MouseButton} from the event code.
*
* @param id the id
* @return the button
*/
public static MouseButton getButton(int id)
{
if (id < DEFAULT.length && id >= 0)
return DEFAULT[id];
return UNKNOWN;
}
}
|
package net.md_5.specialsource;
import net.md_5.specialsource.util.FileLocator;
import net.md_5.specialsource.transformer.MavenShade;
import net.md_5.specialsource.writer.CompactSearge;
import net.md_5.specialsource.writer.Searge;
import net.md_5.specialsource.writer.MappingWriter;
import net.md_5.specialsource.provider.InheritanceProvider;
import net.md_5.specialsource.transformer.MinecraftCodersPack;
import net.md_5.specialsource.transformer.MethodDescriptor;
import net.md_5.specialsource.transformer.ChainingTransformer;
import net.md_5.specialsource.transformer.MappingTransformer;
import java.io.*;
import java.lang.reflect.Modifier;
import java.util.*;
public class JarMapping {
public final LinkedHashMap<String, String> packages = new LinkedHashMap<String, String>();
public final Map<String, String> classes = new HashMap<String, String>();
public final Map<String, String> fields = new HashMap<String, String>();
public final Map<String, String> methods = new HashMap<String, String>();
private InheritanceMap inheritanceMap = new InheritanceMap();
private InheritanceProvider fallbackInheritanceProvider = null;
private Set<String> excludedPackages = new HashSet<String>();
public JarMapping() {
}
/**
* Set the inheritance map used for caching superclass/interfaces. This call
* be omitted to use a local cache, or set to your own global cache.
*/
public void setInheritanceMap(InheritanceMap inheritanceMap) {
this.inheritanceMap = inheritanceMap;
}
/**
* Set the inheritance provider to be consulted if the inheritance map has
* no information on the requested class (results will be cached in the
* inheritance map).
*/
public void setFallbackInheritanceProvider(InheritanceProvider fallbackInheritanceProvider) {
this.fallbackInheritanceProvider = fallbackInheritanceProvider;
}
/**
* Add a class name prefix to the mapping ignore list. Note: this only
* applies before loading mappings, not after
*/
public void addExcludedPackage(String packageName) {
SpecialSource.log("Protecting Package: " + packageName);
excludedPackages.add(packageName);
}
private boolean isExcludedPackage(String desc) {
for (String packageName : excludedPackages) {
if (desc.startsWith(packageName)) {
return true;
}
}
return false;
}
public String tryClimb(Map<String, String> map, NodeType type, String owner, String name, int access) {
String key = owner + "/" + name;
String mapped = map.get(key);
if (mapped == null && (access == -1 || (!Modifier.isPrivate(access) && !Modifier.isStatic(access)))) {
Collection<String> parents = null;
if (inheritanceMap.hasParents(owner)) {
parents = inheritanceMap.getParents(owner);
} else if (fallbackInheritanceProvider != null) {
parents = fallbackInheritanceProvider.getParents(owner);
inheritanceMap.setParents(owner, parents);
}
if (parents != null) {
// climb the inheritance tree
for (String parent : parents) {
mapped = tryClimb(map, type, parent, name, access);
if (mapped != null) {
return mapped;
}
}
}
}
return mapped;
}
/**
* Load mappings from an MCP directory
*
* @param dirname MCP directory name, local file or remote URL ending in '/'
* @param reverse If true, swap input and output
* @param ignoreCsv If true, ignore fields.csv and methods.csv (but not
* packages.csv)
* @param numericSrgNames If true, load numeric "srg" names (num->mcp
* instead of obf->mcp)
*/
private void loadMappingsDir(String dirname, boolean reverse, boolean ignoreCsv, boolean numericSrgNames) throws IOException {
File dir = new File(dirname);
if (!FileLocator.isHTTPURL(dirname) && !dir.isDirectory()) {
throw new IllegalArgumentException("loadMappingsDir(" + dir + "): not a directory");
}
String sep = System.getProperty("file.separator");
List<File> srgFiles = new ArrayList<File>();
File joinedSrg = FileLocator.getFile(dirname + sep + "joined.srg");
if (joinedSrg.exists()) {
// FML/MCP client/server joined
srgFiles.add(joinedSrg);
} else {
// vanilla MCP separated sides
File serverSrg = FileLocator.getFile(dirname + sep + "server.srg");
File clientSrg = FileLocator.getFile(dirname + sep + "client.srg");
if (serverSrg.exists()) {
srgFiles.add(serverSrg);
}
if (clientSrg.exists()) {
srgFiles.add(clientSrg);
}
}
if (srgFiles.size() == 0) {
throw new IOException("loadMappingsDir(" + dirname + "): no joined.srg, client.srg, or server.srg found");
}
// Read output names through csv mappings, if available & enabled
File fieldsCsv = FileLocator.getFile(dirname + sep + "fields.csv");
File methodsCsv = FileLocator.getFile(dirname + sep + "methods.csv");
File packagesCsv = FileLocator.getFile(dirname + sep + "packages.csv"); // FML repackaging, optional
MinecraftCodersPack outputTransformer;
MappingTransformer inputTransformer;
if (numericSrgNames) {
// Wants numeric "srg" names -> descriptive "csv" names. To accomplish this:
// 1. load obf->mcp (descriptive "csv") as chainMappings
// 2. load again but chaining input (obf) through mcp, and ignoring csv on output
// 3. result: mcp->srg, similar to MCP ./reobfuscate --srgnames
JarMapping chainMappings = new JarMapping();
chainMappings.loadMappingsDir(dirname, reverse, false/*ignoreCsv*/, false/*numeric*/);
inputTransformer = new ChainingTransformer(new JarRemapper(chainMappings));
ignoreCsv = true; // keep numeric srg as output
} else {
inputTransformer = null;
}
if (fieldsCsv.exists() && methodsCsv.exists()) {
outputTransformer = new MinecraftCodersPack(ignoreCsv ? null : fieldsCsv, ignoreCsv ? null : methodsCsv, packagesCsv);
} else {
outputTransformer = null;
}
for (File srg : srgFiles) {
loadMappings(new BufferedReader(new FileReader(srg)), inputTransformer, outputTransformer, reverse);
}
}
public void loadMappings(File file) throws IOException {
loadMappings(new BufferedReader(new FileReader(file)), null, null, false);
}
/**
*
* @param filename A filename of a .srg/.csrg or an MCP directory of
* .srg+.csv, local or remote
* @param reverse Swap input and output mappings
* @param numericSrgNames When reading mapping directory, load numeric "srg"
* instead obfuscated names
* @param inShadeRelocation Apply relocation on mapping input
* @param outShadeRelocation Apply relocation on mapping output
* @throws IOException
*/
public void loadMappings(String filename, boolean reverse, boolean numericSrgNames, String inShadeRelocation, String outShadeRelocation) throws IOException {
// Optional shade relocation, on input or output names
MappingTransformer inputTransformer = null;
MappingTransformer outputTransformer = null;
if (inShadeRelocation != null) {
inputTransformer = new MavenShade(inShadeRelocation);
}
if (outShadeRelocation != null) {
outputTransformer = new MavenShade(outShadeRelocation);
}
if (new File(filename).isDirectory() || filename.endsWith("/")) {
// Existing local dir or dir URL
if (inputTransformer != null || outputTransformer != null) {
throw new IllegalArgumentException("loadMappings(" + filename + "): shade relocation not supported on directories"); // yet
}
loadMappingsDir(filename, reverse, false, numericSrgNames);
} else {
// File
if (numericSrgNames) {
throw new IllegalArgumentException("loadMappings(" + filename + "): numeric only supported on directories, not files");
}
loadMappings(new BufferedReader(new FileReader(FileLocator.getFile(filename))), inputTransformer, outputTransformer, reverse);
}
}
/**
* Load a mapping given a .csrg file
*
* @param reader Mapping file reader
* @param inputTransformer Transformation to apply on input
* @param outputTransformer Transformation to apply on output
* @param reverse Swap input and output mappings (after applying any
* input/output transformations)
* @throws IOException
*/
public void loadMappings(BufferedReader reader, MappingTransformer inputTransformer, MappingTransformer outputTransformer, boolean reverse) throws IOException {
if (inputTransformer == null) {
inputTransformer = MavenShade.IDENTITY;
}
if (outputTransformer == null) {
outputTransformer = MavenShade.IDENTITY;
}
String line;
while ((line = reader.readLine()) != null) {
int commentIndex = line.indexOf('
if (commentIndex != -1) {
line = line.substring(0, commentIndex);
}
if (line.isEmpty()) {
continue;
}
if (line.contains(":")) {
// standard srg
parseSrgLine(line, inputTransformer, outputTransformer, reverse);
} else {
// better 'compact' srg format
parseCsrgLine(line, inputTransformer, outputTransformer, reverse);
}
}
}
/**
* Parse a 'csrg' mapping format line and populate the data structures
*/
private void parseCsrgLine(String line, MappingTransformer inputTransformer, MappingTransformer outputTransformer, boolean reverse) throws IOException {
if (reverse) {
throw new IllegalArgumentException("csrg reversed not supported"); // TODO: reverse csg (need to lookup remapped classes)
}
String[] tokens = line.split(" ");
if (tokens.length == 2) {
String oldClassName = inputTransformer.transformClassName(tokens[0]);
String newClassName = outputTransformer.transformClassName(tokens[1]);
if (oldClassName.endsWith("/")) {
// Special case: mapping an entire hierarchy of classes
// TODO: support default package, '.' in .srg
packages.put(oldClassName.substring(0, oldClassName.length() - 1), newClassName);
} else {
classes.put(oldClassName, newClassName);
}
} else if (tokens.length == 3) {
String oldClassName = inputTransformer.transformClassName(tokens[0]);
String oldFieldName = inputTransformer.transformFieldName(tokens[0], tokens[1]);
String newFieldName = outputTransformer.transformFieldName(tokens[0], tokens[2]);
fields.put(oldClassName + "/" + oldFieldName, newFieldName);
} else if (tokens.length == 4) {
String oldClassName = inputTransformer.transformClassName(tokens[0]);
String oldMethodName = inputTransformer.transformMethodName(tokens[0], tokens[1], tokens[2]);
String oldMethodDescriptor = inputTransformer.transformMethodDescriptor(tokens[2]);
String newMethodName = outputTransformer.transformMethodName(tokens[0], tokens[3], tokens[2]);
methods.put(oldClassName + "/" + oldMethodName + " " + oldMethodDescriptor, newMethodName);
} else {
throw new IOException("Invalid csrg file line, token count " + tokens.length + " unexpected in " + line);
}
}
/**
* Parse a standard 'srg' mapping format line and populate the data
* structures
*/
private void parseSrgLine(String line, MappingTransformer inputTransformer, MappingTransformer outputTransformer, boolean reverse) throws IOException {
String[] tokens = line.split(" ");
String kind = tokens[0];
if (kind.equals("CL:")) {
String oldClassName = inputTransformer.transformClassName(tokens[1]);
String newClassName = outputTransformer.transformClassName(tokens[2]);
if (reverse) {
String temp = newClassName;
newClassName = oldClassName;
oldClassName = temp;
}
if (isExcludedPackage(oldClassName)) {
SpecialSource.log("Ignored CL: " + oldClassName + " " + newClassName);
return;
}
if (classes.containsKey(oldClassName) && !newClassName.equals(classes.get(oldClassName))) {
throw new IllegalArgumentException("Duplicate class mapping: " + oldClassName + " -> " + newClassName
+ " but already mapped to " + classes.get(oldClassName) + " in line=" + line);
}
/**
* Generate a mapping given an original jar and renamed jar
*
* @param oldJar Original jar
* @param newJar Renamed jar
* @param logfile Optional .srg file to output mappings to
* @param compact If true, generate .csrg logfile instead of .srg
* @param full if true, generate duplicates
* @throws IOException
*/
public JarMapping(JarComparer oldJar, JarComparer newJar, File logfile, boolean compact, boolean full) throws IOException {
SpecialSource.validate(oldJar, newJar);
this.newJar = newJar;
PrintWriter out;
if (logfile == null) {
out = new PrintWriter(System.out);
} else {
out = new PrintWriter(logfile);
}
MappingWriter srgWriter = (compact) ? new CompactSearge(oldJar.jar.getFilename(), newJar.jar.getFilename()) : new Searge(oldJar.jar.getFilename(), newJar.jar.getFilename());
for (int i = 0; i < oldJar.classes.size(); i++) {
String oldClass = oldJar.classes.get(i);
String newClass = newJar.classes.get(i);
classes.put(oldClass, newClass); // always output class names (no duplicate check)
srgWriter.addClassMap(oldClass, newClass);
}
for (int i = 0; i < oldJar.fields.size(); i++) {
Ownable oldField = oldJar.fields.get(i);
Ownable newField = newJar.fields.get(i);
String key = oldField.owner + "/" + oldField.name;
fields.put(key, newField.name);
if (full || !oldField.name.equals(newField.name)) {
srgWriter.addFieldMap(oldField, newField);
}
}
for (int i = 0; i < oldJar.methods.size(); i++) {
Ownable oldMethod = oldJar.methods.get(i);
Ownable newMethod = newJar.methods.get(i);
String key = oldMethod.owner + "/" + oldMethod.name + " " + oldMethod.descriptor;
methods.put(key, newMethod.name);
MethodDescriptor methodDescriptorTransformer = new MethodDescriptor(null, classes);
String oldDescriptor = methodDescriptorTransformer.transform(oldMethod.descriptor);
if (full || !(oldMethod.name + " " + oldDescriptor).equals(newMethod.name + " " + newMethod.descriptor)) {
srgWriter.addMethodMap(oldMethod, newMethod);
}
}
srgWriter.write(out);
}
}
|
package nl.tudelft.ti2306.blockchain;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import nl.tudelft.ti2306.blockchain.datastructure.Interaction;
import nl.tudelft.ti2306.blockchain.datastructure.Peer;
import nl.tudelft.ti2306.blockchain.datastructure.PeerGraph;
public class Util {
/**
* Naive approach finding common ancestor. Will only return first one found.
* @return null when none found, otherwise the first found (should be lowest) common ancestor
*/
public static Interaction findCommonAncestor(final Interaction left, final Interaction right) {
// queue for bfs
Queue<Interaction> queue = new LinkedList<>();
// start somewhere
Interaction current = left;
queue.add(current);
while (!queue.isEmpty()) {
current = queue.poll();
for (Interaction parent : current.getParents()) {
if (parent != null) {
// Interaction.getParents() kan list met null items geven
queue.add(parent);
}
}
if (current.getPeer1().equals(left.getPeer1()) || current.getPeer1().equals(left.getPeer2())) {
// left is peer1
if (current.getPeer2().equals(right.getPeer1()) || current.getPeer2().equals(right.getPeer2())) {
return current;
}
} else {
// left is peer2
if (current.getPeer2().equals(right.getPeer1()) || current.getPeer2().equals(right.getPeer2())) {
return current;
}
}
}
// nothing found so far
return null;
}
public static String listToString(Collection<? extends Object> collection) {
StringBuilder out = new StringBuilder();
out.append("[");
for (Object o : collection) {
out.append(String.format("%s ", o));
}
out.append("]");
return out.toString();
}
private static List<Peer> concat(Peer p, List<Peer> path) {
ArrayList<Peer> res = new ArrayList<>();
res.add(p);
res.addAll(path);
return res;
}
public static Map<Peer, List<List<Peer>>> getAllPaths(PeerGraph pgraph, Peer source) {
return getAllPaths(pgraph, source, 0);
}
/** Returns for each Peer a List of Paths (Lists of Peers) */
public static Map<Peer, List<List<Peer>>> getAllPaths(PeerGraph pgraph, Peer source, long minTime) {
int n = pgraph.getNodes().size();
Map<Peer, List<List<Peer>>> map = new HashMap<>();
// Initialization of return Map
for (Peer p : pgraph.getNodes()) {
map.put(p, new ArrayList<>());
// If Peer p is connected to `source`
if (pgraph.getEdges(p.getId()).contains(source.getId())) {
if (p.getPrevious(source) == null)
continue;
if (p.getPrevious(source).getTimestamp() < minTime)
continue;
// If p and q ever had an interaction and the time is within bounds,
// Add an initial path from `p` to `source` to the list of paths
map.get(p).add(new ArrayList<Peer>());
map.get(p).get(0).add(p);
map.get(p).get(0).add(source);
}
}
// Dynamic programming commences! Path can be max. `n` long because we do not allow cycles
for (int i = 0; i < n - 1; i++) {
// For each Peer `p` in graph
for (Peer p : pgraph.getNodes()) {
// For all edges (p, q)
for (Integer z : pgraph.getEdges(p.getId())) {
Peer q = pgraph.getNodes().get(z);
if (p.getPrevious(q) == null)
continue;
if (p.getPrevious(q).getTimestamp() < minTime)
continue;
// If p and source ever had an interaction and the time is within bounds,
// For all currently known paths from q to source
for (List<Peer> path : map.get(q)) {
// If p is not already in the path from q to source
if (!path.contains(p)) {
// Add p to the path add the new path to the list
List<Peer> newPath = concat(p, path);
if (!map.get(p).contains(newPath))
map.get(p).add(newPath);
}
}
}
}
}
map.remove(source);
return map;
}
/**
* Only for use if you need ONE SINGLE source-dest, because it calls getAllPaths!
*/
public static double calculateTrust(PeerGraph pgraph, Peer source, Peer dest, long currTime) {
return calculateTrust(pgraph, source, getAllPaths(pgraph, source).get(dest), currTime);
}
public static double calculateTrust(PeerGraph pgraph, Peer source, List<List<Peer>> allPathsToDest, long currTime) {
double failChance = 1.0;
double pathSucceed, edgeSucceed;
Peer p, q;
Interaction last;
for (List<Peer> path : allPathsToDest) {
pathSucceed = 1.0;
for (int i = 0; i < path.size() - 1; i++) {
p = path.get(i);
q = path.get(i + 1);
last = p.getPrevious(q);
if (last == null) {
pathSucceed = 0;
break;
}
edgeSucceed = 1.0 - (currTime - last.getTimestamp()) / 100.0;
pathSucceed *= Math.max(0, edgeSucceed);
}
failChance *= 1.0 - pathSucceed;
}
return 1.0 - failChance;
}
/**
* Naive approach getting the hop count.
* When return value is 0, <tt>from</tt> has seen <tt>to</tt> himself, or they are equal.
*/
public static int getHopCount(final Peer from, final Peer to) {
return getHopCount(to, from, new HashSet<>());
}
private static int getHopCount(final Peer from, final Peer to, final Set<Peer> visited) {
if (from.seenPeers.keySet().contains(to)) {
return 0;
}
int out = -1;
for (Peer peer : from.seenPeers.keySet()) {
if (visited.contains(peer)) {
continue;
}
visited.add(peer);
int res = getHopCount(peer, to, visited) + 1;
if (out == -1 || res == -1) {
out = res;
} else {
out = Math.min(res, out);
}
}
return out;
}
}
|
package nuclibook.entity_utils;
import nuclibook.models.*;
import org.joda.time.DateTime;
import java.util.List;
/**
* A class for reading data from the staff table in the database.
*/
public class StaffUtils extends AbstractEntityUtils {
/**
* Gets the {@link nuclibook.models.Staff} object with the specified ID.
*
* @param id the <code>Staff</code> ID
* @return the associated <code>Staff</code> object
*/
public static Staff getStaff(String id) {
try {
return getStaff(Integer.parseInt(id));
} catch (NumberFormatException e) {
return null;
}
}
/**
* Gets the {@link nuclibook.models.Staff} object with the specified ID.
*
* @param id the <code>Staff</code> ID
* @return the associated <code>Staff</code> object
*/
public static Staff getStaff(int id) {
return getEntityById(Staff.class, id);
}
/**
* Gets the {@link nuclibook.models.Staff} object with the specified username.
*
* @param username the <code>Staff</code> username
* @return the associated <code>Staff</code> object with that username
*/
public static Staff getStaffByUsername(String username) {
List<Staff> matched = getEntitiesByField(Staff.class, "username", username);
if (matched == null || matched.size() != 1) {
return null;
}
return matched.get(0);
}
/**
* Gets all the {@link nuclibook.models.Staff} objects in the database.
* <p>
* Can return data only for the <code>enabled</code> fields.
*
* @param enabledOnly specifies whether the method should get only <code>enabled Staff</code> records
* @return a list of <code>Staff</code> objects
*/
public static List<Staff> getAllStaff(boolean enabledOnly) {
if (enabledOnly) {
return getEntitiesByField(Staff.class, "enabled", "1");
} else {
return getAllEntities(Staff.class);
}
}
/**
* Checks if the specified <code>username</code> already exists in the database.
*
* @param username the username to be checked
* @return true if the username already exists in the database; false otherwise
*/
public static boolean usernameExists(String username) {
return (getStaffByUsername(username) != null);
}
}
|
package org.aksw.mlbenchmark;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.aksw.mlbenchmark.exampleloader.ExampleLoaderBase;
import org.apache.commons.configuration2.BaseConfiguration;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.HierarchicalConfiguration;
import org.apache.commons.configuration2.tree.ImmutableNode;
import com.google.common.collect.Sets;
public class BenchmarkLog {
public static final String tp = "tp";
public static final String fp = "fp";
public static final String tn = "tn";
public static final String fn = "fn";
/**
* Contains
* - learning systems to run ["learningsystems"]
* - seed ["framework.seed"]
* - number of cross validation folds ["framework.crossValidationFolds"]
* - number of threads ["framework.threads"]
* - learning scenarios (e.g. suramin/1) ["scenarios"]
* - max. execution time ["framework.maxExecutionTime"]
*/
private HierarchicalConfiguration<ImmutableNode> benchmarkConfig;
/**
* Each learning system info object contains the following informations:
* - learning system ID (String)
* - config
* - language ["language"]
* - config format (either "prop" or "conf") ["configFormat"]
*
* - optional learning system settings
* - runtime config of the learning system
* - filename positive examples ('data.f')
* - filename negative examples ('data.n')
* - filename base ('data.b')
*/
private Map<String, LearningSystemInfo> lsis;
private ResultsStore results;
private String rootDir;
private String learningTasksDir;
private String learningSystemsDir;
private String tempDir;
private Map<String,Set<String>> learningProblemsCache = null;
private ConfigStore learningSystemConfigs;
public BenchmarkLog() {
lsis = new HashMap<String, LearningSystemInfo>();
learningSystemConfigs = new ConfigStore();
results = new ResultsStore();
}
public void saveBenchmarkConfig(HierarchicalConfiguration<ImmutableNode> config) {
benchmarkConfig = config;
}
public void saveDirs(String rootDir, String learningTasksDir,
String learningSystemsDir, String tempDir) {
this.rootDir = rootDir;
this.learningTasksDir = learningTasksDir;
this.learningSystemsDir = learningSystemsDir;
this.tempDir = tempDir;
}
public void saveLearningSystemInfo(String learningSystem, LearningSystemInfo lsi) {
lsis.put(learningSystem, lsi);
}
public void saveLearningSystemConfig(String learningSystem, String learningTask,
String learningProblem, int fold, String configFilePath) {
learningSystemConfigs.addConfig(learningSystem, learningTask,
learningProblem, fold, configFilePath);
}
public void saveResultSet(String learningSystem, String learningTask,
String learningProblem, int fold, Configuration res) {
results.addResult(learningSystem, learningTask, learningProblem, fold, res);
}
public Configuration getValidationResults(String learningSystem,
String learningTask, String learningProblem, int fold) {
Configuration resConfig = results.getResult(learningSystem, learningTask,
learningProblem, fold);
String prefix = learningTask + "." + learningProblem + ".fold-" +
fold + "." + learningSystem + ".ValidationRaw.";
return resConfig.subset(prefix);
}
public Set<String> getLearningTasks() {
Set<String> learningTasks = new HashSet<String>();
String[] scnenarios = benchmarkConfig.getStringArray("scenarios");
for (String scenario : scnenarios) {
String learningTask = scenario.split("/")[0];
learningTasks.add(learningTask);
}
return learningTasks;
}
public Set<String> getLearningSystems() {
return Sets.newHashSet(benchmarkConfig.getStringArray("learningsystems"));
}
public String getLearningTaskPath(String learningTask, String learningSystem) {
LearningSystemInfo lsi = lsis.get(learningSystem);
String lang = lsi.getConfig().getString("language");
return learningTasksDir + File.separator + learningTask + File.separator + lang;
}
public Set<String> getLearningProblems(String learningTask) {
if (learningProblemsCache == null) {
learningProblemsCache = new HashMap<String,Set<String>>();
for (String scenario : benchmarkConfig.getStringArray("scenarios")) {
String[] tmpParts = scenario.split("/");
String task = tmpParts[0];
String problem = tmpParts[1];
if (!learningProblemsCache.containsKey(task)) {
learningProblemsCache.put(task, new HashSet<String>());
}
learningProblemsCache.get(task).add(problem);
}
}
return learningProblemsCache.get(learningTask);
}
public Set<String> getPosExamples(String learningTask, String learningProblem,
String learningSystem, int fold) throws IOException {
return getExamples(learningTask, learningProblem, learningSystem, fold, "pos");
}
public Set<String> getNegExamples(String learningTask, String learningProblem,
String learningSystem, int fold) throws IOException {
return getExamples(learningTask, learningProblem, learningSystem, fold, "neg");
}
public int getNumFolds() {
return benchmarkConfig.getInt("framework.crossValidationFolds");
}
public Set<String> getExamples(String learningTask, String learningProblem,
String learningSystem, int fold, String posNeg) throws IOException {
String lang = lsis.get(learningSystem).getConfig().getString("language");
ExampleLoaderBase exLoader = ExampleLoader.forLanguage(lang);
String posNegFileName = "";
if (posNeg.equals("pos")) posNegFileName = lsis.get(learningSystem).getPosFilename();
else posNegFileName = lsis.get(learningSystem).getNegFilename();
String path = tempDir + File.separator + learningTask +
File.separator + learningProblem + File.separator + "fold-" +
fold + File.separator + learningSystem + File.separator +
"train" + File.separator + posNegFileName;
exLoader.loadExamples(new File(path));
return exLoader.getExamples();
}
public Configuration getLearningSystemConfig(String learningSystem,
String learningTask, String learningProblem, int fold) {
try {
return learningSystemConfigs.getConfig(learningTask, learningProblem,
learningSystem, fold).subset("main.");
} catch (ConfigLoaderException e) {
e.printStackTrace();
return new BaseConfiguration();
}
}
class ConfigStore {
Map<String, Map<String, Map<String, Map<Integer, String>>>> configPaths;
public ConfigStore() {
configPaths = new HashMap<>();
}
void addConfig(String learningSystem, String learningTask,
String learningProblem, int fold, String configFilePath) {
if (!configPaths.containsKey(learningTask)) {
configPaths.put(
learningTask,
new HashMap<String, Map<String, Map<Integer, String>>>());
}
if (!configPaths.get(learningTask).containsKey(learningProblem)) {
configPaths.get(learningTask).put(
learningProblem, new HashMap<String, Map<Integer, String>>());
}
if (!configPaths.get(learningTask).get(learningProblem).containsKey(learningSystem)) {
configPaths.get(learningTask).get(learningProblem).put(
learningSystem, new HashMap<Integer, String>());
}
configPaths.get(learningTask).get(learningProblem).get(
learningSystem).put(fold, configFilePath);
}
Configuration getConfig(String learningTask, String learningProblem,
String learningSystem, int fold) throws ConfigLoaderException {
String configFilePath = configPaths.get(learningTask).get(
learningProblem).get(learningSystem).get(fold);
return new ConfigLoader(configFilePath).loadWithInfo().config();
}
}
/*
* suramin.1.fold-0.aleph.duration
* suramin.1.fold-0.aleph.trainingRaw
* suramin.1.fold-0.aleph.trainingResult
* suramin.1.fold-0.aleph.validationResult
* suramin.1.fold-0.aleph.ValidationRaw.tp
* suramin.1.fold-0.aleph.ValidationRaw.fp
* suramin.1.fold-0.aleph.ValidationRaw.tn
* suramin.1.fold-0.aleph.ValidationRaw.fn
* suramin.1.fold-0.aleph.measure.pred_acc
*/
class ResultsStore {
Map<String, Map<String, Map<String, Map<Integer, Configuration>>>> res;
public ResultsStore() {
res = new HashMap<>();
}
void addResult(String learningSystem, String learningTask,
String learningProblem, int fold, Configuration config) {
if (!res.containsKey(learningSystem)) {
res.put(learningSystem, new HashMap<String, Map<String, Map<Integer, Configuration>>>());
}
if (!res.get(learningSystem).containsKey(learningTask)) {
res.get(learningSystem).put(learningTask,
new HashMap<String, Map<Integer, Configuration>>());
}
if (!res.get(learningSystem).get(learningTask).containsKey(learningProblem)) {
res.get(learningSystem).get(learningTask).put(learningProblem,
new HashMap<Integer, Configuration>());
}
res.get(learningSystem).get(learningTask).get(learningProblem).put(fold, config);
}
Configuration getResult(String learningSystem, String learningTask,
String learningProblem, int fold) {
Configuration result;
try {
result = res.get(learningSystem).get(learningTask).get(learningProblem).get(fold);
} catch (NullPointerException e) {
result = new BaseConfiguration();
}
return result;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.